Powershell: Why does Add-Content require a read lock when appending to files?

Created on 17 Jan 2018  路  5Comments  路  Source: PowerShell/PowerShell

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):

https://github.com/PowerShell/PowerShell/blob/4bc52d2358222084738157a08907fac32d13bd3a/src/System.Management.Automation/namespaces/FileSystemProvider.cs#L6808

Could FileShare.Write be changed to FileShare.ReadWrite?

This applies to both Windows PowerShell and PowerShell Core

Area-Cmdlets-Management Issue-Bug Resolution-Fixed

Most helpful comment

I don't see any inherent problem with changing it to FileShare.ReadWrite. I'll submit a PR.

All 5 comments

+1 We see the same issue.

One more

Agreed. Very annoying. This needs to be fixed.

Could really use the ability to tail logs without having to use workarounds.
Here is a nice work around [string]$myString >> $myLogFile

I don't see any inherent problem with changing it to FileShare.ReadWrite. I'll submit a PR.

Was this page helpful?
0 / 5 - 0 ratings