Batch : Checking the number of parameters

后端 未结 3 1877
名媛妹妹
名媛妹妹 2021-02-18 22:55

I\'d like to make sure that when calling my batch, no more than 2 parameters are passed.

Is there an easy way to check that, or do I have to call SHIFT as many times as

相关标签:
3条回答
  • 2021-02-18 23:47
    IF NOT "%3"=="" GOTO Too_Many_Args
    
    0 讨论(0)
  • 2021-02-18 23:49

    You can simply test for existence of a third parameter and cancel if present:

    if not "%~3"=="" (
        echo No more than two arguments, please
        goto :eof
    )
    

    But more specifically, there is no direct way of getting the number of arguments passed to a batch, short of shifting and counting them. So if you want to make sure that no more than 19 arguments are passed, then you need to do exactly that. But if the number of expected arguments is below 9 above method works well.

    0 讨论(0)
  • 2021-02-18 23:59

    Here is my small example for gathering and parsing a list of arguments and passing to external command:

    @echo off
    setlocal enabledelayedexpansion
    
    if %1. EQU . (
        echo %~0 [-t NUM] FILE [FILE...]
        goto end
    )
    
    :args_loop
    if "%~1" EQU "-t" (
        set arg_t=%1
        set arg_t_val=%2
        shift
    ) else (
        set files=!files! %1
    )
    shift
    if %1. NEQ . goto args_loop
    
    :args_loop_end
    
    x:\path\to\external.exe %arg_t% %arg_t_val% %files%
    
    :end
    
    0 讨论(0)
提交回复
热议问题