import-csv with multiple elements on the same line

Vinny Vinchenzo 61 Reputation points
2022-08-30T17:13:45.513+00:00

Hi,

Let's say i have a csv file like this:

IP

  1. 1.1.1
  2. 2.2.2

Then if I do:

import-csv $InputCSVFile -delimiter ',' -Encoding UTF8 | ForEach-Object {

try {
$IP = $_.IP
do something
}

Then everything works fine and the current IP address gets assigned to $_ and all is good.

But now, if my file looks like this instead:

IP

  1. 1.1.1,2.2.2.2

Then it only takes the first IP into account. In reality the file contains many IPs on the same line. Then I do not want to have a giant header like IP1,IP2,IP3,IP100.
So I tried to use the split function with the get-content function but then each ip is not treated as an object.

How should I do that?

Thanks
Vince

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,462 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 45,906 Reputation points
    2022-08-30T18:19:36.99+00:00

    Use a different delimiter in the Import-Csv, a delimiter that doesn't exist in the csv file. Maybe something like this:

    import-csv $InputCSVFile -delimiter ';' -Encoding UTF8 |   
        ForEach-Object {  
            $_.IP -split ',' |  
                ForEach-Object{  
                    Try{  
                        # do somthing with $_  
                    }  
                    Catch{  
                        # doing something failed  
                    }  
                }  
        }  
    

1 additional answer

Sort by: Most helpful
  1. Andreas Baumgarten 104K Reputation points MVP
    2022-08-30T18:15:03.433+00:00

    Hi @Vinny Vinchenzo ,

    You can try this in your Csv file if you have a , in a column:

    "IP"  
    "1.1.1.1,2.2.2.2"  
    

    This way you should be able to use split.

    $IP = "1.1.1.1,2.2.2.2"  
    $IP.Split(",")  
    

    ----------

    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards
    Andreas Baumgarten

    1 person found this answer helpful.
    0 comments No comments