Sorry, your attempt is not even closed. if not errorlevel 0 is valid only if the error level is negative.
If you know that the error rate will never be negative, then
if errorlevel 1 (echo error level is greater than 0)
If you must resolve the negative error rate and not be in parentheses in the code, then
set "errorlevel=1" set "errorlevel=" if %errorlevel% neq 0 (echo error level is non-zero)
Note. I edited my answer to explicitly clear any user-defined error level value after reading Joey's comment on the related answer in the question. A user-defined error level may mask the dynamic value that we are trying to access. But this only works if your script has a .bat extension. Scripts with the .cmd extension will set your ERRORLEVEL to 0 if you set or clear the variable! Worse, XP will set ERRORLEVEL to 1 if you try to define an undefined variable that does not exist. That's why I first explicitly define an ERRORLEVEL variable before trying to clear it!
If you are in the parenthesis of the code, you must use the delayed extension to get the current value
setlocal enableDelayedExpansion ( SomeCommandThatMightGenerateAnError set "errorlevel=1" set "errorlevel=" if !errorlevel! neq 0 (echo error level is non-zero) )
But sometimes you do not want pending extension enabled. All is not lost if you want to check the error level immediately after the command.
( SomeCommandThatMightGenerateAnError && (echo Success, no error) || (echo There was an error) )
If you absolutely must check the dynamic value of ERRORLEVEL without using slow expansion in brackets in brackets, then the following works. But it has error handling code in two places.
( SomeCommandThatMightGenerateAnError if errorlevel 1 (echo errorlevel is non-zero) else if not errorlevel 0 (echo errorlevel is non-zero) )
Here, finally, there is a βfinalβ test for nonzero errrelvel, which should work under any circumstances :-)
( SomeCommandThatMightGenerateAnError set foundErr=1 if errorlevel 0 if not errorlevel 1 set "foundErr=" if defined foundErr echo errorlevel is non-zero )
It can even be converted to a macro for ease of use:
set "ifErr=set foundErr=1&(if errorlevel 0 if not errorlevel 1 set foundErr=)&if defined foundErr" ( SomeCommandThatMightGenerateAnError %ifErr% echo errorlevel is non-zero )
The macro supports brackets and ELSE is just fine:
%ifErr% ( echo errorlevel is non-zero ) else ( echo errorlevel is zero )
Last question:
Redirection of input and / or output may fail for a number of reasons. But redirection errors do not set the error level unless the || . See File redirection on Windows and% errorlevel% for more details . Therefore, it can be argued that there is no reliable way to check for errors using the error level. The most reliable method (but not yet infallible) is the || .