How to Ping List of Host Names and Output Results to CSV in PowerShell

Rohan Timalsina Feb 02, 2024
How to Ping List of Host Names and Output Results to CSV in PowerShell

Pinging a device or hostname is a basic feature available in PowerShell. You can send echo requests and test for ping connectivity using the Test-Connection and Test-NetConnection cmdlet.

It is a lot useful for network administrators. This tutorial will teach you to ping a list of hostnames and output the results to a CSV in PowerShell.

Use Test-Connection to Ping a List of Host Names and Output the Results to a CSV in PowerShell

The Test-Connection cmdlet sends Internet Control Message Protocol (ICMP) echo request packets, or pings, to one or more remote machines and returns the echo response replies. You can easily determine whether a specific computer can be reached across an IP network or not.

Here, we have a list of hostnames in the file test.txt.

Get-Content test.txt

Output:

www.google.com
www.delftstack.com

The following script pings a list of hostnames in the file test.txt and outputs the result to a result.csv file.

$testOutput = @()
$testnames = Get-Content "test.txt"
foreach ($name in $testnames) {
    if (Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue) {
        $testOutput += "$name,Up"
        Write-Host "$Name,Up"
    }
    else {
        $testOutput += "$name,Down"
        Write-Host "$Name,Down"
    }
}
$testOutput | Out-File "result.csv"

In the above PowerShell script, the Get-Content cmdlet is used to get a list of hostnames in the test.txt file and the ForEach loop to iterate through each hostname.

The Test-Connection cmdlet pings each hostname from the list. If the ping status is true, the hostname is stored in the $testOutput variable as Up; it stores the hostname as Down in the $testOutput variable.

The $testOutput variable is piped to the Out-File cmdlet, which sends output to a file result.csv. The content in the file is displayed the same as in the terminal.

Output:

www.google.com,Up
www.delftstack.com,Down

We hope this article helps you understand how to ping a list of hostnames and output the results to a .csv file.

Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website