【发布时间】:2015-06-09 13:35:19
【问题描述】:
我正在使用 powershell 来写入和读取日志文件。
一个脚本正在使用 Add-Content 生成一个日志文件。另一个脚本正在跟踪日志文件,使用 Get-Content -Wait。这似乎应该是相当可靠的。
但是,作者经常写不出来,读者也经常看不懂而放弃。我只能假设这两个命令没有使用适当的访问标志打开文件,因此它们相互争斗。
这是一个令人讨厌的小脚本,它演示了同一进程中的两个作业的问题,尽管在不同的 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
在装有 powershell 3 ISE 的 Windows 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 和此处: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,还是我应该放弃,用别的东西来读写我的日志文件?
【问题讨论】: