Tail using PowerShell

Consider a scenario where you are diagnosing an issue on a production server. You've enabled the logs and got everything setup to reproduce the issue. Queue the trigger to invoke the misbehaving operation and finally wait for the log file to update.

Staring at the log file size to change is no fun nor is refreshing the file periodically. I want to be notified the moment the log gets updated in real-time. This is exactly what a program like tail does - it monitors the file for changes and outputs the tail end of the file.

There are a few incarnations of tail out there that do the job perfectly fine, but given that this was a production environment I was not keep about installing new tools.

Luckily, the Get-Content PowerShell cmdlet has this functionality built-in. This is the combo that I finally settled on:

Get-Content log.txt -tail 5 -wait

The -tail argument takes in the number of lines to show from the end of the file and -wait specifies that it should continue to monitor the file.

Granted that this method does not have highlighting capabilities that a dedicated tool would have, but its a pretty useful option to have in a pinch.

Finally, save a few key strokes by using the alias:

cat log.txt -tail 5 -wait

Update 2019-01-30: I recently had the requirement to monitor a file for some text and then note the timestamp of when it was written. It is based off of this suggested solution.

cat .\processed-users.txt -tail 5 -wait | ? { $_ -like 'SEARCH_STRING_HERE' } | % { Write-Host $(Get-Date -Format T) -noNewLine -ForegroundColor Blue; Write-Host " $_" }


comments powered by Disqus