Batch Files

Most Windows books treat batch files as though they are some kind of skeleton in the closet or a crazy aunt you wouldn’t want anyone to meet. Although it’s true that batch files are much less important than they were in DOS and earlier versions of Windows, they can still provide useful functionality.

A batch file is a text file containing a series of commands, each on its own line, that will be executed one line at a time. The filename of the batch file becomes a command that can be executed at the Command Prompt, executed from another batch file, or even run from a Windows shortcut.

Although any commands you can type at the command line can be used in a batch file, several additional commands can be used only in a batch file. These commands are used for loops, conditionals, and other programming functions within the batch file and are explained in detail later in this chapter.

Creating Batch Files

You can create batch files with any text editor or word processor that can save plain-text files, such as Notepad. In fact, by default, you can right-click any batch file and select Edit to open that file in Notepad.

When naming a batch file, make sure you don’t use a name that is already used by a Command Prompt internal command (such as dir, copy, or cd) or by a .com or .exe file in your search path. The reason for this is that when the Command Prompt executes programs, it first looks for the .com extension and then the .exe extension before finally executing a file with the .bat extension. For instance, if you have a file called work.exe and you create work.bat in the same directory, your batch file will not execute unless you type the filename extension as well.

Tip

You can create and execute batch files from the current directory or any directory in your search path, or by specifying their complete pathname, as with any other command. But if you’re going to use batch files a lot, it makes sense to keep them all in one place. Create a directory called Batch and add it to your search path. See "path,” earlier in this chapter, for details.

Some Rules of the Road

