2

Possible Duplicate:
Make an environment variable survive ENDLOCAL
How to keep the value of a variable outside a Windows batch script which uses “delayed expansion local” mode?

I have a batch file that goes something like this:

REM I need to use SETLOCAL so as not to pollute the environment
REM with any variables used to implement the logic in this script
SETLOCAL
SET I_DONT_WANT_THIS_VARIABLE_TO_LEAK_OUTSIDE=c:\

REM BUT, there is this one change to the environment I want to make sticky:
PATH %PATH%;%I_DONT_WANT_THIS_VARIABLE_TO_LEAK_OUTSIDE%

The script uses SETLOCAL to isolate the environment from whatever the batch file wants to do, but this causes a problem: at the end I do want to modify the caller's environment in some very specific manner, but SETLOCAL prevents this (the change is undone as soon as the batch file exits). I also cannot call ENDLOCAL before setting the path because that restores the environment to its original state, wiping out the value of the variable so I cannot append its value to the path.

Is there a way to set the path while ignoring the SETLOCAL in effect? Alternatively, is there any trick to explicitly preserve the value of a variable from being wiped out when calling ENDLOCAL?

I am aware that it's possible to use a temp file as a vessel that can bypass the ENDLOCAL barrier, but a more elegant solution would be welcome.

Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806

1 Answers1

5

Add this to the end of your script (or just before you return):

endlocal & @set path=%path%

The reason that this works is that the cmd parser performs environment variable expansion to the entire line before executing any of it. So by the time endlocal executes, the line that cmd is processing looks like:

endlocal & @set path=c:\whatever\the;c:\new\path;c:\is

Then endlocal throws away all the local changes, but the ones made to the path have been temporarily preserved in the set command that's about to be executed.

Michael Burr
  • 333,147
  • 50
  • 533
  • 760
  • The `@` is optional, of course. If multiple variables need to be saved, `endlocal & (
    set var1=%var1%
    set var2=%var2%
    ...
    )` may be slightly more convenient.
    – Andriy M Jan 26 '13 at 22:59
  • Like the egg of Columbus: obvious in retrospect. Thanks! – Jon Jan 26 '13 at 23:02
  • @Jon: almost nothing in cmd scripting is obvious beyond executing a simple list of commands. – Michael Burr Jan 26 '13 at 23:04