0

I am running this code

SETLOCAL EnableDelayedExpansion
SET count=1
FOR /F "tokens=* delims= usebackq" %%x IN ("%myfilepath.txt%") DO (
SET POS=%%x
echo %POS%
)
ENDLOCAL

but the output is

SET POS = viawizard
echo is on
Joey
  • 344,408
  • 85
  • 689
  • 683
runaway57
  • 5
  • 4
  • possible duplicate of [Batch file variables initialized in a for loop](http://stackoverflow.com/questions/691047/batch-file-variables-initialized-in-a-for-loop) – Andriy M Jul 08 '14 at 09:40

1 Answers1

0

You see the value being assigned to the variable, but then you can not access this value

When a block of code (code enclosed in parenthesis) is parsed, all variable reads are replaced with the value in the variable before starting to execute the code, so, while executing, as there are no reads to the variable, if the value in the variable is changed inside the block the changed value can not be accessed.

Enabling delayed expansion you can change how this works. If you have a variable whose value changes inside a block, and you need to access the changed value from inside that same block, you can/must change the syntax from %var% to !var! for this variable (any variable in the same case), indicating to the parser that the read operation in the variable will be delayed until the execution of the command.

@echo off

    SETLOCAL EnableDelayedExpansion
    SET count=1
    FOR /F "usebackq delims=" %%x IN ("%myfilepath.txt%") DO (
        SET "POS=%%x"
        echo !POS!
    )
    ENDLOCAL
MC ND
  • 69,615
  • 8
  • 84
  • 126