如何在批处理脚本中的第n个参数后迭代输入参数

时间:2016-06-05 06:33:17

标签: batch-file

请检查以下代码并更正。提前谢谢。

  

启动test.bat A B C D E F G H

set argCount=0

for  %%x in (%*) do (

set /A argCount+=1   
    if %argCount% gtr 3 (

    echo element after 3 argument %%x   
    )
 )

echo Number of processed arguments: %argCount%

2 个答案:

答案 0 :(得分:1)

您需要delayed expansion

setlocal enableDelayedExpansion
set argCount=0

for  %%x in (%*) do (
    set /A argCount+=1   
    if !argCount! gtr 3 (
     echo element after 3 argument %%x   
    )
 )
echo Number of processed arguments: %argCount%

答案 1 :(得分:0)

哇! Original npocmaka's code不起作用!

==> D:\bat\SO\37639143npocmaka.bat Wow! Original npocmaka's code does not work!
Number of processed arguments: 1

您需要按如下方式切换延迟扩展:

SETLOCAL EnableExtensions DisableDelayedExpansion

set argCount=0

for  %%x in (%*) do (
    set /A argCount+=1
    setlocal EnableDelayedExpansion   
    if !argCount! gtr 3 (
       endlocal
       echo element after 3 argument %%x   
    ) else endlocal
 )
echo Number of processed arguments: %argCount%

输出:

==> D:\bat\SO\37639143.bat Wow! Original npocmaka's code does not work!
element after 3 argument code
element after 3 argument does
element after 3 argument not
element after 3 argument work!
Number of processed arguments: 7

或者,省略delayed expansion并修改下一个代码片段(我未更改的样本脚本):

@echo OFF
SETLOCAL EnableExtensions DisableDelayedExpansion
echo(
echo  before any shift:  all %%* = [%*]
echo(
set /A "ii=0"
  echo param %%%ii% = %0
:loopfor
  set /A "ii+=1"
  echo param %%%ii% = %1
  SHIFT /1
  if not [%1]==[] goto :loopfor
echo(
echo  after %ii% shifts: %%* = [%*]
goto :eof

输出:

==> cliparser.bat Wow! Original npocmaka's code does not work!

 before any shift:  all %* = [Wow! Original npocmaka's code does not work!]

param %0 = cliparser.bat
param %1 = Wow!
param %2 = Original
param %3 = npocmaka's
param %4 = code
param %5 = does
param %6 = not
param %7 = work!

 after 7 shifts: %* = [Wow! Original npocmaka's code does not work!]

==>