martedì 26 gennaio 2016

Automate DOS commands - Ping example

Imagine you have been given the lovely task of finding out the IP address of more than 40 servers. Do you really want to do it manually? Definitely I do not.
I have created a script and, even if I have to admit that it took me almost more time to write it than doing the task manually, I hope this can save someone's else time.
The script I have written looks like this:

ping -n 1 <ServerName1> | for /F "tokens=*" %%a in ('findstr Reply') do @echo
ping -n 1
<ServerName2> | for /f "tokens=*" %%a in ('findstr Reply') do @echo <ServerName2>:%%a

The option "-n 1" is used to define how many times the server is pinged. One time is enough to get the following output:

Pinging <ServerName1> [] with 32 bytes of data:
Reply from bytes=32 time=45ms TTL=59
Ping statistics for
    Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 45ms, Maximum = 45ms, Average = 45ms

The second part of the command parses the output of the ping command looking for a string starting with 'Reply' and prints the results.
@ECHO OFF is used to prevent the script to print the DOS command in the output.
Here is an example of output file:

<ServerName1>:Reply from bytes=32 time=18ms TTL=59 <ServerName2>:Reply from bytes=32 time=19ms TTL=59

I have decided to separate the server name from the 'Reply' string using a semicolon, but it is mainly because this way I can treat the output as a simple semicolon-delimited file.