Accessing Latest Log File Entries

by Apr 26, 2013

Sometimes you may just be interested in the last couple of entries in a log file. Here’s a simple yet fast way of outputting only the last x lines from a text log:

# Show last 5 lines of windowsupdate.log file
$logs = Get-Content -Path $env:windir\windowsupdate.log -ReadCount 0
$logs[-5..-1]

This example would return only the last (newest) five lines from the windowsupdate.log file.

It’s pretty fast because Get-Content uses –ReadCount 0, reading in even large text files very fast. The result is a text array with the text lines read in. In the example, only the last 5 lines are output (index -5 through -1). However, $logs will hold the complete log file content which may take considerable memory. So in PowerShell 3.0, there is a more efficient approach:

# Show last 5 lines of windowsupdate.log file
Get-Content -Path $env:windir\windowsupdate.log -ReadCount 0 -Tail 5

Here, only the number of lines specified with –Tail are returned, so there is no need for a text array to store all the other text lines found in the log file.

Twitter This Tip! ReTweet this Tip!