Search code examples
batch-fileerrorlevel

Batch ERRORLEVEL results different from CMD?


Why does ERRORLEVEL behave differently in these two circumstances?

From the command line:

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\>aescrypt.exe -v 2> NUL

C:\>echo %errorlevel%
9009

Versus from batch file:

@echo off

set /P C="> "?

set or=
if "%C%"=="a" set or=1
if "%C%"=="A" set or=1
if defined or (
    aescrypt.exe -v 2> NUL
    echo %errorlevel%
)

Result:

> a
1

Solution

  • Remove you "@echo off" and see how the code is being executed. You might find that the errorlevel in example 2 is the result of the "if defined".

    Also, try this:

    @echo off
    set /P C="> "?
    set or=
    if /i "%C%"=="a" set or=1
    if not defined or goto SKIP
    aescrypt.exe -v 2> NUL
    echo %errorlevel%
    :SKIP