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?
Consider the following call to batch file ParamTest.cmd:
C:\Paramtest.cmd \A valueA \B valueB
Here's the contents of 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 TWO values passed by their switch names, A and B, regardless of teh order in which these switches were passed
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
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:
…
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:
…
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.
精彩评论