I want to get particular exit code for each output in for loop which I am printing(echo). I want to use that exit code and give particular output.
for /f "tokens=* delims=" %%i in (list.txt) do ping -n 3 %%i >nul && if /i "ERRORLEVEL" == "0" (
echo %%i Alive
) else (
echo %%i Failed
)
CodePudding user response:
There is no need to get the errorlevel
by literally specifying it for each result. The exitcode
/errorlevel
can be evaluated by using conditional operators &&
and ||
So all you need is:
@echo off
for /f "usebackq delims=" %%i in ("list.txt") do ping -n 3 %%i >nul 2>&1 && echo %%i Alive || echo %%i Failed
What happens is simple. The errorlevel
or exit
code is evaluated. If it the errorlevel
is 0
it is a success and it will use the &&
operator to fire the next command. if it is 1
or larger, it will constitute as an error and it will use the or operator ||
and perform the relevent command.
If however you MUST use the errorlevel
or %errorlevel
literally:
@echo off
for /f "usebackq delims=" %%i in ("list.txt") do (
ping -n 3 %%i >nul 2>&1
if errorlevel 1 (
echo %%i Failed
) else (
echo %%i Alive
)
)
Obviously without needing delayedexpansion
CodePudding user response:
The exact answer to your problem, as you stated it, is this:
@echo off
setlocal EnableDelayedExpansion
for /f "delims=" %%i in (list.txt) do ping -n 3 %%i >nul 2>&1 & if "!ERRORLEVEL!" == "0" (
echo %%i Alive
) else (
echo %%i Failed
)
CodePudding user response:
for /f "tokens=* delims=" %%i in (list.txt) do (
set "reported="
ping -n 3 %%i >nul
call echo %%i responded with errorlevel %%errorlevel%%
if errorlevel 2 set "reported=y"&echo errorlevel 2 actions&cd .
if errorlevel 1 set "reported=y"&echo errorlevel 1 actions&cd .
if not defined reported echo errorlevel 0 actions
)
The string "ERRORLEVEL"
will never be equal to the string "0"
. You are looking for the value of errorlevel
, which would normally be %errorlevel%
BUT since you have used a code block
(a parenthesised sequence of statements) %errorlevel%
, like any variable would be replaced by its value at the time the code block is encountered, not as it changes when executed. See Stephan's DELAYEDEXPANSION link: https://stackoverflow.com/a/30284028/2128947
You can use if errorlevel?
as shown, but you must interrogate errorlevel
in reverse-order as if errorlevel n
is true for errorlevel
being n or greater than n.
The code shown will set errorlevel
to 0
(using cd .
) after whatever actions you choose to execute so any change to errorlevel
made by those actions is overridden and will not cause any of the other errorlevel
actions to be executed. If none of the actions is executed, reported
will remain undefined, so the fact that it's undefined tells us that the original errorlevel
was 0
.