windows 使用开关将参数传递到批处理文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6226587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing parameters with switches to a batch file
提问by Chad
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:
输出:
Param1=\A
Param2=valueA
Param3=\B
Param4=valueB
I would like to be able to identify TWOvalues 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:
..即使我在参数顺序切换的情况下调用批处理文件,也具有相同的输出:
C:\Paramtest.cmd \A valueA \B valueB
C:\Paramtest.cmd \A 值A \B 值B
How do I do this?
我该怎么做呢?
回答by Andriy M
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. The first method is more flexible, in my opinion.
但是对于您的情况来说有点困难,因为您需要成对处理参数。在我看来,第一种方法更灵活。