Skip to content

Instantly share code, notes, and snippets.

@matsest
Last active June 27, 2023 14:54
Show Gist options
  • Save matsest/44b2dc76f97bbca920a7b86f539cef32 to your computer and use it in GitHub Desktop.
Save matsest/44b2dc76f97bbca920a7b86f539cef32 to your computer and use it in GitHub Desktop.
Sorting IP address spaces with PowerShell
# Define ranges
$NetworkRanges = @(
'10.11.0.0/24'
'10.11.1.0/24'
'10.11.12.0/24'
'10.11.24.0/24'
'10.11.2.0/24'
)
# Bad - does not sort according to address spaces, only alphanumerical :(
$NetworkRanges | Sort-Object
# Good - sort it by treating the IP address part as a "Version" :)
$NetworkRanges | Sort-Object -Property { $_.Split('/')[0] -as [System.Version] }
# This can also be done with IP Addresses:
$IpAddresses = @(
'10.11.0.5'
'10.11.1.23'
'10.11.12.33'
'10.11.24.12'
'10.11.2.1'
)
# Good - sort it by treating the IP address as a "Version" :)
$IpAddresses | Sort-Object -Property { $_ -as [System.Version] }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment