Intellectually sort IP addresses w/PowerShell

Cover

Did you try some day to sort IP addresses by embedded PowerShell cmdlet Sort-Object?

If your answer is Yes, you know what do I mean intellectually, if no, I will show you an example.

'192.168.1.30', '192.168.1.21', '192.168.1.3' | Sort-Object

01.Sort-IpAddress

You expected to see the 192.168.1.3 before the 192.168.1.21, right?

The problem is Sort-Object does not know and can’t know Emoj that you are trying to sort IP addresses, it sorts your input as simple strings.

Sort-IpAddress

  • But the Sort-IpAddress function from my PowerShell MS-Module module will do that.

  • If your strings can be recognized as valid IP addresses, the Sort-IpAddress will sort them intellectually. Let’s compare the sort results by Sort-Object and Sort-IpAddress.

'192.168.1.30', '192.168.1.21', '192.168.1.3' | Sort-Object
'192.168.1.30', '192.168.1.21', '192.168.1.3' | Sort-IpAddress

02.Sort-IpAddress

Descending sort

  • The function can make both ascending and descending sorts. The default is ascending sort, but you can switch to descending by adding the -ZA parameter.
1..15 |% {"192.168.10.$_"} | Sort-IpAddress -ZA

03.Sort-IpAddress

Not only Class C

  • I almost forgot, the Class A and B IP addresses are sorted correctly too.
'192.168.1.30', '192.168.2.1', '192.168.1.4', '192.168.2.100' | Sort-IpAddress
'10.1.1.3', '10.2.1.1', '10.2.1.5', '10.1.1.200', '10.2.2.1' | Sort-IpAddress

04.Sort-IpAddress

Summary

  • The real function name is Invoke-SortIpAddress, and Sort-IpAddress is an alias. The reason Sort is reserved PowerShell verb.
Get-Command -Module MS-Module
Get-Alias -Definition Invoke-SortIpAddress
  • For more details about the function, please take a look at the content based help and examples.
Get-Help Invoke-SortIpAddress -Full
Get-Help Sort-IpAddress -Examples
Get-Help Sort-IpAddress -Parameter ZA

You might also like

New-PercentageBar – Create colored and adjustable Percentage Bar in the PowerShell
Write-Menu – Create interactive dynamic Menu in PowerShell
Start-SleepProgress – Put PowerShell scripts to sleep with Progress Bar

One thought on “Intellectually sort IP addresses w/PowerShell

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