Question

I'm currently making a bat script, to ping a host, and return the Packetloss percentage, and the avg ms.

Im using for /f to get the results.

Only thing is, the packet loss and the avg ms is on two different lines.

Therefor, i'm using subcalls, and findstr to set a variable for each.

But, when im trying to call the variable again, it includes all the parameters for the findstr command.

What can i do?

Here's the code:

@echo off
SETLOCAL
SET PingCMD=ping.exe -w 300 -n 1 127.0.0.1
FOR /f "tokens=3,6,9,10,11,12 delims=," %%A IN ('%PingCMD%') DO (

    call :GetLoss %%A
    call :GetAvg %%A

)
echo PacketLoss %loss%  Average %avg%
pause


:GetLoss
SET loss=%1 %2 %3 %4 ^| findstr "loss tab"
GOTO :eof

:GetAvg 
SET avg=%1 %2 %3 ^| findstr "Average Gennemsnit average gennemsnit"
GOTO :eof
EndLocal
Was it helpful?

Solution

@ECHO OFF
SETLOCAL
SET PingCMD=ping.exe -w 300 -n 1 127.0.0.1
FOR /f "tokens=3,6,9,10,11,12 delims=," %%A IN ('%PingCMD%') DO (

    call :GetLoss %%A
    call :GetAvg %%A

)
echo PacketLoss %loss%  Average %avg%
PAUSE
GOTO :eof


:GetLoss
IF "%1"=="Lost" SET loss=%2
GOTO :eof

:GetAvg 
IF "%1"=="Average" SET avg=%2
GOTO :EOF

Translation's your baby...

OTHER TIPS

@echo off

    setlocal enabledelayedexpansion

    set "pingCMD=ping -w 300 -n 1 127.0.0.1"
    set "pct="
    set "avg="
    for /f "tokens=*" %%a in ('%pingCMD% ^| findstr /n /r /c:"([0-9]*%%" /c:"= [0-9]*ms" ') do (
        if not defined pct (
               for /f "tokens=2 delims=(%%"  %%b in ("%%a") do set "pct=%%b"
        ) else ( for /f "tokens=7 delims=,= " %%b in ("%%a") do set "avg=%%b" )
    )
    echo %pct% %avg%

After searching in google images i've found that german ping output puts the percentage in a separate line. The same occurs in my spanish localized window, but not in english windows.

As the localization changes the lines, first for | findstr finds the two lines with the data needed. Then, depending of the line, another for is used to split the line where needed. In this moment i can not test it in another language but this should work with little changes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top