Tricks with Test-Connection

Writing a script that will connect to another computer, perhaps via WMI or PowerShell Remoting? It might make sense to "ping" the computer first, as a quick check to see if it's even reachable.

The Test-Connection cmdlet utilizes the same ICMP protocol as Ping.exe; it's implemented by having the shell query the local computer's Win32_PingStatus WMI class. WMI needn't be running or enabled on the remote computer, though.

The easiest usage is:

Test-Connection -computername SERVER1

This actually returns several result objects. Those objects have, amongst other things, a StatusCode property which is set to 0 when the ping was successful. Sometimes, that's all you care about, in which case this is a lot easier:

Test-Connection -computer SERVER1 -quiet

The result of that is a simple True/False, which is much easier to stick into an If construct. However, you need to be a bite careful in how you use this. When set to -Quiet mode, Test-Connection doesn't return the computer name - it's JUST a True/False. So this won't work well:

Test-Connection -quiet -computer (Get-Content names.txt) | ForEach { # do something }

The problem is that Test-Connection is only outputting True/False, so that's all ForEach-Object will have to work with. You don't have any computer names at that point! A better approach:

Test-Connection -count 1 -computer (Get-Content names.txt) | ForEach { # do something with $_.Address }

This assumes Names.txt contains computer names or IP addresses, one per line. The -count parameter is needed so that each computer is only pinged once, generating only one result - otherwise, by default, each computer will generate 4 results! That could be problematic since ForEach will be executing its script block one time for each of those results.

Discuss this Blog Entry 1

on Feb 1, 2012
I tried this just yesterday actually to test if a server was available with just the boolean. It seemed to go much slower than the standard $ping.send() that I have used before and that I see a lot of others use. Would you say or is it your experience that for test servers liveliness in bulk this is slower than the often used $ping.send() stuff?

Please or Register to post comments.

What's PowerShell with a Purpose Blog?

Don Jones demystifies Windows PowerShell.

Blog Archive

Sponsored Introduction Continue on to (or wait seconds) ×