Is there a way to pass parameters “by name” (and not by order) to a batch .bat file?

前端 未结 9 1734
情话喂你
情话喂你 2021-01-30 20:35

I need to be able to pass parameters to a windows batch file BY NAME (and NOT by order). My purpose here is to give end user the flexibility to pass parameters in any order, and

9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-30 21:16

    Take this attempt (pure batch):

    set PARAM_0=0
    :parameters_parse
    
    set parameter=%~1
    if "%parameter%"=="" goto parameters_parse_done
    if "%parameter:~0,1%"=="-" (
        set ARG_%parameter:~1%="%~2"
        shift
        shift
        goto parameters_parse
    )
    if "%parameter:~0,1%"=="/" (
        set ARG_%parameter:~1%="%~2"
        shift
        shift
        goto parameters_parse
    )
    set /a PARAM_0=%PARAM_0%+1
    set PARAM_%PARAM_0%="%~1"
    shift
    goto parameters_parse
    
    :parameters_parse_done
    
    rem Insert your script here
    

    and some tests:

    call args.bat /bar="Hello World" Test1 -baz "Test test test" /foo=Test1 Test2
    
    echo foo=%ARG_foo%
    echo bar=%ARG_bar%
    echo baz=%ARG_baz%
    echo count=%PARAM_0%
    echo 1=%PARAM_1%
    echo 2=%PARAM_2%
    

    Outputs:

    foo="Test1"
    bar="Hello World"
    baz="Test test test"
    count=2
    1="Test1"
    2="Test2"
    

提交回复
热议问题