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!

2

1 Answer 1

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.

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

2 Comments

As they are, the two shifts can generate an error. If arguments are data -username myname, user name will not be retrieved.
yes, that's what came to my mind tonight ^^ - I'll change that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.