I need to run ping with -t parameter and process every line in bat script. I need to do this in real time.
This code explains my problem. Commant 'ping -t 8.8.8.8' prints nothing to for loop so nothing is printed to console. If I use 'ping -n 10 8.8.8.8' all lines are printed at the same time when ping exits.
How can I get printed lines in real into for loop?
@echo off
Setlocal EnableDelayedExpansion
FOR /f "TOKENS=*" %%i in ('ping -t 8.8.8.8') do (
set LINE=%%i
echo !LINE!
)
Best Answer
As specif iced in the comments; the
FOR
command can not process ongoing output; it handles a set of data once the process terminates.You will need to produce only one set of output per execution of ping to be able to capture each result. You also need to limit the result set to just the ping result and ignore the other lines.
The find command will only return results that contain the address pinged (need to use an IP here)
The
SKIP
option will bypass the first line returned byPing
with a reference to the IP address.In the body of the
For
command you will store the tokens into temp variables for processing outside of theFor
loop.Goto :l_Break_Loop
will for the loop to only accept the one line of output from thePing
command and jump to the data processing section.Afterwards,
Goto :l_Start_Loop
will direct the batch file to the top of the loop for another row of ping data.You can use timer functions to impose a delay between ping attempts, and with some cleaver manipulation of the
%TIME%
variable you can even get the ping command to run at regular intervals as long as the delay is longer than the time to ping and process the results.%TIME:~-8,2%
returns minutes%TIME:~-5,2%
returns seconds%TIME:~-2%
returns hundredths of a second