Say we have a list of IP-Addresses like this:
$IPaddresslist = @(
'1.2.3.4'
'220.2.240.250'
'20.30.40.50'
'3.5.7.9'
'220.230.240.250'
)
The result of a normal sort is:
$IPaddresslist | Sort-Object
1.2.3.4
20.30.40.50
220.2.240.250
220.230.240.250
3.5.7.9
That’s a nice alphabetical sort but not really what you want for IP-Addresses.
So how do we solve this problem?
IP-Addresses, like version numbers, consist of four groups of numbers seperated by a dot.
So if we treat an IP-Adress as if it was a version number we can do this:
$IPaddresslist | Sort-Object -Property { [version]$_ }
1.2.3.4
3.5.7.9
20.30.40.50
220.2.240.250
220.230.240.250
But an IP Adress is not a version number, so is there another way to do this?
Yes there is, we can use [ipaddress] instead of [version], When using the Address property it has the same effect and is much clearer in the code because everyone can understand what it means.
$IPaddresslist | Sort-Object -Property { ([ipaddress]$_).Address }
1.2.3.4
3.5.7.9
20.30.40.50
220.2.240.250
220.230.240.250
As you can see we now have a perfectly sorted list of IP-Addresses.
Leave a Reply