Prof. Powershell

This is Only a Test

PING is fine, if you're not into automation. Otherwise, use Test-Connection to see if a computer is online.

Very often when working with a group of computers, you want to verify a computer is up before attempting to do anything with it. Typically the approach is to ping the computer and only proceed if there is a response. You could use the command line PING.EXE, but then you'd have to parse the output. In PowerShell 2.0, we can use Test-Connection.

The basic command is Test-Connection computername, like this:

PS C:\> test-connection server01

You'll get back basic ping-type information such as the destination name, its IP address and how much time it took. If the computer can't be reached, then nothing should be returned. This means we can use Test-Connection like this PowerShell one-liner:

PS C:\> get-content computers.txt | foreach { if (test-connection $_) { write-host "$_ is up" -foregroundcolor GREEN} else {write-host "$_ is down" -foregroundcolor RED}}

It's a relatively basic example, but I hope you get the picture. Or perhaps you might want to get an average response time:

PS C:\> (test-connection www.mcpmag.com -count 10 | measure-object ResponseTime -average).Average
32.2

I can see that the average response time over 10 pings to MCPMag.com was a tad over 32 milliseconds. If you ran Test-Connection without any additional parameters, you may wonder where I got ResponseTime. Remember that the default display you get in PowerShell is not always the same as the object's properties. Pipe objects to Get-Member to discover the true property names. Once you know the names, you can prepare quick status reports like this:

PS C:\> test-connection redmondmag.com | Format-Table Address,IPv4Address, ResponseTime -autosize
Address        IPV4Address ResponseTime
-------        ----------- ------------
redmondmag.com 66.77.93.49 105
redmondmag.com 66.77.93.49 96
redmondmag.com 66.77.93.49 103
redmondmag.com 66.77.93.49 103

There are a few more ways to use Test-Connection, but I'll leave those for you to try out. Look at full cmdlet help for more information.

About the Author

Jeffery Hicks is an IT veteran with over 25 years of experience, much of it spent as an IT infrastructure consultant specializing in Microsoft server technologies with an emphasis in automation and efficiency. He is a multi-year recipient of the Microsoft MVP Award in Windows PowerShell. He works today as an independent author, trainer and consultant. Jeff has written for numerous online sites and print publications, is a contributing editor at Petri.com, and a frequent speaker at technology conferences and user groups.

comments powered by Disqus
Most   Popular

Upcoming Training Events