批处理脚本获取参数以处理参数加一

batch scripting getting arguments to handle argument plus one

我希望能够获取下一个参数以与当前参数进行比较。所以当 argVec 等于“--define”时,我想回显下一个参数。我得到结果 "y" 而不是 "delivery".

我的输入是: Cmd version version1 --define delivery

set inputArg=%*
setlocal enabledelayedexpansion
set Count=0
for %%x in (%inputArg%) do (
   set /A Count+=1
   set "argVec[!Count!]=%%~x"
)
for /L %%i in (1,1,%Count%) do echo %%i- !argVec[%%i]!
for /L %%x in (1,1,%Count%) do (
  set /A y=%%x+1
  @echo !y!
  @echo !argVec[%%x]!
  if "!argVec[%%x]!"=="--define" (
    @echo !argVec[!y!]!
  )
)
endlocal

当我将 @echo off 添加到脚本的顶部并 运行 它时,我得到以下输出:

1- version1
2- --define
3- delivery
2
version1
3
--define
y
4
delivery

如果我没理解错的话,问题出在倒数第三行的y

您得到 y 的原因是 @echo !argVec[!y!]!。这标记为 @echo!argVec[!y!]!,这意味着 "echo the contents of the !argVec[! variable, then echo y, then echo the contents of the ] variable. Since you don't have an !argVec[! variable or a ] variable, this reduces to "echo y".

要修复它,this SO answer 上有很多有用的信息。为了您的目的,post 的重要部分是:

To get the value of an element when the index change inside FOR/IF enclose the element in double percents and precede the command with call.

我认为这是您脚本的一个版本,可以满足您的要求:

@echo off
set inputArg=%*
setlocal enabledelayedexpansion
set Count=0
for %%x in (%inputArg%) do (
   set /A Count+=1
   set "argVec[!Count!]=%%~x"
)
for /L %%i in (1,1,%Count%) do echo %%i- !argVec[%%i]!
for /L %%x in (1,1,%Count%) do (
  set /A y=%%x+1
  @echo !y!
  @echo !argVec[%%x]!
  if "!argVec[%%x]!"=="--define" (
    @call echo %%argVec[!y!]%%
  )
)
endlocal

打印:

1- version1
2- --define
3- delivery
2
version1
3
--define
delivery
4
delivery

我知道回显到屏幕可能不是你的最终目标,所以当你修改脚本来做你真正想要它做的事情时,记得在整个 "array" 周围使用双百分号,感叹号指向索引,并在您的命令之前加上 call.

例如,如果要添加比较条件,则将argVec[y]的内容设置为call中的临时变量,然后在[=33]中使用临时变量=],像这样:

@echo off
set inputArg=%*
setlocal enabledelayedexpansion
set Count=0
for %%x in (%inputArg%) do (
   set /A Count+=1
   set "argVec[!Count!]=%%~x"
)
for /L %%i in (1,1,%Count%) do echo %%i- !argVec[%%i]!
for /L %%x in (1,1,%Count%) do (
  set /A y=%%x+1
  @echo !y!
  @echo !argVec[%%x]!
  @call set tmpvar=%%argVec[!y!]%%
  if "!tmpvar!"=="--define" (
    echo "found it"
  )
)
endlocal

最新输出:

1- version1
2- --define
3- delivery
2
version1
"found it"
3
--define
4
delivery

你不能"nest"这样延迟扩展:

@echo !argVec[!y!]!

有几种方法可以解决这个问题,here;最有效的是这个:

for %%y in (!y!) do @echo !argVec[%%y]!

编辑注释中所述的其他请求已解决

您可以使用相同的方法获取 argVec[!y!] 的值并以任何您希望的方式使用它。例如:

for %%y in (!y!) do if "!argVec[%%y]!"=="delivery" echo true1