Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import-CSV and Foreach

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?

like image 481
ScriptingBerry Avatar asked Mar 02 '13 10:03

ScriptingBerry


People also ask

What does import CSV do in PowerShell?

The Import-CSV function converts the CSV data into a custom object in PowerShell. This way we can easily walk through each row of the CSV file and use the data in our scripts.


2 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
   ...
}
like image 186
Shay Levy Avatar answered Oct 21 '22 17:10

Shay Levy


$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"
  }
}
like image 44
Bye Avatar answered Oct 21 '22 17:10

Bye