批处理:if-block中的逃生阵列



我正在尝试检查数组中是否存在文件。阵列和循环工作正常,但是if exists -line给出了语法。我尝试了不同的变体(%%list[%x%]%%list[%x%]%%list[%%x%%]%%),但它们都没有起作用。

问题:为什么if exists %%list[%x%]%%不起作用,但是call echo Check file: %%list[%x%]%%起作用?

提示:我使用这种"循环",因为我希望如果数组的大小更改,则必须更改编码。

set list[0]="C:file_a.txt"
set list[1]="C:file_b.txt"
set list[2]="C:file_c.txt"
set "found=0"
set "notfound=0"
set "x=0"
:SymLoop
if defined list[%x%] (
    call echo Check file: %%list[%x%]%%
    if exists %%list[%x%]%% (
        set /a "found+=1"
    ) else (
        set /a "notfound+=1"
    )
    set /a "x+=1"
    GOTO :SymLoop
)
echo %found%/%x% file found. %notfound% files missing!
PAUSE

已解决:问题是缺少的"延迟扩展",此外还有错字(存在而不是存在)。

尝试这样:

setlocal EnableDelayedExpansion
set list[0]="C:file_a.txt"
set list[1]="C:file_b.txt"
set list[2]="C:file_c.txt"
set "found=0"
set "notfound=0"
set "x=0"
:SymLoop
if defined list[%x%] (
    echo Check file: !list[%x%]!
    if exist !list[%x%]! (
        set /a "found+=1"
    ) else (
        set /a "notfound+=1"
    )
    set /a "x+=1"
    GOTO :SymLoop
)
echo %found%/%x% file found. %notfound% files missing!
PAUSE

最新更新