Finding Top 3 (of anything)

by May 12, 2016

Ever wanted to know who are the three worst sources for errors in your System event log? Here is a simple approach that yields the source names with the most errors:

Get-EventLog -LogName System -EntryType Error | 
  Group-Object -Property Source |
  Sort-Object -Property Count -Descending |
  Select-Object -First 3 -Property Count, Name

Key is the use of Group-Object: this cmdlet groups items by a property. All error events are grouped by source. Next, the groups are sorted by size, and the three largest groups are returned.

This works with many things. Here are the top 3 file types in your Windows folder (add -Recurse to search the entire tree):

Get-ChildItem -Path $env:windir | 
  Group-Object -Property Extension -NoElement | 
  Sort-Object -Property Count -Descending | 
  Select-Object -First 3

And these are the three most frequent numbers in a series of numbers:

$numbers = for ($x = 1 $x -lt 1000 $x++) 
  Get-Random -Minimum 1 -Maximum 7

$numbers | 
  Group-Object | 
  Sort-Object -Property Count | 
  Select-Object -First 3 -ExpandProperty Name

Twitter This Tip! ReTweet this Tip!