Problem:

Sorting IP addresses in PowerShell using only the Sort-Object cmdlet does not achieve the desired results. There are a few other steps required in PowerShell to properly sort the data.

Solution:

  1. Download the Sort-IPAddresses.ps1 file from my Github repo.
  2. Move the script to the same directory as your parent script
  3. Add the following code to your parent script:
.\Sort-IPAddresses.ps1
  1. Call the function in your script. For example:
Sort-IPAddresses -IPs @('10.10.10.10','192.168.0.1','8.8.8.8')

Explanation:

Back in 2015, I needed to report out data to a customer but the data needed to be sorted by IP address. Using the Sort-Object cmdlet in PowerShell, IP addresses natively do not sort well. In the following steps, I will walk you through the code and explain my solution.

  1. Split the IP Address up into an array, ensure each object / octet has 3 digits (using zeros for the missing, preceding digits), and join the array to turn it back into a string.
$Octets = $IP.split('.')
$Formatted = foreach ($Octet in $Octets)
{
    if ($Octet.length -eq 1){"00" + $Octet} 
    elseif ($Octet.length -eq 2){"0" + $Octet} 
    else {$Octet}
}
$Formatted -join '' 
  1. Sort the output now that all the strings have the correct digits
$Sorted = $Data | Sort-Object
  1. Reformat the sorted data into IP addresses
$Output = foreach($Obj in $Sorted)
{
    $Obj[0] + $Obj[1] + $Obj[2] + '.' + $Obj[3] + $Obj[4] + $Obj[5] + '.' + $Obj[6] + $Obj[7] + $Obj[8] + '.' + $Obj[9] + $Obj[10] + $Obj[11]
}
$Output