Batch-Script - Iterate through arguments

前端 未结 6 590
暖寄归人
暖寄归人 2020-12-08 18:49

I have a batch-script with multiple arguments. I am reading the total count of them and then run a for loop like this:

@echo off
setlocal enabledelayedexpans         


        
相关标签:
6条回答
  • 2020-12-08 19:31
    @echo off
    setlocal enabledelayedexpansion
    
    set argCount=0
    for %%x in (%*) do (
       set /A argCount+=1
       set "argVec[!argCount!]=%%~x"
    )
    
    echo Number of processed arguments: %argCount%
    
    for /L %%i in (1,1,%argCount%) do echo %%i- "!argVec[%%i]!"
    

    For example:

    C:> test One "This is | the & second one" Third
    Number of processed arguments: 3
    1- "One"
    2- "This is | the & second one"
    3- "Third"
    

    Another one:

    C:> test One Two Three Four Five Six Seven Eight Nine Ten Eleven Twelve etc...
    Number of processed arguments: 13
    1- "One"
    2- "Two"
    3- "Three"
    4- "Four"
    5- "Five"
    6- "Six"
    7- "Seven"
    8- "Eight"
    9- "Nine"
    10- "Ten"
    11- "Eleven"
    12- "Twelve"
    13- "etc..."
    
    0 讨论(0)
  • :loop
    @echo %1
    shift
    if not "%~1"=="" goto loop
    
    0 讨论(0)
  • 2020-12-08 19:37

    If to keep the code short rather than wise, then

    for %%x in (%*) do (
       echo Hey %%~x 
    )
    
    0 讨论(0)
  • 2020-12-08 19:44
    @ECHO OFF
    SETLOCAL
    SET nparms=0
    FOR /l %%i IN (1,1,20) DO (
     SET myparm=%%i
     CALL :setparm %*
     IF DEFINED myparm SET nparms=%%i&CALL ECHO Parameter %%i=%%myparm%%
    )
    ECHO there were %nparms% parameters in %*
    GOTO :EOF
    
    :setparm
    IF %myparm%==1 SET myparm=%1&GOTO :EOF
    shift&SET /a myparm -=1&GOTO setparm
    GOTO :eof
    

    This should show how to extract random parameters by position.

    0 讨论(0)
  • 2020-12-08 19:47

    here's one way to access the second (e.g.) argument (this can be put in for /l loop):

    @echo off
    setlocal enableDelayedExpansion
    set /a counter=2
    call echo %%!counter!
    endlocal
    

    so:

    setlocal enableDelayedExpansion
    set /a counter=0
    for /l %%x in (1, 1, %argCount%) do (
     set /a counter=!counter!+1
     call echo %%!counter! 
    )
    endlocal
    
    0 讨论(0)
  • 2020-12-08 19:49

    For simple iteration can't we just check for additional arguments with "shift /1" at the end of the code and loop back? This will handle more than 10 arguments, upper limit not tested.

    :loop
    
    :: Your code using %1
    echo %1
    
    :: Check for further batch arguments.     
    shift /1
    IF [%1]==[] (
    goto end
    ) ELSE (
    goto loop
    )
    
    :end
    pause
    
    0 讨论(0)
提交回复
热议问题