Eric Hartwell's InfoDabble

April 2005
Sun Mon Tue Wed Thu Fri Sat
          1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
Mar   May


 Saturday, April 23, 2005
Bypass SETLOCAL/ENDLOCAL

Sometimes it would be nice if we could use SETLOCAL and ENDLOCAL to preserve the initial environment but still change one variable "permanently", in the SORTDATE and SORTTIME examples, for example. I recently saw a posting at the alt.msdos.batch.nt newsgroup where Phil Robyn solved this problem in an ingenious way:
SET TEST=
SETLOCAL
:: Variable test is set within local environment, which means
:: its changes are flushed by the next ENDLOCAL command
SET TEST=Some new value
:: By using the ampersand and the following SET command on the
:: same line as the ENDLOCAL command, %TEST% is resolved before
:: the ENDLOCAL command "restores" its value
ENDLOCAL & SET TEST=%TEST%
SET TEST
This way the environment variable TEST and its value are preserved in spite of the ENDLOCAL command.
See my Conditional Execution page for an explanation of the ampersand's usage
2:21:18 PM