Import CSV and Foreach

I have a huge comma-separated CSV list with the IP addresses of my network with which I want to run queries. An example of my CSV input:

172.168.0.1,172.168.0.2,172.168.0.3,172.168.0.4 

Etc ....

When I run the following code to check the output:

 $filepath = "c:\scripts\servers.csv" $servers = Import-CSV $filepath -delimiter "," Foreach ($server in $servers) { write-host $server } 

I do not get a way out, I think, because there are no headlines. I obviously can do a workaround and open the CSV file and enter all the headers. Are there any other ways to solve this problem?

+8
foreach powershell csv
source share
3 answers

You can create headers on the fly (no need to specify a separator when the separator is a comma):

 Import-CSV $filepath -Header IP1,IP2,IP3,IP4 | Foreach-Object{ Write-Host $_.IP1 Write-Host $_.IP2 ... } 
+15
source share
 $IP_Array = (Get-Content test2.csv)[0].split(",") foreach ( $IP in $IP_Array){ $IP } 

Get-content Filename returns an array of strings for each row.

Only in the first line did I divide it into ",". Dumping it to $ IP_Array.

 $IP_Array = (Get-Content test2.csv)[0].split(",") foreach ( $IP in $IP_Array){ if ($IP -eq "2.2.2.2") { Write-Host "Found $IP" } } 
+1
source share

The solution is to change the delimiter.

The contents of the csv file -> Note .. Also space and, in value

Meanings: 6 Dutch words aap, noot, mies, Piet, Gijs, Jan

 Col1;Col2;Col3 a,ap;noo,t;mi es P,iet;G ,ijs;Ja ,n $csv = Import-Csv C:\TejaCopy.csv -Delimiter ';' 

Answer:

 Write-Host $csv @{Col1=a,ap; Col2=noo,t; Col3=mi es} @{Col1=P,iet; Col2=G ,ijs; Col3=Ja ,n} 

You can read the CSV file and use a different delimiter to separate each column.

It worked for my script :-)

0
source share

All Articles