rpi_engin33rs
rpi_engin33rs

Reputation: 21

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

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

Upvotes: 2

Views: 1912

Answers (2)

Esperento57
Esperento57

Reputation: 17472

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

Upvotes: 2

SomeShinyObject
SomeShinyObject

Reputation: 7811

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

Upvotes: 6

Related Questions