Skip to content

Sort ip adresses

2011/02/17

When you have a list of ip addresses and you want to sort them the following “trick” found on powershell.com can be used:

IP addresses consist of four numbers seperated by dots xxx.yyy.zzz.sss . They can be casted to a System.Version type where

xxx becomes the Major

yyy becomes Minor

zzz becomes the Build

and sss becomes Revision

System.Version types are sorted first by Major then by Minor, then by the Build and last by the revision.

After that sort you can cast it back to string which adds the dots again

See

$ipliste = "192.168.10.1", "192.168.10.8", "192.168.10.24"
$ipliste | sort

This gives the “wrong” sequence
192.168.10.1
192.168.10.24
192.168.10.8

See the casting to System.Version

$ipliste | %{[System.Version] $_}
Major  Minor  Build  Revision
-----  -----  -----  --------
192     168     10     1
192     168     10     24
192     168     10     8
And when you sort them
$ipliste | %{[System.Version] $_} | sort
Major  Minor  Build  Revision
-----  -----  -----  --------
192     168     10     1
192     168     10     8
192     168     10     24

Last the re-casting to string

$ipliste | %{[System.Version] $_} | sort | %{[System.String] $_}
192.168.10.1
192.168.10.3
192.168.10.230
Advertisements

From → basics, powershell

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: