如何避免延迟扩展删除文件名中的感叹号?

How to avoid delayed expansion removing the exclamation marks in file names?

如何避免延迟扩展删除文件名中的感叹号?

@echo off

Set path="C:\example"
Set chars=a b c

cd /d %path%

setlocal EnableDelayedExpansion
for %%A in (%chars%) do (
    set filesList=
    for /F "tokens=* delims=" %%B in ('dir %%A^* /a-d /b') do (
        set filesList=!filesList!"%%~nxB"
    )
    if not "!filesList!"=="" (
        echo %%A filesList: !filesList!
    )
)
endlocal

按照 Mofi 的建议,您可以禁用延迟扩展并使用

call set filesList=%%filesList%%"%%~nxB"

但是当你的文件名中有插入符时,这会失败。

你的代码中的问题在于,FOR 参数只能在没有延迟扩展模式的情况下安全地扩展。
通常你会使用 toggline 技术,就像这里一样。

setlocal DisableDelayedExpansion
for /F "delims=" %%B in ('dir %%A^* /a-d /b') do  ( 
    set "line=%%B"

    setlocal EnableDelayedExpansion
    REM *** Process the content of line here
    echo !line!
    endlocal
)

但这只适用于您不需要将 line 的内容传输到(内部)setlocal 范围之外的情况。

在您的例子中,您尝试将 line 内容添加到范围外的 filesList 变量。 对于这种情况,您需要使用或多或少复杂的技术将 line 的内容传输到范围结束,例如
Make an environment variable survive ENDLOCAL
Macro to return multiple variables across endlocal barriers