Usually, you can set variables using the set command in batch file.

set v1=value
echo %v1%
rem output printed value

Here, the variable value is assigned using set and printed using echo along with %v1%.

However, with this approach, you’re binding variables in a file and might not be able to accommodate passing dynamic arguments.

Windows provides command-line to dynamically pass parameters in batch and CMD files.

This tutorial explains how to pass command-line arguments to a batch file.

How to Pass Command Line Arguments to a Batch File

You can pass arguments from the command line to a batch file and read them using %index command, where the index always starts from 1. This means %1 is the first argument, %2 is the second argument, and so on.

Syntax

batchfile arg1 arg2 arg3 .. etc
  • batchfile is a batch file with either a .bat or .cmd extension.

  • arg1, arg2, arg3, etc., are arguments passed to the command line, separated by spaces.

In a batch file, you can access the command line arguments using %index:

%1, %2, %3 contain the first, second, and third arguments, respectively.

file.bat:

@echo off
echo %1 %2 %3

When running the file as seen below:

file.bat 1 2 3
1 2 3

The only drawback is that if you have more than 9 arguments, it will not work and will give the wrong output.

To handle more than 9 arguments, you can use %* to read all arguments. %10, %11, or more do not work because, for example, %10 is assumed as %1 and 0, which returns the first argument and appends zero, not the 10th argument.

@echo off
echo %*

Conclusion

Command-line arguments in batch files allow us to pass dynamic input to files. This is very useful when you need to pass configurations from the command line.

You can use %1, %2 up to %9 to access command-line arguments, and %* is used to read all arguments with more than 9 arguments.