How can I pass arguments to a batch file?
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.
If you want to intelligently handle missing parameters you can do something like:
IF %1.==. GOTO No1
IF %2.==. GOTO No2
... do stuff...
GOTO End1
:No1
ECHO No param 1
GOTO End1
:No2
ECHO No param 2
GOTO End1
:End1
Accessing batch parameters can be simple with %1, %2, ... %9 or also %*,
but only if the content is simple.
There is no simple way for complex contents like "&"^&
, as it's not possible to access %1 without producing an error.
set var=%1
set "var=%1"
set var=%~1
set "var=%~1"
The lines expand to
set var="&"&
set "var="&"&"
set var="&"&
set "var="&"&"
And each line fails, as one of the &
is outside of the quotes.
It can be solved with reading from a temporary file a remarked version of the parameter.
@echo off
SETLOCAL DisableDelayedExpansion
SETLOCAL
for %%a in (1) do (
set "prompt="
echo on
for %%b in (1) do rem * #%1#
@echo off
) > param.txt
ENDLOCAL
for /F "delims=" %%L in (param.txt) do (
set "param1=%%L"
)
SETLOCAL EnableDelayedExpansion
set "param1=!param1:*#=!"
set "param1=!param1:~0,-2!"
echo %%1 is '!param1!'
The trick is to enable echo on
and expand the %1 after a rem
statement (works also with %2 .. %*
).
So even "&"&
could be echoed without producing an error, as it is remarked.
But to be able to redirect the output of the echo on
, you need the two for-loops.
The extra characters * #
are used to be safe against contents like /?
(would show the help for REM
).
Or a caret ^ at the line end could work as a multiline character, even in after a rem
.
Then reading the rem parameter output from the file, but carefully.
The FOR /F should work with delayed expansion off, else contents with "!" would be destroyed.
After removing the extra characters in param1
, you got it.
And to use param1
in a safe way, enable the delayed expansion.
Yep, and just don't forget to use variables like %%1
when using if
and for
and the gang.
If you forget the double %
, then you will be substituting in (possibly null) command line arguments and you will receive some pretty confusing error messages.