Search code examples
batch-filepingfindstr

Better way to use findstr to get packet loss, batch


Looking to use findstr to get it to find "0% loss" after a ping command. Perhaps an array of anything up to "50% loss".

This is for checking and ensuring a connection to the internet is 100% established before launching something online.

Currently it's structured:

ping %ip% -n 3 -w 3000 | findstr "0% loss"
pause
goto Starting

It's currently ignoring findstr and no matter what it refuses to find what I'm looking for

Ideally it would flow like:

ping %ip% -n 3 -w 3000 | findstr "0% loss" || goto Echo
pause
goto Starting
:echo
Could not find "0% loss"
pause

And I have tried that, it will go to echo, but even with 100% connection so it's clearly just not operating how I'd like it to.

Is there a better way to find % packet loss?

Or

Is there a better way to test internet connection, given ping doesn't work when a device is totally offline.


Solution

  • The search string you are looking for is too broad. When you check findstr for "0% loss", you are inadvertently picking up "100% loss" as well. Fortunately, ping puts the packet loss in parentheses, so you can simply include the open parenthesis in the search string.

    @echo off
    title Restart
    color 0A
    cls
    
    :start
    Cls
    set ip=www.google.com
    
    :Pingcheck
    echo Checking ping..
    timeout /t 3
    ping %ip% -n 5 -w 3000 | findstr /C:"(0% loss" || goto Loss
    pause
    
    :NoLoss
    echo We found 0 packet loss, at %ip% on %date% at %time%
    pause
    goto start
    
    :Loss
    echo We found some packet loss.
    pause
    

    I've also changed the name of the :Echo label because echo is already a command and having it also be a label would be confusing.