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

前端 未结 9 1803
情话喂你
情话喂你 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:08

    Very old question, but I think I found a neat way (with no external dependencies) of passing key=value arguments to a batch file. You can test the method with the following MWE:

    @echo off
    chcp 65001
    
    rem name this file test.bat and call it with something like:
    rem test keyc=foo keyd=bar whatever keya=123 keyf=zzz
    
    setlocal enabledelayedexpansion
    
    set "map=%*"
    call :gettoken keya var1
    call :gettoken keyb var2
    call :gettoken keyc var3
    
    rem replace the following block with your real batch
    rem ************************************************
    echo:
    echo Map is "%map%"
    echo Variable var1 is "%var1%"
    echo Variable var2 is "%var2%"
    echo Variable var3 is "%var3%"
    echo:
    echo Done.
    echo:
    pause
    rem ************************************************
    
    goto :eof
    :gettoken
    call set "tmpvar=%%map:*%1=%%"
    if "%tmpvar%"=="%map%" (set "%~2=") else (
    for /f "tokens=1 delims= " %%a in ("%tmpvar%") do set tmpvar=%%a
    set "%~2=!tmpvar:~1!"
    )
    exit /b
    

    The method is quite:

    • fexible, because key=value arguments can be mixed with other arguments (such as filenames), and because the name of the variable used to store the value is independent from the name of key
    • scalable, because it's easy to add keys
    • robust, because anything passed that is not allowed by defined keys is ignored, and unassigned keys get an empty value (if you want you can easily change this behaviour so they get something like null or undefined instead of empty)

    Enjoy.

提交回复
热议问题