Search code examples
batch-filecmdwindows-10ping

Why is this CMD .bat file stopping?


I've written a simple .bat file to monitor the ping between my PC and Google (in an attempt to monitor roughly the health of the network, and record any dropouts).

The following is in a file called Pingtest.bat

@ECHO OFF

:LOOPSTART

FOR /F "tokens=* USEBACKQ" %%i IN ('%DATE:~0% %TIME:~0,8%') DO (SET "TIMED=%%i")

FOR /F "tokens=* USEBACKQ" %%g IN (`ping -n 1 -w 10000 www.google.co.uk`) do (SET "PING=%%g")
FOR /F "tokens=3 delims=," %%a in ("%PING%") do (set AVG_PING=%%a)
SET AVG_PING=%AVG_PING:~11,-2%

set /a varCheck=%AVG_PING%
IF %VarCheck%==%AVG_PING% (goto :OUTPUT) else (goto :ERROR)
:ERROR
SET AVG_PING=ERROR

:OUTPUT
SET OUTPUT=%TIMED% %AVG_PING%

echo %OUTPUT% >> Pingtest.txt
set "TIMED="
set "PING="
set "AVG_PING="
set "varCheck="

timeout /t 5 /nobreak > NUL

GOTO LOOPSTART

Every 5 seconds, this outputs a timestamp and the ping result in ms (e.g. 23/07/2021 23:35:40 15) and appends it to the Pingtest.txt file. This should run indefinitely.

This .bat file is executed via a .vbs file which executes the .bat silently (code from this post), executed at startup.

The issue is that I would expect this code to run indefinitely until the user session ended (shutdown/logoff), but the code seems to stop on its own after ~350 executions (~30 mins). Is there a reason for this, and can this by bypassed/resolved such that the code can run indefinitely?

P.S. Fully aware this is is probably awfully-written code, so open to any feedback/improvements.

Thanks


Solution

  • IF %VarCheck%==%AVG_PING% (goto :OUTPUT) else (goto :ERROR)
    

    This is the core of the issue. If the DNS lookup or ping outright fails, VarCheck ends up being empty, then this line is parsed nonsensically, and the end result is the rest of the batch file is ignored. Changing it to something like:

    IF [%VarCheck%]==[%AVG_PING%] (goto :OUTPUT) else (goto :ERROR)
    

    Will handle the case where VarCheck is empty.