PowerShell to ping a list of IP addresses in a CSV file

Source:www.opentechguides.com | Date Published: 2017-01-12 13:19:45

This PowerShell script reads a list of IP addresses or host names from a CSV file, Ping each of them and report the results. The filename and path of the CSV file to read is passed to the script as a parameter. The script gets the IP addresses from a column in CSV file with header "IPaddress". If you want to use a different column, simply change the variable $ColumnHeader in the script.

The main PowerShell cmdlets used in this script are Import-CSV to read the CSV file and Test-Connection to ping the IP addresses.



  Powershell script to ping all IP addresseses in a CSV file.
  This PowerShell script reads a CSV file and pings all the IP addresses listed in the IPAddress column.
.PARAMETER <csvfile>
   File name and path of the CSV file to read.
  Version:        1.0
  Author:         Open Tech Guides
  Creation Date:  12-Jan-2017
  Ping-IPList c:\IPaddressList.csv

  [Parameter(Mandatory=$true, position=0)][string]$csvfile

$ColumnHeader = "IPaddress"

Write-Host "Reading file" $csvfile
$ipaddresses = import-csv $csvfile | select-object $ColumnHeader

Write-Host "Started Pinging.."
foreach( $ip in $ipaddresses) {
    if (test-connection $ip.("IPAddress") -count 1 -quiet) {
        write-host $ip.("IPAddress") "Ping succeeded." -foreground green

    } else {
         write-host $ip.("IPAddress") "Ping failed." -foreground red

Write-Host "Pinging Completed."


Consider a CSV file like below>

ip address list csv

Here is how to run the script:

PS C:\> Ping-IPList.ps1 c:\IPAddressList.csv
Reading file c:\IPAddressList.csv
Started Pinging.. Ping failed. Ping succeeded. Ping failed. Ping failed. Ping succeeded.
Pinging Completed.

With some minor changes you can extend the functionality of this script a lot further. For example instead of pinging all the IP address in the list if you want to ping only the devices in a particular location, you only need to add a Where-Object cmdlet to Import-csv as below

$ipaddresses = import-csv $csvfile | where-object {$_Location -eq "Office 1"} | select-object $ColumnHeader 

The above line will get only the IP address that are in "Office 1" location.

This script is free of any copyrights, so feel free to customize and share your experience with us ;)

Open Tech Guides | www.opentechguides.com