PowerShell Sort-Object and -GroupBy

It's so much easier to read a list when the columns are sorted into a meaningful order.  As PowerShell interprets a script, so it often has to deal with raw data which is not sequenced either numerically or alphabetically.  Consequently, a good programmer will add an instruction to sort or group the columns on the most important property.

Topics for PowerShell Sort-Object Cmdlet

 ♣

Example 1: Rank on DisplayName by Using Sort-Object

To this day, I still have trouble finding certain Windows services, for example, where in the list is the firewall?  Why can't I find the print spooler under the letter 'P'?   My memory and experience tell me these services are there somewhere, but what does Microsoft call them?  The answer is to focus not on 'Name', but 'DisplayName' and then apply Sort-Object to this property.

Before we start experimenting with sorting and grouping the output, let me introduce the cmdlet which will be the vehicle for our study, namely: Get-Service.  Incidentally, the nouns in PowerShell's cmdlets are always singular hence service (and not serviceS).

# PowerShell Sort-Object Examle
Get-Service | Sort-Object DisplayName

Note 1:  If you disregard PowerShell's pipe (|) then Sort-Object won't work.  The idea is that we get a raw list of services and then squirt them into the Sort-Object cmdlet; naturally, we provide the name of the property that is going to act as the primary key for our sort, in the above example we will use DisplayName.

Note 2:  You can abbreviate Sort-Object to plain sort thus: Get-Service | Sort displayName

Background Research with Get-Member

Never miss an opportunity to run Get-Member (gm) against any cmdlet that you are studying.  In the case of Get-Service, preceding it with Get-Member reveals interesting properties that we can use for sorting, such as 'DependentServices', 'ServiceDependsOn' and CanStop.  Do remember the pipe symbol thus:

Get-Service | Get-Member

Note 3: This is merely a digression to find suitable properties for sorting.

Guy Recommends: Free WMI Monitor for PowerShellSolarwinds Free WMI Monitor for PowerShell

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft's operating systems.  Fortunately, SolarWinds have created a Free WMI Monitor so that you can discover these gems of performance information, and thus improve your PowerShell scripts.

Take the guess work out of which WMI counters to use when scripting the operating system, Active Directory, or Exchange Server. Give this WMI monitor a try - it's free.

Download your free copy of WMI Monitor

Example 2: Sort-Object with Format-Table and -GroupBy

Armed with information from Get-Member about the additional properties of Windows services, we need a method of selecting the names and position of these extra columns in the output, for this we append the Format-Table cmdlet.  Once again, this example illustrates how piping the output of the first command, becomes the input of the second section, and then onwards into the script's third element.  I find it helpful to think of successive pipes as refining the output.

The key to understanding -GroupBy is to realize that it's a parameter, which is associated with Format-Table (and other sister cmdlets).  There are two minor traps with -GroupBy, firstly understand how it differs from Sort-Object.  Secondly, appreciate that -GroupBy is a parameter different from the group-Object cmdlet.

# PowerShell Sort-Object Example
Clear-Host
Get-Service | Sort-Object Status, DisplayName `
| Format-Table DisplayName, CanStop, Status -groupBy status -auto

Note 4: There is a lot going on in the above example.  Realize that we can sort on more than one property, firstly Status and secondly DisplayName.  Also observe how this example does not just sort, but also groups the services into those which are running and those which are stopped.

Make my day:  Choose different properties for Format-Table.  Also experiment with omitting Status from the Sort-Object pipe and appreciate how messy the output gets when you don't sort on the property that you also want to group.

One more challenge:  Which cmdlet supports -auto?  Try putting Get-Help before Get-Service.  Now try help before Format-Table.  Any sign of -AutoSize?   My not-so-hidden agenda is to encourage you to research the full list of parameters available to the cmdlets that you are using.

Engineer's Toolset v10Guy Recommends: SolarWinds Engineer's Toolset v10

This Engineer's Toolset v10 provides a comprehensive console of 50 utilities for troubleshooting computer problems.  Guy says it helps me monitor what's occurring on the network, and each tool teaches me more about how the underlying system operates.

There are so many good gadgets; it's like having free rein of a sweetshop.  Thankfully the utilities are displayed logically: monitoring, network discovery, diagnostic, and Cisco tools.  Try the SolarWinds Engineer's Toolset now!

Download your fully functional trial copy of the Engineer's Toolset v10

Researching Sort-Object Parameters

Clear-Host
Get-Help Sort-Object -full

Note 5: This command reveals useful parameters such as -Descending and -Unique

Clear-Host
Get-ChildItem -path "C:\windows\" | Sort-Object length -descending

Note 6: The default sequence is ascending, so just remove the -descending parameter and see how the files are sorted.

Find More PowerShell 'Object' Cmdlets

Clear-Host
Get-Command -Noun object

As a result of this knowledge you can refine the output of a where clause by piping it into a Sort-Object statement.

Summary of Windows PowerShell's Sort-Object and -GroupBy

For the user, sorting and grouping data make raw data that bit easier to read.  For the programmer, ranking the output gives satisfaction and a sense of a job well done.  In terms of learning PowerShell, the secret is to understand the difference between the cmdlet Sort-Object and the parameter -GroupBy.  As usual, Get-Member and Get-Help... -full have crucial role in researching the full power of any cmdlet that you employ.

If you like this page then please share it with your friends

 


See more PowerShell examples of 'Object' cmdlets

PowerShell Tutorials  • Syntax  • PowerShell Where-Object  • Foreach-Object  • Free WMI Monitor

  • New-Item  • Remove-Item  • ItemProperty  • PowerShell New Object   • Sort-Object   • Group-Object

PowerShell Splatting  • Select-String  • -replace string  • Compare-Object  • Measure-Object

Please email me if you have a better example script. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.

 

 *


Custom Search

Site Home

Guy Recommends: WMI Monitor for PowershellSolarwinds WMI Monitor

Windows Management Instrumentation (WMI) is most useful for PowerShell scripting.

SolarWinds have produced this Free WMI Monitor to take the guess work out of which WMI counters to use for applications like Microsoft Active Directory, SQL or Exchange Server.

Download your free copy of WMI Monitor

Author: Guy Thomas Copyright © 1999-2017 Computer Performance LTD All rights reserved.

Please report a broken link, or an error to: