0

I have a script that has a lot of use of the SETLOCAL ENABLEDELAYEDEXPANSION command, so I start the script off that way (less headaches). However, it does not allow you to use the ! character without escaping each instance of it (and I want to create a long line of !s for an error logging section =D ) and I don't want to escape every one of them.

Is there a way to temporarily break out of SETLOCAL, then reenter it keeping all previously created variables within the original SETLOCAL?

For example:

SETLOCAL ENABLEDELAYEDEXPANSION
set var=HELLO
ECHO %var%
ENDLOCAL

SETLOCAL ENABLEDELAYEDEXPANSION
ECHO %var%

The 2nd ECHO will not give you the previous value of var

EDIT: ^ will not allow you to escape the ! inside SETLOCAL ENABLEDELAYEDEXPANSION

Anthony Miller
  • 15,101
  • 28
  • 69
  • 98

2 Answers2

1
setlocal DisableDelayedExpansion
set var=Value! with! many! Bangs!
setlocal EnableDelayedExpansion
echo !var!
Aacini
  • 65,180
  • 12
  • 72
  • 108
1

You can nest it like Aacini shows it.
Or you can use the return technic or escape ! inside a EnableDelayed block with ^^!

Setlocal EnableDelayedExpansion
echo 1^^!^^!^^!^^!^^!^^!^^!
REM *** Or use a self removing quote
echo !="! 2^!^!^!^!^!^!

Setlocal DisableDelayedExpansion
echo 3 !!!!!!!!
set var=Hello
(
  endlocal
  rem Bring the value behind the endlocal barrier
  set var=%var%
)

echo var is still there, %var%

The return technic can also be used for exclamation marks, but then it is a bit more complex.
It can be found at Make an environment variable survive ENDLOCAL

Community
  • 1
  • 1
jeb
  • 78,592
  • 17
  • 171
  • 225