Skip to content

Why does Add-Content require a read lock when appending to files? #5924

@latkin

Description

@latkin

I (and various customers of my company) notice that Add-Content often fails to append to files with an error like:

Add-Content : The process cannot access the file
'C:\Users\Administrator\logs\access_log.log' because it is being used by another process.

This happens if the file in question is being read ("tailed") by some other process at the same time, e.g. a log collection framework.

I confirmed via ProcMon that this is because Add-Content takes a read lock on its target file. So if the file is already open for read by another process (even if that process has taken no locks), the cmdlet will fail.

This is unexpected. Why does a writing cmdlet need a read lock? Out-File -Append does essentially the same thing and takes no such lock. Others are confused as well: https://stackoverflow.com/questions/30733610/get-content-wait-is-locking-the-file-while-it-reads-it-preventing-add-content, https://stackoverflow.com/questions/10655788/powershell-set-content-and-out-file-what-is-the-difference

As far as I can surmise the relevant bit of code is here (FileSystemProvider.GetContentWriter):

stream = new FileSystemContentReaderWriter(path, streamName, filemode, FileAccess.Write, FileShare.Write, encoding, usingByteEncoding, false, this, false, suppressNewline);

Could FileShare.Write be changed to FileShare.ReadWrite?

This applies to both Windows PowerShell and PowerShell Core

Metadata

Metadata

Assignees

Labels

Issue-BugIssue has been identified as a bug in the productResolution-FixedThe issue is fixed.WG-Cmdlets-Managementcmdlets in the Microsoft.PowerShell.Management module

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions