How to Sort List of IP Addresses from a CSV in Powershell

1.8k views Asked by At

I currently have a list of IP Addresses in a CSV file called computer_info, I want to import them into powershell and sort them. I have tried a few methods on here and had no luck. I know how to import the CSV and identify the column that I want to use, but I cant figure out how to sort the strings in actual IP address order

i currently have

import-csv computer_info.csv| select ip_addr | sort ip_addr

Thanks for any suggestions

2

There are 2 answers

0
Esperento57 On

other method :

import-csv "C:\temp\test.txt" | %{
    $array=$_.ip_addr.Split('.')
    [pscustomobject]@{Part1=[int]$array[0];Part2=[int]$array[1];Part3=[int]$array[2];Part4=[int]$array[3];IP=$_.ip_addr}   
} | sort Part1, Part2, Part3, Part4 | select IP
5
SomeShinyObject On

One recommended way of doing this is leveraging [System.Version]

Import-CSV computer_info.csv| Select ip_addr | Sort {[System.Version]$_}

It's not really the intended purpose of Version but it works. This turns an IP address into a version object which can be sorted.

  • Octet 1 becomes Version.Major.
  • Octet 2 becomes Version.Minor.
  • Octet 3 becomes Version.Build.
  • Octet 4 becomes Version.Revision.

Sorting IP addresses in PowerShell, part 1, IPv4