I've got a huge comma seperated CSV-list with IP-addresses of my network that I want to run queries against. 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 test for the output:

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

I get no output, I think it's because there are no headers specified. I can obviously do a workaround and open the CSV-file and type in all the headers. Are there any other ways to solve this?

0

4 Answers

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

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

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

On the first string only, I split it based on ",". Dumping it into $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" } } 
2

Solution is to change Delimiter.

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

Values are 6 Dutch word 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} 

It is possible to read a CSV file and use other Delimiter to separate each column.

It worked for my script :-)

$filepath = ".\ADcomputerslist.csv" $servers = Import-CSV $filepath -delimiter ","

Foreach ($entry in $servers) { write-host $entry.name }

also can replace stupid file with object.

$servers = Get-ADComputer -Filter * -Property * | Select-Object Name,OperatingSystem,OperatingSystemVersion,ipv4Address

Foreach ($entry in $servers) { write-host $entry.name }

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy