I need to pass an ID and a password to a batch file at the time of running rather than hardcoding them into the file.
Here\'s what the command line looks like:
To refer to a set variable in command line you would need to use %a%
so for example:
set a=100
echo %a%
rem output = 100
Note: This works for Windows 7 pro.
Simple solution(even though question is old)
Test1.bat
echo off
echo "Batch started"
set arg1=%1
echo "arg1 is %arg1%"
echo on
pause
CallTest1.bat
call "C:\Temp\Test1.bat" pass123
output
YourLocalPath>call "C:\Temp\test.bat" pass123
YourLocalPath>echo off
"Batch started"
"arg1 is pass123"
YourLocalPath>pause
Press any key to continue . . .
Where YourLocalPath is current directory path.
To keep things simple store the command param in variable and use variable for comparison.
Its not just simple to write but its simple to maintain as well so if later some other person or you read your script after long period of time, it will be easy to understand and maintain.
To write code inline : see other answers.
@ECHO OFF
:Loop
IF "%1"=="" GOTO Continue
SHIFT
GOTO Loop
:Continue
Note: IF "%1"==""
will cause problems if %1
is enclosed in quotes itself.
In that case, use IF [%1]==[]
or, in NT 4 (SP6) and later only, IF "%~1"==""
instead.
In batch file
set argument1=%1
set argument2=%2
echo %argument1%
echo %argument2%
%1
and %2
return the first and second argument values respectively.
And in command line, pass the argument
Directory> batchFileName admin P@55w0rd
Output will be
admin
P@55w0rd
Another useful tip is to use %*
to mean "all". For example:
echo off
set arg1=%1
set arg2=%2
shift
shift
fake-command /u %arg1% /p %arg2% %*
When you run:
test-command admin password foo bar
the above batch file will run:
fake-command /u admin /p password admin password foo bar
I may have the syntax slightly wrong, but this is the general idea.
Here's how I did it:
@fake-command /u %1 /p %2
Here's what the command looks like:
test.cmd admin P@55w0rd > test-log.txt
The %1
applies to the first parameter the %2
(and here's the tricky part) applies to the second. You can have up to 9 parameters passed in this way.