Skip to content

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

Closed

Description

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

Activity

  1. added
    Issue-Question
    on Jan 17, 2018
  2. yangl900 commented on Aug 9, 2018

    @yangl900

    +1 We see the same issue.

  3. fonta commented on Sep 22, 2018

    @fonta

    One more

  4. mbwmbw1337 commented on Oct 18, 2018

    @mbwmbw1337

    Agreed. Very annoying. This needs to be fixed.

  5. cpumanaz commented on Oct 19, 2018

    @cpumanaz

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

  6. SteveL-MSFT commented on Oct 20, 2018

    @SteveL-MSFT
    Member

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

  7. added
    Issue-Bug
    Resolution-Fixed
    and removed
    Issue-Question
    on Oct 24, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Issue-BugResolution-FixedWG-Cmdlets

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions