Tuesday, December 4, 2007

VBScript: ping with WScript.Shell and WMI

VBScript: Output Snippet

This function can be found on Microsoft.com somewhere. I remember once finding some nslookup function where the author wrote the output of nslookup to a file on the hard drive, parsed it then forgot to delete it. I used that script and after a few years, I found that directory full of thousands of text files. Anyway, using StdOut.ReadAll would have been much more efficient. Here's a snippet I've used over and over:

Function PingHost(strComputer)
  Set objShell = CreateObject("WScript.Shell")
  Set objExec = objShell.Exec("ping -n 2 -w 1000 " & strComputer)
  strPingResults = LCase(objExec.StdOut.ReadAll)
    If InStr(strPingResults, "reply from") Then
      PingHost = True
    Else
      PingHost = False
    End If
  Set objExec = Nothing
  Set objShell = Nothing
End Function

For the record, a better way to find out if a machine is pingable is by using WMI and the machine's fully qualified domain name (if you use the netbios name, there is a delay if the host doesn't exist..but DNS reports back immediately)

Set objWMIService = GetObject("winmgmts:\.\root\cimv2")
strComputer =  "myServer.myDomain.net"
Set colItems = objWMIService.ExecQuery("Select * from Win32_PingStatus Where Address = '" & strComputer & "'")
          For Each objItem in colItems
              If objItem.StatusCode = 0 Then 'The Computer is Pingable
              msgbox "Woot"
              End if
         Next
Set objWMIService = Nothing