Dzyann
Dzyann

Reputation: 5208

Issues with variables when using EnableDelayedExpansion

I have 2 issues with my Batch file, I think they are due to EnableDelayedExpansion.

I am basing my script in this post from SO.

I need EnableDelayedExpansion for another part of my script, so I need to keep it.

This is my script:

@echo off
set myPath=Subfolder1
set folderList=input.txt
set originalPath=%~dp0  

cd %myPath%
setlocal EnableDelayedExpansion

:process

for /F "tokens=*" %%S in (%~dp0\%folderList%) do (
    echo Folder %%S
    REM echo Folder %%S prints: Folder folderName
    set testPath=C:\BatchTests\%%S\
    echo test path: %testPath%
    REM echo test path: %testPath% prints: test path:
)
echo %originalPath%
REM echo %originalPath% prints: C:\BatchTests\
cd %originalPath%
pause

testPath seems to be always empty, and the line cd %originalPath%.

What am I doing wrong? What is the right way to use/set testPath?

The second issue I am having is different, so I opened a separate question here.

Upvotes: 1

Views: 381

Answers (1)

jeb
jeb

Reputation: 82247

To use delayed expansion in batch you need to parts.

First you have to enable it with setlocal EnableDelayedExpansion.
And then you can expand any variable with exclamation marks instead of percent signs.

setlocal EnableDelayedExpansion
set var=origin
(
  set var=New Value
  echo Percent: %var%
  echo delayed: !var!
)

The output is

Percent: origin
delayed: New Value

Percent expansion is evaluated when a command or block is parsed.
Delayed expansion is evaluated when a command is executed.

Upvotes: 1

Related Questions