I see your errorlevel and raise you a process exit code

Have you ever written a batch file that is more of a “application” than a script? Of course you made sure ERRORLEVEL is set correctly so when your batch file is a part of a larger script, IF ERRORLEVEL error checking can be used. What could go wrong?

For some crazy reason, cmd.exe does not use the expected logic when you use the && and/or || syntax. I assume part of the problem is because the batch file is executed by cmd.exe itself and there is no child process and no real process exit code.

Fixing this requires some hacky workarounds and is generally a big pain in the ass.

Method 1:

@echo off
setlocal
set ec=0
if /I "%~1"=="fail" set ec=1

REM This next line MUST be the last line in the file!
@%COMSPEC% /C exit %ec% >nul

Method 2:

@echo off
setlocal
set ec=0
if /I "%~1"=="fail" set ec=1
goto q

:q_
exit /B %1
:q
REM To preserve ERRORLEVEL, the next line MUST be the last line in the file!
call :q_ %ec%
Advertisements

Tags: , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s