1

I want to create a Windows batch file that accepts parameters and uses it inside. For instance, when I type "sample.bat -username admin -password pass123" in the command line, it will store "admin" and "pass123" in the variables inside sample.bat

This is how I do it in Linux:

USERNAME=
PASSWORD=

while [ $# -ne 0 ]
do
case $1 in
    -username*)
        USERNAME=$2
        ;;
    -password*)
        PASSWORD=$2
        ;;
    *)
        ;;
esac
shift 1
done

I'm not used to making scripts in Windows but I need to do a Windows counterpart for this one. Kindly help me. Thank you so much!

joanna
  • 117
  • 1
  • 4
  • 12
  • possible duplicate of [How to Pass Command Line Parameters in Batch File](http://stackoverflow.com/questions/26551/how-to-pass-command-line-parameters-in-batch-file) – Winderps Feb 05 '14 at 16:48
  • 1
    Take a look at [Windows Bat file optional argument parsing](http://stackoverflow.com/a/8162578/1012053) for ready made code to parse named parameters with batch. – dbenham Feb 06 '14 at 03:43

1 Answers1

3
@echo off
set user=
set pass=

:loop 
if "%1" == "" goto done
if /i "%1" == "-username" set "user=%2"
if /i "%1" == "-password" set "pass=%2"
shift
goto :loop

:done
echo Username:  %user%
echo Passoword: %pass%

Note: don't use %username% as a variablename, because it's a systemvariable.

Stephan
  • 53,940
  • 10
  • 58
  • 91
  • As they are, the two shifts can generate an error. If arguments are `data -username myname`, user name will not be retrieved. – MC ND Feb 05 '14 at 19:32
  • yes, that's what came to my mind tonight ^^ - I'll change that. – Stephan Feb 06 '14 at 08:12