batch-filecmdvariable-expansiondelayedvariableexpansion

How do SETLOCAL and ENABLEDELAYEDEXPANSION work?


I notice in most scripts, the two are usually in the same line as so:

SETLOCAL ENABLEDELAYEDEXPANSION

Are the two in fact separate commands and can be written on separate lines?

Will setting ENABLEDELAYEDEXPANSION have an adverse effect on a script if it is set on the first lines of the script and not disabled until the end of the script?


Solution

  • ENABLEDELAYEDEXPANSION is a parameter passed to the SETLOCAL command (look at setlocal /?)

    Its effect lives for the duration of the script, or an ENDLOCAL:

    When the end of a batch script is reached, an implied ENDLOCAL is executed for any outstanding SETLOCAL commands issued by that batch script.

    In particular, this means that if you use SETLOCAL ENABLEDELAYEDEXPANSION in a script, any environment variable changes are lost at the end of it unless you take special measures.