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;
}

 

Comments (1)

  1. timid says:

    Here's one that works for a list of computers:

    function Ping-Computer {

    param (

    [string[]]$computer = @(),

    [int]$timeout = 1,

    [switch]$one

    );

    foreach ($myComputer in $computer) {

    if (!$myComputer) { continue; }

    Write-Verbose "Processing $myComputer";

    $pingStatus = $null;

    & {

    trap {

    Write-Warning "${computer}: $($_.Exception.Message)";

    continue;

    }

    (New-Object System.Net.NetworkInformation.Ping).Send($myComputer,$timeout * 1000).Status | Set-Variable -Scope 1 -Name pingStatus;

    }

    if ($one) {

    $pingStatus -eq 'Success';

    break;

    } else {

    $pingStatus | Select-Object -Property @{

    name = 'name';

    expression = { $myComputer; }

    }, @{

    name = 'status';

    expression = { $pingStatus -eq 'Success' }

    }

    }

    }

    }