Sorting Tricks (Part 4)

by Jul 2, 2021

In the previous tip we showed that Sort-Object accepts property names, hash tables or plain script blocks to sort things, and we used script blocks to control the sort algorithms, and sort string information by date and time, not alphanumerical.

In this final example, let’s use this to sort IPv4 addresses. By default, Sort-Object treats them as plain text and uses alphanumeric sorting:

 
PS> '10.12.11.1', '298.12.11.112', '8.8.8.8' | Sort-Object
10.12.11.1
298.12.11.112
8.8.8.8 
 

To correctly sort IPv4 addresses, you can cast them to the [version] type which also consists of four numbers:

 
PS> '10.12.11.1', '298.12.11.112', '8.8.8.8' | Sort-Object -Property { $_ -as [version] }

8.8.8.8
10.12.11.1
298.12.11.112     
 


Twitter This Tip! ReTweet this Tip!