Ping and Range Ping

by Jan 26, 2009

In PowerShell, you can access .NET methods directly so it is easy to add a ping functionality:

$object = New-Object system.Net.NetworkInformation.Ping
$object.Send('127.0.0.1')

You can wrap it as function to get even more out of this:

function ping-ip {
param( $ip )
trap {$falsecontinue}
$timeout = 1000
$object = New-Object system.Net.NetworkInformation.Ping
(($object.Send($ip, $timeout)).Status -eq 'Success')
}
ping-ip 127.0.0.1
ping-ip "microsoft.com"
ping-ip "zumsel.soft"

Ping-IP can now ping any IP or hostname and returns true (online) or false (no response). Take note of the simple error handler: if you specify a host name that cannot be resolved, the Send() method raises an exception which the error handler handles. In this case, it also returns $false so even invalid host names return a $false (no response).

You can add a loop to create your own network segment scan:

0..255 | % { $ip = "192.168.2.$_""$ip = $(ping-ip $ip)" }