Tuesday, November 6, 2007

PowerShell to report top 10 results from log file

Ever want to sift through a log file and report on the top 10 occurances of a certain field value? Here is a PowerShell script that will do just that.

I had a log file that contained an IP address in the third field (column index 2 since arrays start at zero in PowerShell). I wanted to know what were the top 10 IPs that were logs. I could call this script like:

./ipcount.ps1 logfile.log 2

When using huge log files, don't forget if you want to redisplay, but not recompute, the results, you can "dot source" the script like:

. ./ipcount.ps1 logfile.log 2

Then $result will always hold the last set of results. Here is the script (3 lines...middle line is really long):

param($file,$index)

$result = gc $file | foreach {$hash=@{}}{$hash[$_.split(',')[[int]$index]] += 1}{$hash.getenumerator()} | sort value -desc | select -first 10

$result

No comments:

Can't RDP? How to enable / disable virtual machine firewall for Azure VM

Oh no!  I accidentally blocked the RDP port on an Azure virtual machine which resulted in not being able to log into the VM anymore.  I did ...