Expanding Group Results

by May 4, 2009

Group-Object is perfect for grouping objects based on one or more properties. Once you group objects, you can then filter, or sort, based on their frequency. The following line returns all running software grouped by company name and sorted by frequency:

Get-Process |
Group-Object Company |
Where-Object { $_.Name -ne '' } |
Sort-Object Count -descending

The actual programs in each Group can be found in the Group property as they are wrapped as an array now. You may not be aware that Select-Object can take the array content of a property and expand it. What happens here is that for each element in that array, a new object is created. So you can use Group-Object to sort and filter, then re-expand the Groups to get back the original process list:

Get-Process |
Group-Object Company |
Where-Object { $_.Name -ne '' } |
Sort-Object Count -descending |
Select-Object -expandProperty Group |
Format-Table Company, Name

You may argue that you could have gotten the same result without Group-Object and -expandProperty, simply by sorting on Company like this:

Get-Process |
Where-Object { $_.Company -ne $null } |
Sort-Object Company -descending |
Format-Table Company, Name

The difference is that with Group-Object, you get the opportunity to sort on frequency, outputting the company with the most used software first, whereas a simple sort could have only sorted alphabetically.