-
When building command-line batch scripts, you often want to pass input arguments to the script — just like passing parameters to a function.
That’s where positional parameters (
%1through%9) come in.In batch scripting,
%1,%2, ...,%9refer to the arguments passed to your script from the command line or when calling one batch file from another.Each
%nholds the nth argument::: call like: myscript.bat arg1 arg2 arg3 :: inside myscript.bat ECHO First argument is %1 ECHO Second argument is %2
@ECHO OFF ECHO Hello, %1!
greet.bat Alice
✅ Output:
Hello, Alice!
-
:: multiply.bat @ECHO OFF SET /A result=%1 * %2 ECHO %1 x %2 = %result%
multiply.bat 6 9
✅ Output:
6 x 9 = 54 -
:: renamefile.bat @ECHO OFF IF EXIST "%1" ( REN "%1" "%2" ECHO Renamed %1 to %2 ) ELSE ( ECHO File %1 not found! )
renamefile.bat oldname.txt newname.txt
-
:: backup.bat @ECHO OFF SET filename=%1 COPY "%filename%" "%filename%_%DATE:/=-%.bak"
backup.bat config.json
✅ Creates something like:
config.json_2025-07-22.bak
| Issue | Explanation / Fix |
|---|---|
Only %1 to %9 available |
No %10, %11 etc — %10 is interpreted as %1 + 0 |
Use SHIFT for more params |
SHIFT lets you access beyond 9 (see below) |
| Quoting required for spaces | Always quote: "My File.txt" |
-
When you need to handle more than 9 arguments, use the
SHIFTcommand to rotate the arguments left by 1.@ECHO OFF :loop IF "%1"=="" GOTO end ECHO Arg: %1 SHIFT GOTO loop :end
loopargs.bat one two three four five six seven eight nine ten eleven
✅ Output:
Arg: one Arg: two ... Arg: eleven
@ECHO OFF
IF "%1"=="" (
ECHO Usage: %0 filename
EXIT /B 1
)This pattern:
- Checks if
%1is missing - Shows usage and exits cleanly
:: wrapper.bat
@ECHO OFF
ECHO Calling inner script with: %*
CALL inner.bat %*%* means: “all arguments as one string”.
| Tip | Why |
|---|---|
Quote %1, %2 if file paths are involved |
Handles spaces in paths |
| Validate args before use | Prevent errors or unexpected behavior |
Use SHIFT in loops with many args |
Enables argument handling beyond %9 |
Use %~n1, %~x1, etc. for parsing |
Extract parts of filenames (see below) |
| Expression | Meaning |
|---|---|
%~f1 |
Fully qualified path of %1 |
%~n1 |
File name only |
%~x1 |
File extension only |
%~dp1 |
Drive + path of %1 |
:: Show parts of a file path
@ECHO OFF
ECHO File: %1
ECHO Name: %~n1
ECHO Extension: %~x1
ECHO Path: %~dp1| Feature | Description |
|---|---|
%1–%9 |
Positional arguments to scripts |
%* |
All arguments as one |
SHIFT |
Shift all arguments left (access beyond %9) |
| Modifiers | Extract filename, extension, path, etc. |