How can I pass arguments to a batch file?

 

You can pass arguments to a batch file in Windows by including them after the batch file's name when you execute it. These arguments can be accessed within the batch script using special variables like %1, %2, and so on. Here's how you can do it with an example:

Example Batch Script (myscript.bat):

batch
@echo off echo My Batch Script REM Accessing the first argument echo First argument: %1 REM Accessing the second argument echo Second argument: %2 REM Accessing all arguments echo All arguments: %* REM Count of arguments echo Number of arguments: %# REM Loop through all arguments echo Loop through all arguments: for %%a in (%*) do ( echo %%a ) pause

In this script:

  • %1 refers to the first argument.
  • %2 refers to the second argument.
  • %* refers to all arguments.
  • # is used to count the number of arguments.
  • The for loop is used to iterate through all the arguments.

Executing the Batch Script with Arguments:

Suppose you have the batch script saved as "myscript.bat," and you want to pass arguments to it. You can do so when running the script from the command prompt:

batch
myscript.bat arg1 arg2 arg3

In this example, we're passing three arguments, "arg1," "arg2," and "arg3," to the batch script.

Output:

When you run the script with these arguments, you'll see the following output:

sql
My Batch Script First argument: arg1 Second argument: arg2 All arguments: arg1 arg2 arg3 Number of arguments: 3 Loop through all arguments: arg1 arg2 arg3 Press any key to continue . . .

The batch script processes the arguments as shown in the script example, allowing you to pass data to the script from the command line. You can access and use these arguments within your batch script as needed for your specific task.

Comments