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?

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

Don't post link only answer.
Added code snippet from link where I do refered the answer. @PetterFriberg
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!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.