Home > Articles > Home & Office Computing > Microsoft Windows Desktop

  • Print
  • + Share This
This chapter is from the book

Argument Substitution

Many times you'll find that the repetitive tasks you encounter use the same programs but operate on different files each time. In this case, you can use command-line arguments to give information to the batch file when you run it. When you start a batch file from the command line with a command such as

batchname xxx yyy zzz 

any items after the name of the batch file are made available to the batch program as arguments. The symbols %1, %2, %3, and so on are replaced with the corresponding arguments. In this example, anywhere that %1 appears in the batch file, CMD replaces it with xxx. Then, %2 is replaced with yyy, and so on.

Argument substitution lets you write batch files like this:

@echo off 
notepad %1.vbs
cscript %1.vbs

This batch file lets you edit and then run a Windows Script Host program. If you name the batch file ws.bat, you can edit and test a script program named, say, test.vbs just by typing this:

ws test 

In this case, CMD treats the batch file as if it continued the following:

@echo off 
notepad test.vbs
cscript test.vbs

This kind of batch file can save you many keystrokes during the process of developing and debugging a script.

Besides the standard command-line arguments %1, %2, and so on, you should know about two special argument replacements: %0 and %*. %0 is replaced with the name of the batch file, as it was typed on the command line. %* is replaced with all the command-line arguments as they were typed, with quotes and everything left intact.

If I have a batch file named test.bat with the contents

@echo off 
echo The command name is %0
echo The arguments are: %*

then the command test a b c will print the following:

The command name is test 
The arguments are: a b c

%0 is handy when a batch file has detected some problem with the command-line arguments the user has typed and you want it to display a "usage" message. Here's an example:

if "%1" == "" ( 
    rem - no arguments were specified. Print the usage information
    echo Usage: %0 [-v] [-a] filename ...
    exit /b

If the batch file is named test.bat, then typing test would print out the following message:

Usage: test [-v] [-a] filename ... 

The advantage of using %0 is that it will always be correct, even if you rename the batch file at a later date and forget to change the "usage" remarks inside.

  • + Share This
  • 🔖 Save To Your Account