Often when running WMI queries against a set of computers, the total script execution time can be quite long. Especially if there are computers that are unreachable, as the default WMI timeout is quite long. Therefore it’s always smart to do a ping check first, so that you only run the WMI query against a computer you have verified is reachable.
I’m going to show you three different ways of doing ping check using PowerShell. For this test I’m pinging google.com and I’m only after a true/false response whether the target is reachable or not.
Test-Connection -Count 1 -Quiet -ComputerName google.com
This is the built-in PowerShell cmdlet for checking ping. When I did this test it took approximately 51 milliseconds to ping google.com using Test-Connection.
Get-WmiObject -query "SELECT * FROM Win32_PingStatus WHERE Address = 'google.com'"
WMI is wonderful, there is (almost) nothing you can’t do using WMI. Ping check using WMI took approximately 41 milliseonds when I did my tests, so 10ms faster than using Test-Connection. Not bad!
Creating a new .NET object like this is perhaps not what most people would try first, but in most cases it can be very fast. During my test, a ping check like this took 22 milliseconds. That’s 19ms faster than using WMI and 29ms faster than using Test-Connection
So, shaving off 30ms is perhaps not worth it in many cases, but if this ping check is part of a larger script run at a big corporate network of 10k computers, the milliseconds quickly adds up.. to 5 minutes in fact!