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
):
Could FileShare.Write
be changed to FileShare.ReadWrite
?
This applies to both Windows PowerShell and PowerShell Core
+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.
Most helpful comment
I don't see any inherent problem with changing it to FileShare.ReadWrite. I'll submit a PR.