I use powershell to write and read log files.
One script creates a log file with add-content. Another script closes the log file using Get-Content -Wait. It seems to be pretty reliable.
However, a writer often cannot write, and a reader often cannot read and give up. I can only assume that these two teams do not open the file with the corresponding access flags, and therefore they fight each other.
Here's a nasty little script that demonstrates a problem with two jobs in the same process, although the same thing happens between different powershell processes:
$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
On my Windows 7 x64 machine with powershell 3 ISE, I usually get a lot of write errors:
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
And then the readable file has spaces in it:
Checking reader ... 23 24 25 54 55 56 ...
NB is another issue for the one being discussed here: Get-Content -wait does not work 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 , which relate to closing a file that does not close between entries.
Is there any way to use Get-Content and Add-Content like this, or should I give up and use something else to read and write log files?