Downloads
23931.zip

How can I use the Ping command in a Windows Script Host (WSH) script to determine whether I can reach a host?

As Listing 2 shows, you need to use the Ping command with the -n and -w parameters. The -n parameter specifies the number of pings, and the -w parameter specifies the timeout interval (in milliseconds). In this case, I'm pinging the host www.google.com twice, with a timeout interval of 20 seconds. To obtain a complete list of available parameters for the Ping command, type

Ping -?

on the command line.

You use WshShell object's Run method to execute the Ping command. Ping is an interactive command that writes output to the screen. To access and view its output, you must redirect that output to a file, then manipulate the file. Thus, before you execute the Ping command, you need to use the FileSystemObject object's GetSpecialFolder and GetTempName methods to create a temporary file to capture the Ping command's output. The GetSpecialFolder method returns the specified special folder. In this case, you specify the constant value of 2, which returns an instance of the Temp folder. The GetTempName method returns a randomly generated temporary filename or folder name. In this case, you use the method to generate a temporary file in the Temp folder and assign that file to the filTemp variable. (For more information about the GetSpecialFolder and GetTempName methods, go to http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/jsorifilesystemobjectmethods.asp?frame=true.)

After the Ping command executes and filTemp contains the results, you set filTemp to the filPingResponse variable so that you can process the output. If the output contains the string Reply, the code displays the message Ping successful. Otherwise, the code displays the message Ping failed.

To use the code in Listing 2, you need to adjust the number of pings (if needed) and customize the host name. Note that some hosts don't respond to pings. For example, if you try pinging www.microsoft.com or www.hotmail.com, you'll never get a response.

Corrections to this Article:
  • The code in Listing 2 contains an error. In the Do...Loop statement, the line

    If InStr(ts.ReadLine, "Reply") > 0 Then

    Should be

    If InStr(ts.ReadLine, "TTL=") > 0 Then


    We apologize for any inconvenience this error causes.