如何批量地用变量对数组进行索引?

如何批量地用变量对数组进行索引?

我正在尝试处理批处理文件的输入参数,我需要在最后调用可执行文件之前将一些成对的参数绑定在一起。我将所有参数放入一个数组中,以便可以处理它们,但我无法找出批处理等效于“获取数组中下一个条目的值”。以下是我正在尝试的:

setlocal EnableDelayedExpansion 
set "Batchmode="
set "RelativePaths="
set "DbFile="
set "TemplateFile="
set "LuaFile="
set "LogFile="
set i=0
:TOP
IF (%1) == () GOTO END
    set args[!i!]=%1
    set /A i+=1
SHIFT
GOTO TOP
:END

set argsLength=!i!
echo argsLength: !argsLength!
for /l %%n in (0,1,!argsLength!) do ( 
    set /A nextIndex = %%n + 1
    echo n: %%n, arg: !args[%%n]!, nextIndex: !nextIndex!, nextIndexArg: !args[!nextIndex!]!
    if !args[%%n]! equ -batchMode set Batchmode=-batchMode
    if !args[%%n]! equ -relativePaths set RelativePaths=-relativePaths
    if !args[%%n]! equ -dbFile set DbFile=-dbFile !args[!nextIndex!]!
    if !args[%%n]! equ -templateFile set TemplateFile=-templateFile !args[!nextIndex!]!
    if !args[%%n]! equ -luaFile set LuaFile=-luaFile !args[!nextIndex!]!
    if !args[%%n]! equ -logFile set LogFile=-logFile !args[!nextIndex!]!
)

if !argsLength! geq 2 (
// do some input verification stuff here
)

start /wait "" "MyExeFileHere.exe" !Batchmode! !RelativePaths! !DbFile! !TemplateFile! !LuaFile! !LogFile!

我正在使用以下命令运行批处理文件:

<batchFilePathHere.bat> -batchMode -relativePaths -dbFile <dbFilePathHere.db>

我从 for 循环内的 echo 行获得的输出如下:

n:0,arg:-batchMode,nextIndex:1,nextIndexArg:nextIndex

n:1,arg:-relativePaths,nextIndex:2,nextIndexArg:nextIndex

n:2,arg:-dbFile,nextIndex:3,nextIndexArg:nextIndex

n:3,arg:myDbFilePathHere.db,nextIndex:4,nextIndexArg:nextIndex

n:4,arg:,nextIndex:5,nextIndexArg:nextIndex

我不明白为什么 !nextIndex! 单独运行时会计算 nextIndex 的值,而放在数组访问器中时却不会。我也尝试过使用 !args[nextIndex]!,但所有这些值都为空,我猜是因为它使用的是 nextIndex 的内存地址而不是值之类的,但显然我对批处理不太了解,所以我可能大错特错。

答案1

当前脚本的问题是 的!args[!nextIndex!]!求值方式与 类似!args[!, "nextIndex", !]!。批处理没有其他方法来指示延迟变量或在变量名内进行添加,因此对于参数对,最好的选择是创建第二个偏移数组,如下argsNext所示。我已经调整argsLength为基于 0:

@echo off
setlocal EnableDelayedExpansion 

set i=0
:TOP
IF (%1) == () GOTO END
    set args[!i!]=%1
    set argsNext[!i!]=%2
    set /A i+=1
SHIFT
GOTO TOP
:END

set /A i=%i%-1
set argsLength=!i!
echo argsLength: !argsLength!
for /l %%n in (0,1,!argsLength!) do ( 
    set /A nextIndex = %%n + 1
    echo n: %%n, arg: !args[%%n]!, nextIndex: !nextIndex!, nextIndexArg: !argsNext[%%n]!
)

输出如下:

c:\test>test.bat a b c
argsLength: 2
n: 0, arg: a, nextIndex: 1, nextIndexArg: b
n: 1, arg: b, nextIndex: 2, nextIndexArg: c
n: 2, arg: c, nextIndex: 3, nextIndexArg:  

相关内容