Pinging a Hostname with Timeout
Well, that's simple:
$ping = New-Object System.Net.NetworkInformation.Ping;
[bool]($ping.Send($computer, $pingTimeout).Status -ne 'Success');
It gets more interesting when we need to verify that $computer is actually valid. We can use [System.Net.DNS]::GetHostAddresses(), but that emits an error if the host doesn't exist, which can be disconcerting if we're trying to write something that looks pretty. In this case, we'll use trap {} to suppress the error message and get on with our lives:
& {trap { continue; } $script:hostEntry = [System.Net.Dns]::GetHostEntry($computer); }
[bool]$script:hostEntry ;
Put it all together, and we get:
function Ping-Computer {
param (
[string]$computer,
[int]$pingTimeout = 1000 # in milliseconds
);
if (!$computer) {
Write-Warning "-computer not specified, required.";
return $false;
}
$script:hostEntry = $null;
& { trap { continue; } $script:hostEntry = [System.Net.Dns]::GetHostEntry($computer); }
if (!$script:hostEntry) {
Write-Warning "$computer is not known.";
return $false;
}
$script:pingStatus = $null;
& { trap { continue; } $script:pingStatus = (New-Object System.Net.NetworkInformation.Ping).Send($computer, $pingTimeout).Status; }
if ($script:pingStatus -ne 'Success') {
Write-Warning "$computer is not pingable.";
return $false;
}
return $true;
}