6

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?

Chad
  • 23,658
  • 51
  • 191
  • 321
  • 1
    you'd be much better off doing this in a real programming language, or lowering you expectations of batch – David Heffernan Jun 03 '11 at 11:50
  • http://stackoverflow.com/questions/761615/is-there-a-way-to-indicate-the-last-n-parameters-in-a-batch-file – ethrbunny Jun 03 '11 at 11:52
  • 1
    By the way, it is more typical to use the forward slash (`/`) as a parameter prefix, rather than the backslash (`\\`). Just saying. You don't have to be like others, of course. – Andriy M Jun 03 '11 at 11:58

1 Answers1

9

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.

Andriy M
  • 76,112
  • 17
  • 94
  • 154
  • What does the ampersand do? I can't seem to find documentation for it. – Kyle Delaney May 03 '18 at 18:35
  • 1
    @KyleDelaney: It's a command delimiter. Normally you put distinct commands on separate lines in a batch script. When you put them on the same line, you separate them with an ampersand. – Andriy M May 03 '18 at 22:45
  • 1
    Finally found documentation: https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-xp/bb490954(v=technet.10) – Kyle Delaney May 04 '18 at 17:37