[英]Passing parameters with switches to a batch file
How do I display the value associated with switch A and switch B regardless of the order in which A and B was specified?无论指定 A 和 B 的顺序如何,如何显示与开关 A 和开关 B 关联的值?
Consider the following call to batch file ParamTest.cmd:考虑以下对批处理文件 ParamTest.cmd 的调用:
C:\Paramtest.cmd \A valueA \B valueB
Here's the contents of C:\Paramtest.cmd:下面是 C:\Paramtest.cmd 的内容:
ECHO Param1=%1
ECHO Param2=%2
ECHO Param3=%3
ECHO Param4=%4
Output: Output:
Param1=\A
Param2=valueA
Param3=\B
Param4=valueB
I would like to be able to identify TWO values passed by their switch names, A and B, regardless of teh order in which these switches were passed我希望能够识别通过它们的开关名称 A 和 B 传递的两个值,而不管这些开关的传递顺序如何
For example, if I execute the following call:例如,如果我执行以下调用:
C:\Paramtest.cmd \B valueB \A valueA
I would like to be able to display我希望能够显示
A=ValueA
B=ValueB
..and have the same output even if I called the batch file with the param order switched: ..并且具有相同的 output 即使我在切换参数顺序的情况下调用批处理文件:
C:\Paramtest.cmd \A valueA \B valueB C:\Paramtest.cmd \A valueA \B valueB
How do I do this?我该怎么做呢?
In short, you need to define a loop and process the parameters in pairs.简而言之,你需要定义一个循环并成对处理参数。
I typically process the parameter list using an approach that involves labels & GOTOs, as well as SHIFTs, basically like this:我通常使用涉及标签和 GOTO 以及 SHIFT 的方法处理参数列表,基本上像这样:
…
SET ArgA=default for A
SET ArgB=default for B
:loop
IF [%1] == [] GOTO continue
IF [%1] == [/A] …
IF [%1] == [/B] …
SHIFT & GOTO loop
:continue
…
It is also possible to process parameters using the %*
mask and the FOR
loop, like this:也可以使用
%*
掩码和FOR
循环来处理参数,如下所示:
…
SET ArgA=default for A
SET ArgB=default for B
FOR %%p IN (%*) DO (
IF [%%p] == [/A] …
IF [%%p] == [/B] …
)
…
But it's a bit more difficult for your case, because you need to process the arguments in pairs.但这对您的情况有点困难,因为您需要成对处理 arguments。 The first method is more flexible, in my opinion.
在我看来,第一种方法更灵活。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.