Monday, August 13, 2012

Get-Content -wait and Set-Content incompatibility

Under Powershell, there is a cmdlet named 'Set-Content' which is used to replace the content of a text file with something else. And under Powershell 3.0 there is the possibility to tail a file by using the well known cmdlet 'Get-Content' with the option '-wait'.

When reading the help file for 'Set-Content', it states that:

"The Set-Content cmdlet is a string-processing cmdlet that writes or replaces the content in the specified item, such as a file. Whereas the Add-Content cmdlet appends content to a file, Set-Content replaces the existing content. You can type the content in the command or send content through the pipeline to Set-Content."

The truth is that 'Set-Content' deletes the original file and creates a new one.

If by any chance you are having a look at the same file with 'Get-Content -wait', you will get this error here:

Get-Content : The process cannot access the file 'C:\file1.log' because it is being used by
another process.
At line:1 char:1
+ Get-Content C:\file1.log -wait| ?{$_ -like "*com* ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ReadError: (C:\file1.log:String) [Get-Content], IOException
    + FullyQualifiedErrorId : GetContentReaderIOError,Microsoft.PowerShell.Commands.GetContentCommand

As you can see this error message doesn't help you to understand where the problem could lie.

The bad news is that there is no solution to this for me. The only thing that I could invent to work around this issue and that works well, is to use 'Set-Content' to write into a buffer text file, use 'Add-Content' to append the buffer text file to the text file that I am monitoring with 'Get-Content -wait' and then remove the buffer log file with 'Remove-Item -force'.

This way 'Get-Content' will never loose grip on the monitored text file.

Hope this might help someone.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...