windows batch SET inside IF not working

var2 is set, but the expansion in the line echo %var2% occurs before the block is executed.
At this time var2 is empty.

Therefore the delayedExpansion syntax exists, it uses ! instead of % and it is evaluated at execution time, not parse time.

Please note that in order to use !, the additional statement setlocal EnableDelayedExpansion is needed.

setlocal EnableDelayedExpansion
set var1=true
if "%var1%"=="true" (
  set var2=myvalue
  echo !var2!
)

Leave a Comment