ben*_*ben 5 powershell powershell-3.0
我正在使用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
Run Code Online (Sandbox Code Playgroud)
在使用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
Run Code Online (Sandbox Code Playgroud)
然后正在读取的文件中有空白:
Checking reader
...
23
24
25
54
55
56
...
Run Code Online (Sandbox Code Playgroud)
注意这是与此处讨论的问题不同的一个问题:Get-Content -wait无法按照文档和此处的说明进行操作: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"
Run Code Online (Sandbox Code Playgroud)
和:
Out-File "c:\temp\blah.txt" -Append -Encoding ascii
Run Code Online (Sandbox Code Playgroud)
如果您想要的话,您需要使用 Out-File 将编码指定为 ascii,因为它是 add-content 的默认编码,但不是 out-file 的默认编码。您还需要使用 -append 和/或 -noclobber 以避免覆盖现有文件内容。
| 归档时间: |
|
| 查看次数: |
2068 次 |
| 最近记录: |