V Britt
V Britt

Reputation: 25

Split IP addresses in a CSV Cell

I am struggling in importing from a CSV file. This file has and "IP Address" field however the program that generates the form (which I have not control over) can create a CSV file like this

hostname,IP Address,Site
server1,192.168.1.10,florida
Server2,192.168.10.100
192.168.10.101
8.8.8.8,Alaska
server3,10.10.10.10,Ohio

I import the csv into variable $sessions=import-csv -path $Path

In a foreach ($session in $sessions) loop I try to get the IP's and split them with the following:

$IPs=$session."IP Address" -split "`r`n"

However when I check the $IPs it does not seem to be an array as for server 2 $IPs shows

PS c:\$IPS
 192.168.10.100
192.168.10.101
8.8.8.8
PS c:\$IPs.count
1

What can I do to split the Cell in to an array so I can process the IP's found in a foreach ($IP in $IPs) loop

Upvotes: 0

Views: 212

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174445

Using "`r`n" to split on newlines will fail if the input doesn't use carriage returns.

Either make the carriage return char optional in the regex pattern:

$IPs = $session."IP Address" -split "`r?`n"

Or use -split in unary mode, which will trim the input string and split on consecutive whitespace sequences:

$IPs = -split $session."IP Address"

Upvotes: 1

Related Questions