February PowerShell One-Liner

If you subscribe to the SAPIEN newsletter you should have seen this already. If not, why don’t you take a moment to subscribe? Create an account at my.SAPIEN.com and you’ll automatically be subscribed. Each month you’ll get all the latest product and training news from SAPIEN Technologies as well as useful tips like this Powershell one-liner that produces a report on event log sizes for multiple computers.

This is a single line PowerShell expression, although you could easily insert it into a script file to save some typing. I’ve inserted line breaks using the escape character (`) to make this easier to read.

Get-Content c:\computers.txt  | where {($_.Trim()).length -gt 0} | foreach { 
 Get-WmiObject Win32_NTEventLogFile -computer $_.Trim() `
 -filter "NumberOfRecords > 0" | Select-Object `
 @{Name="Computername";Expression={$_.CSName}},LogFileName,NumberOfRecords,`
 @{Name="Size(KB)";Expression={$_.FileSize/1kb}},`
 @{Name="MaxSize(KB)";Expression={($_.MaxFileSize/1KB) -as [int]}}, `
 @{name="PercentUsed";Expression={"{0:P2}" -f ($_.filesize/$_.maxFileSize)}}
} |  Sort Computername  | Format-Table -GroupBy Computername `
-property LogFileName,NumberOfRecords,*Size*,PercentUsed
 

This expression will go through all the computer names in C:\computers.txt. Each string is validated by Where-Object which strips out any surrounding spaces and only sends on strings with a length greater than 0.  This weeds out blank lines. Each computer name is then passed to ForEach-Object which uses Get-WmiObject to query the Win32_NTEventLogFile, looking for event logs with more than 0 entries.

feb09OneLinerCaptureEach event log is then passed to Select-Object which creates a custom object for the computer, defining properties for name, size and maximum size in KB and a percentage used. These results are piped to Sort-object which sorts on the computername property. Finally output is piped to Format-Table which groups the output by computername and prepares a formatted report.

I ended the expression by creating a report, which you could have further sent to a file using Out-File or directly to a printer using Out-Printer. Or perhaps instead of a formatted report, you could have created an HTML report using ConvertTo-HTML. The point is that PowerShell’s pipeline is flexible and versatile.

If you are new to PowerShell looking for a resource, take a look at Windows PowerShell v1.0: TFM 2nd Edition. Also keep an eye on the blog for announcements regarding PowerShell training this year. Finally, if you need help with this one-liner or any PowerShell question, please join the discussion at ScriptingAnswers.com.

If you want to try this one-liner out, download it here.