简体   繁体   English

Windows批处理脚本:ENABLEDELAYEDEXPANSION + For循环无法按预期工作

[英]Windows batch script: ENABLEDELAYEDEXPANSION + For Loop not working as expected

I'm not sure how to make the following code work. 我不确定如何使以下代码正常工作。 The loop is not returning all supposed files and %%~FI only expands at the beginning of the FOR loop. 该循环不会返回所有假定的文件,并且%%~FI仅在FOR循环开始时扩展。 By the time the last command executes, "%%~FI" yields a literal string rather than expanding to the desired file name: 到最后一条命令执行时, "%%~FI"产生文字字符串,而不是扩展为所需的文件名:

SETLOCAL ENABLEDELAYEDEXPANSION
FOR %%I IN (*.foo *.bar) DO (
    SET OFileBase=%%~DPNI
    ECHO "%%~FI" REM Expands correctly at this point
    :WhileLoop2
    IF EXIST "!OFileBase!.baz" (
        SET /A SuffixIndex += 1
        SET OFileBase=%%~DPNI [!SuffixIndex!]
        GOTO WhileLoop2
    )
    ECHO "%%~FI" REM Expands no more, now a literal string?!
    fooparser.exe --input "%%~FI" - | bazmaker.exe - "!OFileBase!.baz"
)
ENDLOCAL

What am I doing wrong? 我究竟做错了什么?

SETLOCAL ENABLEDELAYEDEXPANSION
FOR %%I IN (*.foo *.bar) DO (
    SET OFileBase=%%~DPNI
    ECHO "%%~FI" REM Expands correctly at this point
    call :WhileLoop2 "%%~DPNI"
    ECHO "%%~FI" REM Expands no more, now a literal string?!
    fooparser.exe --input "%%~FI" - | bazmaker.exe - "!OFileBase!.baz"
)
ENDLOCAL
goto :eof

:WhileLoop2
IF EXIST "!OFileBase!.baz" (
 SET /A SuffixIndex += 1
 SET OFileBase=%~1 [!SuffixIndex!]
 GOTO WhileLoop2
)
goto :eof

Always difficult working with an isolated segment of a batch - especially one that's obviously been santitised further. 始终很难处理一批中的孤立部分-尤其是显然已被进一步杀菌的部分。

Your problem is attempting to use a label within a block statement (a parenthesised series of statements). 您的问题是试图在block语句(带括号的一系列语句)中使用标签。 Not a good idea - confuses FOR and terminates the loop. 这不是一个好主意-混淆FOR并终止循环。

Since you are using the metavariable %%I within the inner loop, pass it as a quoted parameter (in case %%I contains separators) to a subroutine, then access the value within the subroutine as %~1 which removes the quotes. 由于您正在内部循环中使用元变量%%I ,因此请将它作为带引号的参数(以防%%I包含分隔符)传递给子例程,然后以%~1访问子例程中的值,从而删除引号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM