2

I am completeley new with windows batch scripting. I want to write a batch script that gets commandline parameters as below;

myscript -parameter1 param1 -parameter2 param2

It should set parameter1 to param1 and parameter2 to param2 inside the script. Does anybody have a code block which does the above?

Thanks

kyy
  • 321
  • 3
  • 11
  • 2
    possible duplicate of [Windows Bat file optional argument parsing](http://stackoverflow.com/questions/3973824/windows-bat-file-optional-argument-parsing) Take a look at [my recent answer](http://stackoverflow.com/a/8162578/1012053) to this old question - It has some ideas and techniques you may find useful. – dbenham Aug 16 '12 at 11:26

1 Answers1

4

You can go through the arguments with a loop and try something like this:

:argloop
  set "arg=%~1"
  if "%arg:~0,1%"=="-" (
    set "%arg:~1%=%~2"
    shift
  )
  shift
if not "%1"=="" goto argloop

echo parameter 1: %parameter1%
echo parameter 2: %parameter2%

This will look at the arguments one by one and if an argument starts with a - it will set an environment variable of the same name with the next argument as its value:

H:\>args.cmd -parameter1 param1 -parameter2 param2
parameter 1: param1
parameter 2: param2

If you need the original arguments later, then you should move above loop to a subroutine and call it with %* as arguments.

Joey
  • 344,408
  • 85
  • 689
  • 683
  • @korhan If it worked for you, then maybe you could think about accepting the answer? Accepting answers will make people more willing to answer you in the future. – Some programmer dude Aug 16 '12 at 11:07