I have several batch file tips to share. The first one deals with setlocal. This command will give you a context in which you can change environment variables without worrying about what they should be after your batch file. All you need to do is call setlocal at the beginning of your batch file and endlocal at the end.
@ECHO OFF VERIFY OTHER 2>nul SETLOCAL ENABLEEXTENSIONS IF ERRORLEVEL 1 GOTO :NOEXT REM Body of batch file here. SET MODIFY=Any ENV Vars Here SET _RETURN=42 :DONE ENDLOCAL & SET _RETURN=%_RETURN% GOTO :EOF :NOEXT ECHO.This Batch file requires command extensions. :EOF
There are three tricks here.
The first trick is on line 02. That command will set an errorlevel. The setlocal enableextensions command will clear the errorlevel if it succeeds. The effect of this is that the command extensions (included since some version of NT4) will be enabled and a local environment will be created. Then we have the test to make sure it succeeded.
The second trick is line 11. Normally the endlocal command will clear the changes to the environment when it is run. That still happens. The trick comes in because CMD.EXE expands environment variables when it parses the line not when the command is run. So the environment variable _RETURN is expanded and set to the environment variable _RETURN outside our local context.
The third trick is the label :NOEXT on line 14. If command extensions do not work then we don’t want to try running the file. So, we write out an error message and the file completes.
References:
Leave a comment