How to ping computers to test for network connectivity.
If you only need to ping a single machine with Test-Connection then using the -quiet parameter will return a True/False value that can be used as part of a simple If statement:
If (Test-Connection remotehost -quiet) {
Write 'The host responded'
# Add other statements here..
}
The function below may be used two ways: pipe one, or a whole list of machines to psp, or alternatively type psp remotehost on the command line. Examples below. The function is named psp rather than ping because you may still wish to run ping.exe from the PowerShell command prompt.
Function psp {
param($InputObject = $null)
BEGIN {$status = $False}
PROCESS {
if ($InputObject -and $_) {
throw 'ParameterBinderStrings\AmbiguousParameterSet'
} elseif ($InputObject -or $_) {
$processObject = $(if ($InputObject) {$InputObject} else {$_})
write-host "Ping [$processObject]"
if( (Test-Connection $processObject -Quiet -count 1)) {
write-host "Ping response OK" -ForegroundColor DarkGreen
$status = $True
}
else {
write-host "Ping failed - host not found" -ForegroundColor red
$status = $False
}
}
else {throw 'ParameterBinderStrings\InputObjectNotBound'}
# next processObject
}
# Return True if pings to all machines succeed:
END {return $status}
}
This function will return a True or False value, $True will only be returned if the pings to ALL the machines succeed.
Note: PowerShell does not save functions or aliases permanently by default. So if you close and reopen PowerShell, this function will no longer be available. To make it permanent, add the function to your PowerShell $Profile file.
Examples
Ping server64:
PS C:\> psp server64
Ping three servers:
PS C:\> "server64" ,"server65" , "10.164.199.200" | psp
Ping a list of servers:
PS C:\> $servers = cat E:\MachineNames.txt
PS C:\> $servers | psp
Ping a server and capture the result:
PS C:\> $result = psp server64
PS C:\> $result
“And now I see with eye serene
The very pulse of the machine.” - William Wordsworth, (She Was a Phantom of Delight)
Related:
Test-Connection - Ping one or more computers
Functions and Filters - Write a named block of code
Write-Warning - Write a warning message