If you’ve used VBScript in the past you will remember using Win32_PingStatus to test the connectivity to a remote machine. In the 2010 Scripting Games we’ve seen a lot of scripts testing if a remote machine can be contacted.
Many of the scripts contain code of the form
$query = "Select * from Win32_PingStatus WHERE Address = ’127.0.0.1′"
Get-WmiObject -Query $query
There’s nothing wrong with this and it does the job so any marks for testing remote connectivity will be awarded. This code is a direct translation of the VBScript code.
The query could be given as part of the call to Get-WmiObject bit we can make it easier by doing this:
Get-WmiObject -Class Win32_PingStatus -Filter "Address = ’127.0.0.1′"
The query after the WHERE statement becomes the filter and we give the class directly. Bit less typing and easier to read.
if we want this as part of a loop where we will be testing multiple machines then we can refine it to this
$computer = ’127.0.0.1′
Get-WmiObject -Class Win32_PingStatus -Filter "Address = ‘$computer’"
The $computer variable could be set as part of the loop control rather than as a direct variable. One thing to be aware of is that computername parameter isn’t supported in the way most WMI classes support it
Note that this is NOT supported
Get-WmiObject -Class Win32_PingStatus -ComputerName $computer
In PowerShell v2 it gets even simpler as we have a cmdlet that wraps Win32_PingStatus for us
Test-Connection -ComputerName $computer
but it returns four pings by default so use
Test-Connection -ComputerName $computer -Count 1
All of the above work but the last one is the easiest and involves least typing (remember tab completion)