PowerShell with a Purpose Blog

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.

Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.