Batch file 批处理脚本获取参数以处理参数加1

Batch file 批处理脚本获取参数以处理参数加1,batch-file,delayedvariableexpansion,Batch File,Delayedvariableexpansion,我希望能够将下一个参数与当前参数进行比较。因此,当argVec等于“-define”时,我想回显下一个参数。我得到的结果是“y”,而不是“交货” 我的意见是: Cmd版本1——定义交付 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,

我希望能够将下一个参数与当前参数进行比较。因此,当argVec等于“-define”时,我想回显下一个参数。我得到的结果是“y”,而不是“交货”

我的意见是: Cmd版本1——定义交付

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
!]
,意思是“回显
!argVec[!
变量的内容,然后回显
y
,然后回显
]
变量的内容。由于您没有
!argVec[!
变量或
]
变量,因此这将减少为“回显
y

为了解决这个问题,网站上有很多很好的信息。出于您的目的,这篇文章的重要部分是:

当索引在FOR/IF中更改时获取元素的值,请将元素用两个百分比括起来,并在命令前面加上
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
我意识到,回显屏幕可能不是您的最终目标,因此,当您修改脚本以执行您真正希望它执行的操作时,请记住在整个“数组”周围使用双百分比,在索引周围使用感叹号,并在命令之前使用
call

例如,如果要添加比较条件,则将
argVec[y]
的内容设置为
调用中的临时变量,然后在
if
中使用临时变量,如下所示:

@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
您不能以这种方式“嵌套”延迟扩展:

@echo !argVec[!y!]!
有几种解决此问题的方法,如下所述;最有效的方法是:

for %%y in (!y!) do @echo !argVec[%%y]!
编辑:注释中说明的附加请求已解决

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

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

谢谢,但是如果我想添加比较条件,如果“%%argVec[!y!]%%”==“delivery”echo true1,我不知道如何使用那里的调用。@ThomasPham我编辑了答案以包含比较值的案例。最简单的方法是设置一个临时变量,然后在比较中使用临时变量。