Get-Content -Wait 在读取文件时锁定文件,防止 Add-Content 写入数据

Get-Content -Wait is locking the file while it reads it, preventing Add-Content from writing data

我正在使用 powershell 写入和读取日志文件。

一个脚本正在生成一个带有 Add-Content 的日志文件。另一个脚本使用 Get-Content -Wait 跟踪日志文件。这个好像应该是挺靠谱的。

但是,作者经常写不出来,而reader经常看不懂而放弃。我只能假设这两个命令没有使用适当的访问标志打开文件,所以他们在互相争斗。

这是一个讨厌的小脚本,它演示了同一进程中两个作业的问题,尽管在不同的 powershell 进程之间也会发生同样的问题:

$writer = start-job -ScriptBlock {     
    foreach($i in 1..500)
    {
        "$i" | Add-Content "c:\temp\blah.txt"
        Sleep -Milliseconds 10
    }
}

$reader = start-job -ScriptBlock { 
    Get-Content "c:\temp\blah.txt" -wait
}

while($writer.State -eq "Running")
{
    Sleep 1
}
Sleep 2

"Checking writer"
receive-job $writer

"Checking reader"
receive-job $reader

remove-job $writer -force
remove-job $reader -force

在我的 Windows 带有 powershell 3 ISE 的 7 x64 机器上,我通常会遇到很多写入错误:

Checking writer
The process cannot access the file 'C:\temp\blah.txt' because it is being used by another process.
    + CategoryInfo          : ReadError: (C:\temp\blah.txt:String) [Get-Content], IOException
    + FullyQualifiedErrorId : GetContentReaderIOError,Microsoft.PowerShell.Commands.GetContentCommand
    + PSComputerName        : localhost

然后正在读取的文件中有间隙:

Checking reader
...
23
24
25
54
55
56
...

注意,这是一个与此处讨论的问题不同的问题:Get-Content -wait not working as described in the documentation and here: https://social.technet.microsoft.com/Forums/windowsserver/en-US/e8ed4036-d822-43d3-9ee5-dd03df3d9bfc/why-doesnt-wait-work-and-why-doesnt-anyone-seem-to-care?forum=winserverpowershell 这是关于拖尾一个在两次写入之间未关闭的文件。

有没有像这样使用 Get-Content 和 Add-Content 的方法,或者我应该放弃,并使用其他东西来读写我的日志文件?

尝试使用 Out-File 而不是 Add-Content

替换

Add-Content "c:\temp\blah.txt"

与:

Out-File "c:\temp\blah.txt" -Append -Encoding ascii

如果您需要的话,您需要使用 Out-File 将编码指定为 ascii,因为它是 add-content 的默认设置,而不是 out-file 的默认设置。您还需要使用 -append and/or -noclobber 来避免覆盖现有文件内容。