Sorting Tricks (Part 1)

by Jun 24, 2021

Sort-Object is your cmdlet to sort things: simply specify the property you like to sort, and Sort-Object covers the rest, including picking the correct sort algorithm based on the property data type:

Get-Service | Sort-Object -Property DisplayName -Descending 
  1. A lesser-known fact is that Sort-Object also accepts hash tables which gives you more control. For example, you can easily sort multiple properties like this:
Get-Service | Sort-Object -Property Status, DisplayName -Descending 

If you want to control the sort direction per property, though, you need a hash table. This example sorts the status in descending order, but the display name in ascending order:

$displayName = @{
    Expression = "DisplayName"
    Descending = $false

Get-Service | Sort-Object -Property Status, $displayName -Descending

Twitter This Tip! ReTweet this Tip!