windowsfor-loopbatch-filecmddelayedvariableexpansion

Why can't I access local variable in for loop (batch file) even with setlocal enabledelayedexpansion?


Trying to access a custom local variable in a FOR loop within a batch file, I keep getting ECHO is off.
Despite that enabledelayedexpansion is set and used with !_!, as numerous guides suggest..

What may be wrong and how such trick should be performed in this case?

@ECHO OFF

for %%I IN (.) DO SET BatCurrPath = %%~fI
ECHO ---------------
ECHO %BatCurrPath%
ECHO ---------------

SETLOCAL ENABLEDELAYEDEXPANSION
for /d %%d IN (*.*) DO (
    SET DirFound = %%d
    ECHO !DirFound!      <==== outputs "ECHO is off"
    ECHO %%d             <==== outputs child's dirname
)
ENDLOCAL

Solution

  • Try like this:

    @ECHO OFF
    
    for %%I IN (.) DO SET "BatCurrPath=%%~fI"
    ECHO ---------------
    ECHO %BatCurrPath%
    ECHO ---------------
    
    SETLOCAL ENABLEDELAYEDEXPANSION
    for /d %%d IN (*.*) DO (
        SET "DirFound=%%d"
        ECHO !DirFound!     
        ECHO %%d            
    )
    ENDLOCAL
    

    Dont use spaces around = otherwise the spaces will become part of the variable name.