Advanced Sorting (Part 2)

by Nov 3, 2021

Sort-Object supports advanced sorting and provides much more control when you submit a hash table. The hash table can for example control sort direction individually for multiple properties.

For example, this line sorts services by status, then by name. Sort direction can be controlled via the -Descending switch parameter but always applies to all chosen properties:

Get-Service | Sort-Object -Property Status, DisplayName | Select-Object -Property DisplayName, Status 

Get-Service | Sort-Object -Property Status, DisplayName -Descending | Select-Object -Property DisplayName, Status

To control sort direction individually, submit a hash table and use the Expression and Descending keys. This sorts services first by status (descending), then by display name (ascending):

Get-Service | 
Sort-Object -Property @{Expression='Status' Descending=$true}, @{Expression='DisplayName' Descending=$false } | 
Select-Object -Property DisplayName, Status 

Note: when you look at the results, you may be irritated by the way how the content of the property “Status” is sorted. Even though the code asked for descending sort, you first see running services, then stopped services.

The simple answer to this problem is: you now know how to control sorting individually, so if the sorting is in wrong order, simply try and reverse the sort order to see if that works for you.

The in-depth answer is: the “Status” property really is a numeric constant, and Sort-Object always sorts the underlying data. Sort order is therefore correct as you can see when you make the numeric constant visible:

Get-Service | 
Sort-Object -Property @{Expression='Status' Descending=$true}, @{Expression='DisplayName' Descending=$false } | 
Select-Object -Property DisplayName, { [int]$_.Status } 

As you now can see, “Running” is really the constant “4”, whereas “Stopped” is represented by the constant 1.

Don’t miss our next tip for even more control (and an elegant fix for the problem caused by underlying numeric constants).


Twitter This Tip! ReTweet this Tip!