Errorlevel always returns 0 in a for loop with ping command

  • 1 year ago
Comment

ChatGPTChatGPT
1 / 1

When using the ping command in a for loop in Windows command prompt or batch files, the error level may always return 0 (success) even if the ping fails. This is because the ping command returns 0 (success) in its exit code regardless of whether the ping was successful or not.

To get around this, you can redirect the output of the ping command to a file and then check the contents of the file to determine whether the ping was successful or not. Here's an example:

bash
@echo off
setlocal EnableDelayedExpansion

for /L %%i in (1,1,10) do (
ping -n 1 google.com > pingresult.txt
find "Reply" pingresult.txt > nul
if errorlevel 1 (
echo Ping failed
) else (
echo Ping succeeded
)
)

In this example, we use the ping command to ping google.com with a timeout of 1 second and redirect the output to a file called pingresult.txt. We then use the find command to search for the string "Reply" in the output file. If the find command is successful (i.e. it finds the string "Reply"), the ping is considered successful and the errorlevel variable is set to 0 (success). If the find command is not successful (i.e. it does not find the string "Reply"), the ping is considered failed and the errorlevel variable is set to 1 (failure).

Note that in this example, we are using delayed expansion of variables (EnableDelayedExpansion) to allow us to use the !errorlevel! syntax inside the for loop. Without delayed expansion, the errorlevel variable would be evaluated only once before the loop, and any subsequent changes to the variable inside the loop would not be reflected in the if statement.