Sort PowerShell Results in both Ascending and Descending Order

A few weeks ago I was trying to figure out how to sort something in PowerShell with one property sorted descending and another one ascending. How to accomplish this was hiding in plain sight in the help examples for Sort-Object, but I thought I would documented it here for future reference.

Use the Property parameter with a hash table to specify the property names and their sort orders.

Get-Service -Name Win* |
Sort-Object -Property @{
    expression = 'Status'
    descending = $true
}, @{
    expression = 'DisplayName'
    descending = $false
}

sort-multiple-orders1a.jpg

This same command can be written on one line.

Get-Service -Name Win* | Sort-Object -Property @{expression = 'Status';descending = $true}, @{expression = 'DisplayName';descending = $false}

sort-multiple-orders2a.jpg

It can also be shortened with aliases and positional parameters if you’re running this in the console and don’t plan to share or save it.

gsv Win* | sort @{e='Status';desc=$true},@{e='DisplayName';desc=$false}

sort-multiple-orders3a.jpg

Technically, it doesn’t appear that you even have to specify Descending = $false as that’s the default sort order.

gsv Win* | sort @{e='Status';desc=$true},DisplayName

sort-multiple-orders4a.jpg

You should of course use full cmdlet and parameter names in any command that you share or save.

ยต