Sort Things with Type

by Mar 17, 2015

All Versions

Sort-Object is your one-stop solution for sorting. If it’s primitive data, simply pipe it to Sort-Object. If it is object data, specify the property you want to use for sorting:

# sorting primitive data
1,5,2,1,6,3,12,6 | Sort-Object -Unique

# sorting object data
Get-ChildItem -Path c:\windows | Sort-Object Property name

Because of the object nature, PowerShell automatically picks the correct sorting algorithm. But what if you want more control?

Simply submit a script block. Inside of it, $_ represents the object that is being sorted. You can now cast it to any type you want:

# sorting string as numbers
'1','5','3a','12','6' | Sort-Object -Property { $_ -as [int]  }

# sorting IPv4 addresses as versions
'1.2.3.4', '10.1.2.3', '100.4.2.1', '2.3.4.5', '9.10.11.12' | 
  Sort-Object -Property { [version] $_ }

Twitter This Tip! ReTweet this Tip!