It is often necessary to write a batch file that calls to a certain server, for example, when copying files. In this case script is run automatically in the background at a specified interval of time. What if in one of the starts the server will not be available (dropped off network, unreliable channel, etc.)? Then the script will be unsuccessful to contact the inaccessible server, trying to get something from him. The solution to this problem can be considered as a preliminary check on the availability of the server by using the well known program ping. But the ping does not return error status, and the program can not know whether you have connected successfully to the server or not. Here is the code to workaround this shortcoming.
check_server_is_online.cmd SET OK=N FOR /f "Tokens=*" %%a IN ('ping server_name^|FIND "TTL="') DO ( SET OK=Y ) IF "%OK%" EQU "N" GOTO failure :success ECHO server is online :failure ECHO server is offline
Here, server_name – is the name of the server, which you want to ping. The essence of the solution is to check the text output from ping on the presence of certain strings. For example, if the string «TTL =» exists in the output, the server is unavailable. You can, of course, use other lines, by your choice.
You can loop the program with the operators GOTO, to make it “wait” until the server becomes available. The program sleep is usefull to set the latency interval in case of unsuccessful connection. For example, you can create the program that verifies connectivity with the server every 5 minutes, and once the connection is established, your program will produce some action.
Naturally, this method of checking output strings can be used for any commands and programs, not just ping.