Here are the basics of batch file programming:

  • Each command in a batch file must be on a separate line. The last command line in the file should end with a carriage return. The commands are the same as those you’d type in succession at the Command Prompt.

  • The name of the batch file itself is stored in the variable %0. This allows you to do things such as have a temporary batch file that deletes itself when done. The name is stored as it was typed at the command line, so if you had typed myfile.bat, %0 would be myfile.bat, but if you had typed c:atchmyfile, %0 would be c:atchmyfile.

  • A batch file run from the Command Prompt or by double-clicking on its icon will open a Command Prompt window while it is executing; however, a batch file run from an existing Command Prompt window will run inside that window.

  • Click the control menu and select Properties (see "Using the Command Line,” earlier in this chapter, for details) to control the default look and feel of the Command Prompt window. To change these settings for an individual batch file, create a Windows shortcut to the batch file, right-click the new shortcut, and select Properties.

  • The Properties sheet for the shortcut actually adds several options not normally available through the control menu. For example, Shortcut → Start In allows you to choose the initial working directory, and Shortcut → Run allows you to have the batch file run minimized.

  • You can stop a running batch file by pressing Ctrl-Break or Ctrl-C; the following message will appear in its DOS window: “Terminate batch job (Y/N)?”.

  • By default, each command in a batch file is echoed to the Command Prompt window. To execute a command silently, precede it with an @ symbol. Alternatively, you can turn command echo off by issuing @echo off at the beginning of the batch file.

  • A batch file can contain any command that you can type at the Command Prompt. However, keep in mind that each line in the batch file is executed sequentially, so there are a couple of gotchas, especially when the batch file runs programs that pop up a separate window. When you run a Windows program and it pops up its own window, control returns immediately to the batch file and the next line is executed. This “race condition” is unfortunately unavoidable with batch files; you’ll have to use a WSH script for this type of control.

  • You can store temporary data in your batch file using environment variables created with the set command. To use the value of any variable with any other command or program, surround its name with % symbols.

The “Why” and “When” of Using Batch Files

This section gives a few examples of instances when you might want to use batch files.

Batch files are used to automate repetitive tasks, but they can be useful for more than just issuing a sequence of commands. For example, type the names of three applications in a batch file to have them all opened in a single step. Or write a one-line batch file that copies a directory of files onto a removable drive; instead of performing a copy manually every day before you go home from work, just double-click the batch file icon and it will be done for you.

Batch files are particularly powerful for creating and moving files and directories. For example, when starting a new project, an author might always want to create the same directory structure and put some basic files into each directory. Here’s the kind of batch file you might create for this kind of housekeeping:

@echo off
if "%1"=="" goto skip
mkdir %1figures
mkdir %1sources
mkdir %1old
copy c:	emplatesmainfile.doc %1
copy c:	emplatesother.doc %1
copy c:	emplatesimage.tif %1figures
:skip

Create a new folder in the Explorer, and then drag and drop it onto this batch file (or add the batch file to the SendTo menu). Subdirectories called figures, sources, and old will be created inside the target (when you drag and drop something onto a batch file, its name is put into the %1 variable), and three template files are copied into the new directories. Voilà—you just saved about a minute of clicking and dragging.

The construct:

if "%1"=="" go to skip

is a useful error-checking technique. You can use an if statement to test for null arguments (or other similar conditions), and if encountered, either issue an error message or simply quit. (This example will exit after jumping to the :skip label because there are no further commands to be executed.)

You can also use batch files to work around some of the limits of Windows Vista. For example, the Explorer doesn’t let you print out a hardcopy listing of the contents of a folder. You can do this from the command line by typing:

dir > lpt1:

But the following batch file does even better—you can drag and drop a folder icon onto it to get a printed directory listing:

@echo off
if "%1"=="" goto skip
dir %1 > lpt1:
:skip

If you don’t have a parallel printer, you could also replace lpt1: with something such as c:windowsdesktopdir-list.txt to output the directory listing to a text file instead (and then print it with notepad /p filename), or construct a loop so that the batch file could repeat itself automatically for multiple directory name arguments.

Variables

Variables can be used in batch files. In fact, a variable that is assigned in one batch file can be accessed by a different batch file (in the same Command Prompt session), because the Command Prompt environment is used to store all variables. See "set,” earlier in this chapter, for more information on setting, modifying, reading, and deleting variables from the environment.

A batch file can take arguments such as filenames or options. Up to nine arguments are stored in the variables %1 through %9. For example, the following line in a batch file:

copy %1 %2

means that the batch file would copy the filename specified in the first argument to the name specified in the second argument. Use this feature in conjunction with the if statement—for example, to display a help screen when the “user” includes the /? option. The %* variable returns a string with all arguments (e.g., %1 %2 %3 %4 %5 . . .), which can be a convenient way to pass all a batch file’s arguments to another batch file or command.

The following variable operators can also be used with variables containing filenames. They don’t actually change the contents of the target variable, but they do return an expanded version of it.

%~ var

Expands % var, removing any surrounding quotes.

%~f var

Expands % var to a fully qualified pathname (useful if % var references a file in the current directory).

%~d var

Expands % var to a drive letter only.

%~p var

Expands % var to a path only.

%~n var

Expands % var to a filename only.

%~x var

Expands % var to a file extension only.

%~s var

The expanded path contains short names only.

%~a var

Expands % var to file attributes.

%~t var

Expands % var to the date/time of the file.

%~z var

Expands % var to the size of the file.

%~$ dir : var

Searches the directories listed in the dir variable and expands % var to the fully qualified name of the first one found. If dir is not defined, or if the file is not found by the search, an empty string is returned. If you specify $PATH for dir, the command search path will be used (see "path,” earlier in this chapter).

These operators are most commonly used with command-line arguments; for example, use %~z 2 in a batch file to display the size of the file specified by %2. These operators can be combined; for example, %~nx1 expands %1 to the filename and extension only, and %~ftza7 expands %7 to a dir-like output line. If the variable % var is not defined or does not contain the filename of an existing file, an empty string will be returned.

Additional Commands Used in Batch Files

The following list contains descriptions of the commands that are used principally within batch files. You can use these in conjunction with any of the commands listed earlier in this chapter, as well as the filenames of any Command Prompt programs or even Windows applications.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.79.176