Thursday, 10 January 2013

How to issue periodical execution of DOS command in a single line

Let's say we want to check the state of the socket connection on the port 4016 every second. We can use netstat command to display required information and ping invalid IP address with timeout of 1 second. These two commands can be grouped in the same line with & operator and that group can be put inside infinite FOR loop:

Command:
C:\Users\Scrillex>for /L %a in (0,0,0) do (netstat -an|find "4016" & ping 1.1.1.1 - n 1 -w 1000 >nul)

Output:
C:\Users\Bojan>(netstat -an | find "4016" & ping 1.1.1.1 -n 1 -w 1000 1>nul)
TCP 0.0.0.0:4016 0.0.0.0:0 LISTENING
TCP [::]:4016 [::]:0 LISTENING

C:\Users\Bojan>(netstat -an | find "4016" & ping 1.1.1.1 -n 1 -w 1000 1>nul)
TCP 0.0.0.0:4016 0.0.0.0:0 LISTENING
TCP [::]:4016 [::]:0 LISTENING

C:\Users\Bojan>(netstat -an | find "4016" & ping 1.1.1.1 -n 1 -w 1000 1>nul)
TCP 0.0.0.0:4016 0.0.0.0:0 LISTENING
TCP [::]:4016 [::]:0 LISTENING
^C

To stop the execution of this single line script use CTLR-C.