2

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

  • What is it coming out as? What problems are you running into? – SomeShinyObject Sep 01 '17 at 02:59
  • the address comes in as a string so it goes digit by digit to sort them so it would say for example 10.11.10.252 is smaller than 10.11.10.26 and therefore is listed before it because the 10.11.10.2 match but the next digit is a 5 compared to a six so it determines 10.11.10.252 is smaller and therefore is listed before 10.11.10.26 – rpi_engin33rs Sep 01 '17 at 03:10
  • i feel like the solution lies in casting the strings to another type then sorting them but I haven't found the proper solution yet – rpi_engin33rs Sep 01 '17 at 03:45
  • Related: https://stackoverflow.com/q/72407929/7571258 – zett42 May 27 '22 at 22:48

2 Answers2

6

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

SomeShinyObject
  • 7,581
  • 6
  • 39
  • 59
  • thanks, i had looked at that page earlier today when i was researching this. When i follow the directions on the link i get error messages saying cannot covert value of type selected.system. management.automation.PScustomObject to type System.Version it works with the values in the format they provide but not when i try to import the csv values in as the addresses – rpi_engin33rs Sep 01 '17 at 04:53
  • @rpi_engin33rs Retry with the edit. That should work. – SomeShinyObject Sep 01 '17 at 05:03
  • it goes through each ipaddress and throws the same error then spits out the unsorted list at the bottom after all the error messages – rpi_engin33rs Sep 01 '17 at 05:24
  • Why not cast to `ipaddress` instead? – ZzZombo Dec 31 '20 at 11:46
  • Whomever was the first person to realise that this .NET class could be (ab)used in this way...well, I don't know whether to chastise or congratulate them. – Bren0man Nov 12 '21 at 11:30
2

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
Esperento57
  • 16,521
  • 3
  • 39
  • 45