Sorting IP Addresses

by Feb 2, 2011

Sorting or comparing IP addresses won't initially work because PowerShell uses alphanumeric comparison. However, you can compare or sort them correctly by casting IP addresses temporarily to the type System.Version:

$iplist = "10.10.10.1", "10.10.10.3", "10.10.10.230"

"Not sorted correctly:"
$iplist | Sort-Object

"Sorted correctly:"
$iplist |
ForEach-Object { [System.Version] $_ } |
Sort-Object |
ForEach-Object { $_.toString() }

Twitter This Tip!
ReTweet this Tip!