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
  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
Set objWMIService = Nothing

Chrissy is a Cloud and Datacenter Management MVP who has worked in IT for over 20 years. She is the creator of the popular SQL PowerShell module dbatools, and holds a number of certifications, including those relating to SQL Server, Linux, SharePoint and network security. You can follow her on Twitter at @cl.

Posted in VBScript

Leave a Reply

Your email address will not be published. Required fields are marked *