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

前端 未结 9 1724
情话喂你
情话喂你 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 20:55

    A bit late to the party :) This is my suggestion for managing "posix like" options. For example mybatchscript.bat -foo=foovalue -bar=barvalue -flag

    :parseArgs
    :: asks for the -foo argument and store the value in the variable FOO
    call:getArgWithValue "-foo" "FOO" "%~1" "%~2" && shift && shift && goto :parseArgs
    
    :: asks for the -bar argument and store the value in the variable BAR
    call:getArgWithValue "-bar" "BAR" "%~1" "%~2" && shift && shift && goto :parseArgs
    
    :: asks for the -flag argument. If exist set the variable FLAG to "TRUE"
    call:getArgFlag "-flag" "FLAG" "%~1" && shift && goto :parseArgs
    
    
    :: your code here ...
    echo FOO: %FOO%
    echo BAR: %BAR%
    echo FLAG: %FLAG%
    
    goto:eof
    

    ..and here the functions that do the job. You should put them in the same batch file

    :: =====================================================================
    :: This function sets a variable from a cli arg with value
    :: 1 cli argument name
    :: 2 variable name
    :: 3 current Argument Name
    :: 4 current Argument Value
    :getArgWithValue
    if "%~3"=="%~1" (
      if "%~4"=="" (
        REM unset the variable if value is not provided
        set "%~2="
        exit /B 1
      )
      set "%~2=%~4"
      exit /B 0
    )
    exit /B 1
    goto:eof
    
    
    
    :: =====================================================================
    :: This function sets a variable to value "TRUE" from a cli "flag" argument
    :: 1 cli argument name
    :: 2 variable name
    :: 3 current Argument Name
    :getArgFlag
    if "%~3"=="%~1" (
      set "%~2=TRUE"
      exit /B 0
    )
    exit /B 1
    goto:eof
    

    Save the file as mybatchscript.bat and run

    mybatchscript.bat -bar=barvalue -foo=foovalue -flag
    

    You'll get:

    FOO: foovalue
    BAR: barvalue
    FLAG: TRUE
    

提交回复
热议问题