Search code examples
batch-fileconditional-statementserrorlevel

ERRORLEVEL conditions


Should this logic not send 0 and 1 error levels to the 'mailerror' subroutine and simply exit if they are 0 or 1 errors?

IF %ERRORLEVEL% NEQ 0 (
    IF %ERRORLEVEL% NEQ 1 (   
    SET BODY="exit error code from Backup of RAD file = %ERRORLEVEL%."
    goto mailerror
    )
 ) ELSE (
 EXIT
 )

Solution

  • Firstly, you do not need all those parenthesis. Also, you are currently testing for errorlevel 0 and then 1, but your else is in the wrong place and therefore errorlevel 1 clause will do nothing (not exit):

    This would test and action exit on both errorlevel 0 and then errorlevel 1

    @echo off
    if %errorlevel% neq 0 if %errorlevel% neq 1 (
    set BODY="exit error code from Backup of RAD file = %errorlevel%."
    echo %body%
    goto mailerror
    )
    exit
    :mailerror
    echo %BODY%
    echo do something else..
    

    But seeing as you want to do anything other than errorlevel 0 and 1 you could simply do set if %errorlevel% greater than 1 (in otherwords not 0 or 1):

    @echo off
    if %errorlevel% GTR 1 (
    set BODY="exit error code from Backup of RAD file = %errorlevel%."
    goto mailerror
    )
    exit
    :mailerror
    echo %BODY%
    echo do something else..
    

    As per @Stephan's comment. Some rare programs generate a negative errorlevel, if that is the case the first option will do, or this:

    @echo off
    if %errorlevel% GTR 1 if %errorlevel% lss 0 (
    set BODY="exit error code from Backup of RAD file = %errorlevel%."
    goto mailerror
    )
    exit
    :mailerror
    echo %BODY%
    echo do something else..