0

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

aschipfl
  • 33,626
  • 12
  • 54
  • 99
M R
  • 77
  • 2
  • 9
  • Pinging a server provides only an indication of the time taken to hop a message to, and possibly receive a response from that specific server. It does not provide you with any indication of the health of your network. – Compo Jul 24 '21 at 00:47
  • 1
    I've been running your script for an hour now and it's still working correctly. Try running your script from the command line instead of double-clicking the script and see what error message you get. – SomethingDark Jul 24 '21 at 01:04

1 Answers1

0
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.

Anon Coward
  • 9,784
  • 3
  • 26
  • 37
  • Best practice is to use quotes like `if "%VarCheck%"=="%AVG_PING%" …`, because they also protect whitespaces and other special characters… – aschipfl Jul 28 '21 at 20:13