2

This might be a simple question, but I didn't found any thread, may be I am searching wrong.

I am having a simple bat script and passing some arguments. Currently I am getting the argument based on there order. But I want to make simple for the user.

My current command line looks like: testBatch.bat setupip setupuser setuppass My current batch script looks like:

set setupip=%1
set setupuser=%2
set setuppass=%3
echo I am doing some operation after this based on the input I got.

Now I want to modify the command such that the user should not be woried about the order of argument to pass. Basically I want to see my command like this: testBatch.bat --ip setupip --user setupuser --password setuppass

What modification I have to do in my batch script?

Shashi Ranjan
  • 1,491
  • 6
  • 27
  • 52
  • 1
    Possible duplicate of [Is there a way to pass parameters "by name" (and not by order) to a batch .bat file?](http://stackoverflow.com/questions/5215729/is-there-a-way-to-pass-parameters-by-name-and-not-by-order-to-a-batch-bat-f) – Petter Friberg Mar 17 '16 at 12:01

3 Answers3

4

Thing you are looking for is called 'Named Arguments'. I found link for same question here.

Answer Which I like from that link is as follow:

set c=defaultC
set s=defaultS
set u=defaultU

:initial
if "%1"=="" goto done
echo              %1
set aux=%1
if "%aux:~0,1%"=="-" (
   set nome=%aux:~1,250%
) else (
   set "%nome%=%1"
   set nome=
)
shift
goto initial
:done

echo %c%
echo %s%
echo %u%

Run the following command:

arguments.bat -c users -u products

Will generate the following output:

users
defaultS
products
Community
  • 1
  • 1
Prashant
  • 138
  • 8
4

try this:

@echo off


for %%a in (%*) do (
    call set "%%~1=%%~2"
    shift
)

echo :%--user%
echo :%--pass%

if the passed it is called like:

namedArgs.bat --user user --pass pass

the output will be like:

:user

:pass

This will handle also quoted parameters with spaces in them.

Community
  • 1
  • 1
npocmaka
  • 55,367
  • 18
  • 148
  • 187
1

There is a batch command called shift, which can basically do a shift left on your parameter variables.

So as the start of your script, you need a loop

inside that loop you decode %1 for the 'verb' part of your option with a if statement

inside that if block, you call shift. then old %2 becomes the new%1, old %3 becomes the new %2, etc

so inside that if, you can pick up a secondary argument for the verb, if needed. Then call shift again.

loop until your arguments are empty. Tadah!

infixed
  • 1,155
  • 7
  • 15