Search code examples
batch-filetestingcmdping

Creating a Batch file that pings google constantly and testing the response time


I'm trying to create a batch file that will constantly ping google.com and check the response time - "time=Xms".

  • If the time <= 39ms the text of that ping(or the background) should be green.
  • If the time > 40ms and < 80ms the text of that ping(or the background) should turn orange.
  • If the time >= 80ms the text of that ping(or the background) should turn red.

I have this batch at the moment which pings google every 3 seconds changes the background from green to red if the response fails:

    @echo off
:color 97

:start
PING -n 1 www.google.com 
call :color
goto :start

:color
    IF %ERRORLEVEL% EQU 0 (
        COLOR 27
    ) else (
        COLOR 47
    ping -n 1 127.0.0.1 >nul
    COLOR 74
    ping -n 1 127.0.0.1 >nul
    COLOR 47
    )
    ping -n 3 127.0.0.1 >nul
    GOTO:EOF

This works fine but I don't know how to test response times.


Solution

  • There are some quirks.

    a) you have to get the desired value of ping to a variable. Use a for to get it.

    b) you can't compare it directly, because if compares strings, not numbers (2 is bigger than 10). Add leading zeros to the string (and afterwards cut it to a fixed length)

    c) cmd has no native way of coloring single lines (or characters). It can be done with pure cmd, but I think, powershell is a much better way to do it.

    @echo off
    :loop
    set "tim=unreachable"
    for /f "tokens=7 delims== " %%i in ('PING -n 1 www.google.com ^|find "TTL"') do set "tim=%%i"
    set "ti=0000%tim%"
    set "ti=%ti:~-6,-2%"
    if %ti% leq 0040 powershell write-host -foreground green %tim% & goto :loop
    if %ti% leq 0080 powershell write-host -foreground yellow %tim% & goto :loop
    powershell write-host -foreground red %tim% & goto :loop