0

I am trying to use the variable outside of the For loop. The echo inside the loop gives the result as expected. it is not working when i echo the variable outside of the loop. below is the script-

'SETLOCAL ENABLEDELAYEDEXPANSION
SET x=0
FOR /f "tokens=*" %%a in ('dir "%InPath%*_Out.txt" /b') DO (
SET /a x+=1& SET /a cnt+=1& SET Fname%x%=%%a& SET FDate%x%=!Fname%x%:~0,8!
ECHO %x% !cnt! !Fname%x%! !Date%x%!
)

set z=3
ECHO !FDate%z%! `
  • So - what is the routine showing, what is the result you see and what is the result you expect? – Magoo Jun 20 '14 at 08:44
  • Full details on array management in Batch files are given at: http://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990 – Aacini Jun 20 '14 at 09:35

1 Answers1

1

What you have here is a bad interpretation of what you see. The for loop does not work (determined from what you are trying to do outside of the for loop).

This

Fname%x%=%%a
SET FDate%x%=!Fname%x%:~0,8!

is executed inside the loop. There is no delayed expansion over the x variable, so, changes in the value of the variable are not visible inside the for loop and all the iterations are executed as

Fname0=%%a
SET FDate0=!Fname0:~0,8!

So, your claim that the code in the for loop works is not correct. Since it is not working, the code outside the for will not work as intended

You need something like

FOR /f "tokens=*" %%a in ('dir "%InPath%*_Out.txt" /b') DO (
    SET /a x+=1
    SET /a cnt+=1
    SET "Fname!x!=%%a"
    for %%b in (!x!) do (
        SET "FDate!x!=!Fname%%b:~0,8!"
        ECHO !x! !cnt! !Fname%%b! !FDate%%b!
    )
)

This will properly populate the "arrays" so your code outside the for loop will work

MC ND
  • 69,615
  • 8
  • 84
  • 126