1
votes

so i have really problems with the ERRORLEVEL of batch. Its just not working for me. I have a big own ms build batch script and i always get 0 back from ERRORLEVEL, whatever I do (eg. msbuild, tf get, tf checkout, copy, xcopy,...)

so i did a small example to post it here:

@echo off
set Update=1
IF %Update% == 1 (
    echo.
    set /p "=- Copy stuff..." <NUL
    xcopy /R /Y C:\test\2.lib   C:\test1
    if %ERRORLEVEL% neq 0 (echo FAILED!) ELSE (echo SUCCEED!)
    echo -^> done
    pause
)

so its always returning succeed and printing 0 when i do: echo %ERRORLEVEL%

can you please help me with that? I really would like to use that errorlevel

2

2 Answers

3
votes

you need delayed expansion here or to use IF ERRORLEVEL :

@echo off
set Update=1
IF %Update% == 1 (
    echo.
    set /p "=- Copy stuff..." <NUL
    xcopy /R /Y C:\test\2.lib   C:\test1
    IF ERRORLEVEL 1 (echo FAILED!) ELSE (echo SUCCEED!)
    echo -^> done
    pause
)

with IF ERRORLEVEL 1 you can check if the errorlevel is 1 or bigger .

1
votes

As npocmaka says, you have a delayed expansion issue.

An alternative is to ditch ERRORLEVEL and use the && and || conditional command concatenation operators instead.

@echo off
set Update=1
IF %Update% == 1 (
    echo.
    set /p "=- Copy stuff..." <NUL
    xcopy /R /Y C:\test\2.lib   C:\test1 && (echo SUCCEED!) || (echo FAILED!)
    echo -^> done
    pause
)

Edit showing use of multiple lines

@echo off
set Update=1
IF %Update% == 1 (
    echo.
    set /p "=- Copy stuff..." <NUL
    xcopy /R /Y C:\test\2.lib   C:\test1 && (
        echo First success command
        echo SUCCEED!
    ) || (
        echo First failure command
        echo FAILED!
    )
    echo -^> done
    pause
)