In the previous tip we illustrated how WMI can ping multiple computers in a very fast way. So today, let’s wrap the code into a reusable PowerShell function. It can ping one or many computers with lightning speed.

Here’s the function code:

function Test-OnlineFast
{
    param
    (
        [Parameter(Mandatory)]
        [string[]]
        $ComputerName,
 
        $TimeoutMillisec = 1000
    )
    
    # convert list of computers into a WMI query string
    $query = $ComputerName -join "' or Address='"
 
    Get-WmiObject -Class Win32_PingStatus -Filter "(Address='$query') and timeout=$TimeoutMillisec" | Select-Object -Property Address, StatusCode
 }

Now it’s super easy to ping computers with a timeout of your choice:

 
PS> Test-OnlineFast -ComputerName microsoft.com, google.de
 
Address       StatusCode
-------       ----------
google.de              0
microsoft.com      11010  
 

A status code of “0” indicates a response: the system is online. Any other status code indicates failure.

By default, Test-OnlineFast uses a timeout of 1000 milliseconds, so when a machine does not respond, it waits a maximum of 1 second. You can change this timeout via -TimeoutMilliseconds. The more time you grant, the longer the command will take. You should therefore use a timeout that is as small as possible, while still allowing enough time for responding systems to send a response.

Another time factor to consider is DNS resolution: if DNS resolution is slow, or cannot resolve a name, this adds to the overall time it takes. With IP addresses, this slowdown does not occur.

Here is an example that pings 200 IP addresses and takes just a few seconds:

 
PS> $ComputerName = 1..255 | ForEach-Object { "10.62.13.$_" }
 
PS> Test-OnlineFast -ComputerName $ComputerName
 
Address      StatusCode
-------      ----------
10.62.13.1        11010
10.62.13.10           0
10.62.13.100          0
10.62.13.101      11010
10.62.13.102      11010 
(...)
 

Are you an experienced professional PowerShell user? Then learning from default course work isn’t your thing. Consider learning the tricks of the trade from one another! Meet the most creative and sophisticated fellow PowerShellers, along with Microsoft PowerShell team members and PowerShell inventor Jeffrey Snover. Attend this years’ PowerShell Conference EU, taking place April 17-20 in Hanover, Germany, for the leading edge. 35 international top speakers, 80 sessions, and security workshops are waiting for you, including two exciting evening events. The conference is limited to 300 delegates. More details at www.psconf.eu.

Twitter This Tip! ReTweet this Tip!

Anonymous