0

我正在尝试在 For 循环之外使用变量。循环内的回声给出了预期的结果。当我在循环外回显变量时它不起作用。下面是脚本-

'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%! `
4

1 回答 1

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

于 2014-06-20T09:30:01.380 回答