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

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

    I wanted to see the possibility of reading named parameter supplied to a batch program. For example :

    myBatch.bat arg1  arg2 
    

    Reading parameter can be done as follows :

    %~1 would be arg1
    %~2 would be arg2
    

    Above argument supplied to batch program is easy to read but then each time you execute it, you have to maintain order and remember what arg1 is supposed to have. In order to overcome it, parameter can be supplied as key:value format. And command would look like below :

    mybatch.bar key1:value1 key2:value2
    

    Though there is no straight forward way to parse such argument list. I wrote following nested for loop in batch script which will basically parse and create environment variable with key1 as name, and value1 assigned to it. This way you can read all argument supplied using straight forward way of reading environment variable.

    @echo off
    FOR %%A IN (%*) DO (
       FOR /f "tokens=1,2 delims=:" %%G IN ("%%A") DO setLocal %%G=%%H
    )
    

    Afterwards, you can use %key1% format to read all argument being supplied.

    HTH

提交回复
热议问题