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?
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.
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
...
}
$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"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With