Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 827
Chad Avatar asked Jun 03 '11 11:06

Chad


People also ask

What is %% A in batch?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.

How many parameters can I pass to batch file?

There is no practical limit to the number of parameters you can pass to a batch file, but you can only address parameter 0 (%0 - The batch file name) through parameter 9 (%9).

What is %% K in batch file?

So %%k refers to the value of the 3rd token, which is what is returned.

How do I pass a variable in command prompt?

To pass variable values via the command line, use the PrjVar ( pv ) or PSVar ( psv ) arguments for the project and project suite variables respectively. Variable values you pass via the command line are temporary.


1 Answers

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.

like image 67
Andriy M Avatar answered Nov 09 '22 08:11

Andriy M