Tail a File in PowerShell
In my limited Linux administration experience I got used to dealing with text. Text documents that held configuration files, text manipulation in the pipeline, text everywhere. Every search was just a grep away.
When troubleshooting in Linux you’re constantly reading log files. Checking for changes and seeing if your what you’re flushing comes out the correct pipe. A tool that made the job easier was the tail command with the -f argument. This allows you to follow whatever is appended to the file in question. You could now navigate to your webpage and see the apache access.log file written to in real-time. I always wanted something like that in Windows.
Get-Content
That is where Get-Content comes into play. Normally, Get-Content retrieves whatever is in your file, line by line. That’s useful for piping computer names into another function.
Get-Content Computers.txt | Get-RebootingPendingStatus
You can also use Get-Content -Raw to work with the entire file at once. Maybe you’re running a Regular Expression against an HTML file (ewwww I know) and line by line doesn’t cut it. For that, the raw option is available.
We, however, are interested in the -Tail parameter (I wonder where Microsoft got the name for that?!!?!) along with the -Wait parameter. Imagine the following example:
$FilePath = "~\Desktop\Tail.txt"
1..100 | ForEach-Object {
"echo $_" | Out-File $FilePath -Append
Start-Sleep -Seconds 2
}
I know this is a bit contrived but this example will generate text to the tail.txt file located on your desktop. We add Start-Sleep so we have time to fire up Get-Content. When you run this the For each loop will run 100 times and will echo the loop counter to the tail file. Run this then open up ANOTHER PowerShell window. You should begin to see the results trickle in.
PS:\> Get-Content ~\Desktop\Tail.txt -Tail 10 -Wait
echo 1
echo 2
echo 3
echo 4
echo 5
echo 6
echo 7
echo 8
echo 9
echo 10
echo 11
echo 12
echo 13
echo 14
echo 15
This will show the last 10 lines and wait for any more that get appended. Ctrl+C a couple times breaks out of the wait loop.
This example could have easily been an application install trace, an IIS log, or the markdown file I used to write this post!