Chris Liu
Chris Liu

Reputation: 41

Windows Batch ERRORLEVEL of ping is not working while in loop

Could anybody help to figure out what the problem is in the following batch code? I want to check if the device with ip 192.168.0.1 is ready to connect. I power off the device and power on it after executed the batch. It seems the %errorlevel% is not working if first check is not 0

@echo off

set "host=192.168.0.1"

for /l %%i in (1,1,255) do (
    ping -n 1 "%host%" | findstr /r /c:"[0-9] *ms"
    if %errorlevel% == 0 (
        echo ping %host% ok.
        goto :endLoop
    ) else (
        echo ping %host% fail count %%i
        REM "ping -n 6 -w 1000 " sleep 5 seconds
        ping 127.0.0.1 -n 6 -w 1000 > nul
    )
)

:endLoop
echo Done

I got the following log, it can't stop when ping response successfully.

D:\document\code\windows\bat>check_ip.bat
ping 192.168.0.1 fail count 1
ping 192.168.0.1 fail count 2
ping 192.168.0.1 fail count 3
...
ping 192.168.0.1 fail count 21
ping 192.168.0.1 fail count 22
ping 192.168.0.1 fail count 23
Reply from 192.168.0.1: bytes=32 time=1ms TTL=64
    Minimum = 1ms, Maximum = 1ms, Average = 1ms
ping 192.168.0.1 fail count 24
Reply from 192.168.0.1: bytes=32 time=2ms TTL=64
    Minimum = 2ms, Maximum = 2ms, Average = 2ms
ping 192.168.0.1 fail count 25
Reply from 192.168.0.1: bytes=32 time=1ms TTL=64
    Minimum = 1ms, Maximum = 1ms, Average = 1ms
ping 192.168.0.1 fail count 26
Reply from 192.168.0.1: bytes=32 time=1ms TTL=64
    Minimum = 1ms, Maximum = 1ms, Average = 1ms
ping 192.168.0.1 fail count 27
^CTerminate batch job (Y/N)? Y

I tried the batch on windows 10 machine. I expect the code can stop after ping response successfully.

Upvotes: 1

Views: 122

Answers (1)

Compo
Compo

Reputation: 38579

Here's my comment as a visual answer. Please note that this is only to show you how to make the ErrorLevel work as intended, (your specific question), not to determine whether a device is ready to connect.

@Echo Off
SetLocal EnableExtensions

Set "host=192.168.0.1"

For /L %%G In (1 1 255) Do (
    %SystemRoot%\System32\ping.exe -n 1 "%host%" | %SystemRoot%\System32\find.exe "TTL" 1>NUL 2>&1
    If Not ErrorLevel 1 (
        Echo ping %host% ok.
        GoTo endLoop
    )
    Echo ping %host% fail count %%G
    %SystemRoot%\System32\ping.exe 127.0.0.1 -n 6 -w 1000 1>NUL
)

:endLoop
Echo Done
%SystemRoot%\System32\ping.exe 127.0.0.1 -n 4 -w 1000 1>NUL
EndLocal

I added the penultimate line just to give you around three seconds to read the Done message. This is only optionally required if you are not running the script from a Command Prompt window.

Upvotes: 2

Related Questions