Link to home
Start Free TrialLog in
Avatar of brucehobbs

asked on

enabledelayedexpansion and capturing errorlevel

Can someone help me understand why even with "enabledelayedexpansion" the value of %ERRORLEVEL% on line 11 of the attached code snippet is still zero?

I think I've identified two workarounds:

1) Replacing line 9 with "if %ERRORLEVEL% gtr 0 (" seems to produce the expected result.
2) Without line 11 the expected value is returned in the last line of code.

Or am I completely misunderstanding something?

(The code snippet is obviously designed to fail.)
setlocal enabledelayedexpansion & pushd
call :INIT
popd & endlocal & exit %ERRORLEVEL%
if exist "C:\Junk" (
	echo -Junk exists!
) else (
	mkdir x?
	if errorlevel 1 (
		echo ****Unable to create directory
		exit /b %ERRORLEVEL%
exit /b %ERRORLEVEL%

Open in new window

Avatar of oBdA

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of brucehobbs


I think your second point is exactly what I was forgetting. (Insert headslap here.)

As for the first point, I'm not finding that either popd or endlocal are changing the errorlevel, but I'd certainly love to know if there is a document listing exactly which commands do so. Unless I'm missing something the two workarounds I noted appear to allow the errorlevel to percolate back up to the caller. I'm using "exit /b" for that specific purpose.

I completely understand your final point about a simple exit, but this script is being launched by SQL Server Agent (SQL Server 2000) and it seems to always report an "exit /b" as a successful execution regardless of the return code.
Thanks for reminding me about needing to use the exclamation point for delayed expansion.

It's only a secondary issue, but since popd and endlocal don't seem to change the errorlevel it seems simpler to me to stick with exit /b !ERRORLEVEL!