0

I am trying to write a PowerShell script to ping each IP Address from a CSV file 4 times. I know there are plenty of issues with this script, I am working and learning as I go. The one issue that has me stumped is when I run the script the $iplist variable takes the first variable and then runs through the list. I think it has to do with the array and the import-Csv, but I can't figure it out or break it well enough to get a clue.

Thank you

I omitted the full target location for security's sake

$iplist = @(Import-Csv "Book1.csv")

Write-Host $iplist

ForEach ($Data in $iplist)
{
Test-Connection $Data | Out-File  Bookx.txt
}

When the contents of $iplist are Write-Host the following is displayed: @{151.171.77.24=151.171.175.132} @{151.171.77.24=151.171.175.131}

There are a few dozen that all have the same 151.171.77.24= please note that 151.171.77.24 is the first IP in Book1.csv

1 Answers1

0

Given that @{} should be @{key=value}, I assume that you don't have a header in the CSV file. Try this:

$iplist = import-csv Book1.csv -Header 'test'
ForEach ($Data in $iplist)
{
   Test-Connection $Data.test | Out-File  Bookx.txt -Append
}

Basically, CSV files are grids, kind of like 2D arrays. Each column needs some key to define it. You can address these fields like so: $Data.column1, $Data.column2. Even though you only have one column, you must still follow these rules. In this case, your first IP address was being set as the column header, which is why you saw @{ip=ip}.

Adding the -Header switch allows you to address your column without modifying the file. Basically, imagine that it temporarily adds a header to the first column, right before you import the file.

If you're certain you will only have one column, you can also alternatively treat the file as plain text. For example, you could do something like this:

Get-Content file.csv | % {Test-Connection $_}

Get-Content will create an array, with each item being a single line. You can then do: for each line, test-connection with the IP of the current line.

To include failures, I would try implementing something like this: https://stackoverflow.com/a/51690032/4868262 Basically, setting the status field depending on the success of the command, thus allowing you to view failures in the output.

Hope this helped!

Jacob Colvin
  • 2,625
  • 1
  • 17
  • 36
  • That definitely solved my issue. Thank You!!! So the first line is the header unless the Header switch is used? I do have a question on this still, it is only writing the good output(successful pings), do you know how I can get it to write all output? thank you again – Reckless Liberty Aug 13 '18 at 15:20
  • I'll add some more details in an hour or so. – Jacob Colvin Aug 13 '18 at 15:29