无法使用 % 显示变量

Unable to display variable using %

我正在查看一个能够在循环外显示变量的示例批处理文件:

@echo off
setlocal EnableDelayedExpansion 
:: count to 5 storing the results in a variable
set _tst=0
FOR /l %%G in (1,1,5) Do (echo [!_tst!] & set /a _tst+=1)
echo Total = %_tst%

它能够回显 %_tst% 因为它在循环之前在顶部声明。

我用当前正在使用的批处理文件进行了尝试:

@echo off
cls
setlocal EnableDelayedExpansion

set drive=R:
set counter=0

FOR /F "tokens=*" %%c IN ('dir %USERPROFILE%\Backup /B') DO (set /A counter+=1)

if %counter% GTR 0 (
    echo Total # of folders: %counter%  
) else (
    echo No folders to move
)

它有效,但是,当我尝试在执行循环之前检查驱动器是否可用时,我使用了 !counter!访问变量,像这样:

如果我不这样做,它只是说 "Please press any key to continue." 因为停顿。

@echo off
cls

setlocal EnableDelayedExpansion

set drive=R:
set counter=0

if exist %drive% (

    FOR /F "tokens=*" %%c IN ('dir %USERPROFILE%\Backup /B') DO (set /A counter+=1)

    if !counter! GTR 0 (
        echo You have !counter! folder(s)
    ) else (
        echo No folders to move
    )
)
pause
exit /b

为什么当我有 if 语句检查我的驱动器是否可用时我必须使用 !counter!

文本 file(s) 中的 ) 有问题 - 这会关闭内部 if !counter! GTR 0 块。然后它看到另一个 ) 关闭外部 if exist %drive% 块。

要解决此问题,请转义 echo 中的 ):

if exist %drive% (

    FOR /F "tokens=*" %%c IN ('dir %USERPROFILE%\Backup /B') DO (set /A counter+=1)

    if !counter! GTR 0 (
        echo You have !counter! folder^(s^)
    ) else (
        echo No folders to move
    )
)