Rybski.be

Font Size

Layout

Menu Style

Cpanel

Sorting IP Addresses with Powershell

Recently I had to sort a list of IP addresses with Powershell. This can be a bit tricky because the IP addresses get treated as strings which might give the wrong results. In an internet forum post I found a clever way to sort IP addresses in Powershell.

Consider the following example:

PS C:\> $list = "197.1.1.1", "10.1.1.1", "20.1.1.1"

PS C:\> $list
197.1.1.1
10.1.1.1
20.1.1.1

PS C:\> $list | sort
10.1.1.1
197.1.1.1
20.1.1.1

As you can see, the addresses are sorted incorrectly. The address 197.1.1.1 is put before 20.1.1.1 which is not the result we're after.

Keith Hill, a Powershell MVP, mentions in his post on vistax64.com a clever way to sort lists of IP addresses correctly:

$list | %{"{0:000}.{1:000}.{2:000}.{3:000}" -f @([int[]]$_.split('.'))} | sort | %{"{0}.{1}.{2}.{3}" -f @([int[]]$_.split('.'))}
10.1.1.1
20.1.1.1
197.1.1.1

This is what we want, 20 before 197.

Basically, the addresses are split into four parts, leading zeroes are added and then sorted correctly. The leading zeroes are removed at the end of the command. Rather new for me was the –f operator which is used to format. More information about the –f operator can be found on this website.

You are here: Home Articles Powershell Sorting IP Addresses with Powershell