Advanced Sorting (Part 1)

by Nov 1, 2021

Sort-Object easily sorts results for you. For primitive data such as numbers or strings, simply add Sort-Object to your pipeline. This gets you a sorted list of lottery numbers:

$lottery = 1..49 | Get-Random -Count 7 | Sort-Object
# set the string you want to use to separate numbers in your output
$ofs = ','
"Your numbers are $lottery"

Object data with multiple properties requires you to define the property you want to sort. This line sorts services by status:

Get-Service | Sort-Object -Property Status

Sort-Object even supports multiple sorts. This line sorts services by status, then sorts by service name:

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

To reverse sort order, add the -Descending switch parameter.

For more control over sorting, for example, sorting one property ascending and another property descending, see our next tip.

Twitter This Tip! ReTweet this Tip!