When it comes to quick-and-dirty scripting, it’s hard to beat DOS batch files. Batch files, similar to WSH scripts (discussed in Chapter 9), are plain-text files with the .bat filename extension. However, rather than relying on a complex, unfamiliar scripting language, batch files simply consist of one or more DOS commands, typed one after another.
One of the problems with Windows-based scripting (see Chapter 9) is that it tries to control a graphical environment with a command-based language. Because DOS is a command-based interface, DOS-based scripting (batch files) is a natural extension of the environment.
Consider the following four DOS commands:
c: cd windows emp attrib -r *.tmp del *.tmp
If you type these commands into a plain-text editor, such as Notepad, save it into a .bat file, and then execute the batch file by double-clicking or typing its name at the Command Prompt, it will have the same effect as if the commands were manually typed consecutively at the prompt. Obviously, this can be a tremendous time saver if you find yourself entering the same DOS commands repeatedly.
When you run a batch file, each command in the file will be
displayed (echoed) on the screen before it’s executed, which can be
unsightly for the more compulsive among us. To turn off the echoing of
any given command, precede it with the @
character. To turn off the printing of all commands in a
batch file, place the command @echo
off
at the beginning of the batch file.
Batch files can be executed by double-clicking them in Explorer or by typing their names at a DOS prompt. You’ll want to put more frequently used, general-purpose batch files in a folder specified in the system path (see Section 10.3.3, later in this chapter), so that they can be executed from the command prompt, regardless of the current working directory.
Although batch files can run Windows programs (just type notepad
to launch Notepad), it’s preferable to run Windows programs with
Windows Script Host scripts, because they’ll be able to run without
having to first load a Command Prompt window.
In addition to the standard DOS commands, most of which are
documented earlier in this chapter, batch files use a couple of extra
statements to fill the holes. Variables, conditional statements, and
For...Next
loops are all implemented
with statements that are ordinarily not much use outside of batch
files.
The following topics cover the concepts used to turn a task or a string of DOS commands into a capable batch file.
The use of variables in batch files can be somewhat confusing. All variables used in a batch file (with the exception of command-line parameters) are stored in the environment —an area of memory that is created when you first boot and is kept around until the computer is turned off. The environment variable space is discussed in more detail in Section 10.3.3, later in this chapter.
To view the contents of the environment, type set
without any arguments. To set a variable to a
particular value, type this command:
set VariableName=Some Data
Unlike VBScript (see Chapter
9), the set
command is
required and no quotation marks are used when setting the value of a
variable. To remove the variable from memory, you set its value to
nothing, like this:
set VariableName=
To then display the contents of the variable, use the echo
command, as
follows:
echo %VariableName%
Here, the percent signs (%
) on both ends of the variable name are mandatory;
otherwise, the echo
command would
take its arguments literally and display the name of the variable
rather than the data it contains.
What’s confusing is that in some cases, variables need no percent signs; sometimes they need one, sometimes two at the beginning, or sometimes one on each end. See the following topics for details.
Batch files have a very rudimentary, but easy-to-understand
flow-control structure. The following example exhibits the use of the
goto
command:
@echo off echo Griff echo Asa goto LaterOn echo Ox :LaterOn echo Etch
The :LaterOn
line (note the
mandatory colon prefix) is called a label, which is used as a target
for the goto
command. If you follow
the flow of the script, you should expect the following output:
Griff Asa Etch
because the goto
command has
caused the Ox
line to be skipped.
The label can appear before or after the goto
line in a batch file, and you can have
multiple goto
commands and multiple
labels.
Suppose you executed a batch file called Demo.bat by typing the following at the DOS prompt:
Demo file1.txt file2.txt
Both file1.txt
and file2.txt
are command-line parameters and
are automatically stored in two variables,
%1
and %2
,
respectively, when the batch file is run.
The implication is that you could run a batch file that would then act with the parameters that have been passed to it. A common use of this feature is, as shown in the previous example, to specify one or more filenames, which are then manipulated or used in some way by the batch file. Section 10.3.1, later in this chapter, shows a batch file that utilizes command-line parameters.
The following two-line example uses command-line parameters and
the FC
utility to compare two text
files. A similar example using the Windows Script Host, shown in Section 9.1.5, takes 22
lines to accomplish approximately the same task:
fc %1 %2 >c:windows empoutput.txt notepad c:windows empoutput.txt
Save this batch file as compare.bat, and execute it like this:
compare c:windows ips.txt c:windowsfaq.txt
which will compare the two files, tips.txt and faq.txt (both located in your Windows
folder), save the output to a temporary file, and then display the
output by opening the file in Notepad. Note that the >
character on the first line redirects
the output of the FC program to the output.txt file, which would otherwise be
displayed on the screen. The second line then opens the output.txt file in Notepad for easy
viewing.
There are ways, other than typing, to take advantage of command-line parameters. If you place a shortcut to a batch file (say, Demo.bat) in your SendTo folder, then right-click on a file in Explorer, select Send To and then Demo, the Demo.bat batch file will be executed with the file you’ve selected as the first command-line parameter. Likewise, if you drag-drop any file onto the batch-file icon in Explorer, the dropped file will be used as the command-line parameter.[1]
Batch files have a limit of 9 command-line parameters (%1
through %9
), although there’s a way to have more if
you need them. Say you need to accept 12 parameters at the command
line; your batch file should start by acting on the first parameter.
Then, you would issue the shift
command, which eliminates the first parameter, putting the second in
its place. %2
becomes %1
, %3
becomes %2
, and so on. Just repeat
the process until there are no parameters left. Here’s an example of
this process:
:StartOfLoop if "%1"=="" exit del %1 shift goto StartOfLoop
Save these commands into MultiDel.bat. Now, this simple batch file deletes one or more filenames with a single command; it’s used like this:
MultiDel file1.txt another.doc third.log
by cycling through the command-line parameters one by one using
shift
. It repeats the same two
lines (del
%1
and
shift
) until the %1
variable is empty (see Section 10.2.4, next, for
the use of the if
statement), at
which point the batch file ends (using the exit
command).
There are three versions of the if
statement, which
allow you to compare values and check the existence of files. The
first version, which is usually used to test the value of a variable,
is used as follows:
if "%1"=="help" goto SkipIt
Note the use of quotation marks around the variable name and the
help
text, as well as the double
equals signs, all of which are necessary. Notice also there’s no
then
keyword, which those of you
who are familiar with VBScript (see Chapter 9) might expect. If the
batch file finds that the two sides are equal, it executes everything
on the right side of the statement; in this case, it issues the
goto
command.
The second use of the if
command is to test for the existence of a file:
if exist c:windows ips.txt goto SkipIt
If the file c:windows ips.txt exists, the goto
command will be executed. Similarly,
you can you can test for the absence of a file, as follows:
if not exist c:autoexec.bat goto SkipIt
The third use of the if
command is to check the outcome of the previous command, as
follows:
if errorlevel 0 goto SkipIt
If there was any problem with the statement immediately before
this line, the errorlevel
(which is similar to a system-defined variable) will be
set to some nonzero number. The if
statement shown here tests for any errorlevel
that is greater than zero; if there is no error,
execution will simply continue to the next command.
Here’s a revised version of the file-compare example first shown in the Section 10.2.3 section earlier in this chapter:
if "%1"=="" goto problem if "%2"=="" goto problem if not exist %1 goto problem if not exist %2 goto problem fc %1 %2 >c:windows empoutput.txt if errorlevel 0 goto problem if not exist c:windows empoutput.txt goto problem notepad c:windows empoutput.txt exit :problem echo "A problem has been encountered."
This batch file is essentially the same as the original two-line
example shown earlier, except that some error-checking statements that
utilize the if
statement have been
added to make the batch file a little more robust. If you neglect to
enter one or both command-line parameters, or if the files you specify
as command-line parameters don’t exist, the batch file will display
the error message. An even more useful version might have multiple
error messages that more accurately describe the specific problem that
was encountered.
Batch files have a very simple looping mechanism, based loosely on
the For...Next
loop used in other
programming languages. The main difference is that the batch file
for
loop doesn’t increment a
variable regularly, but rather cycles it through a list of values. Its
syntax is as follows:
for %%i in ("Abe","Monty","Jasper") do echo %%i
Here, the variable syntax gets even more confusing; the
reference to the i
variable when
used in conjunction with the for...in...do
statement gets two percent signs in front of the
variable name and none after. Note also that only single-letter
variables can be used here.
If you execute this batch file, you’ll get the following output:
Abe Monty Jasper
Note also the use of the quotation marks; although they aren’t strictly necessary, they’re helpful if one or more of the values in the list has a comma in it.
To simulate a more traditional For...Next
statement in a batch file, type
the following:
for %%i in (1,2,3,4,5) do echo %%i
Batch files have no support for named subroutines (as described in Section 9.1.5). However, you can simulate subroutines by creating several batch files: one main file and one or more subordinate files (each of which can accept command-line parameters). You probably won’t want to do this if performance is an issue.
This is useful in cases like the for...in...do
statement (described in the
preceeding section), which can only loop a single command.
In one batch file, called WriteIt.bat, type:
if "%1"=="" exit if exist %1.txt del %1.txt echo This is a text > %1.txt
Then, in another batch file, called Main.bat, type the following:
for %%i in ("Kang","Kodos","Serak") do call WriteIt.bat %%i
The single-line Main.bat
batch file uses the call
command to run the other batch file, WriteIt.bat, three times. The call
command allows one batch file to run
another batch file; if it’s omitted, one batch file can still run
another, but the first batch file will abruptly end upon running the
second batch file.
When this pair of batch files is run, you should end up with
three files, Kang.txt, Kodos.txt, and Serak.txt, all containing the text, “This
is a text.” The if
statement, as
well as the for...in...do
loop, are
explained in earlier sections.
[1] If you drop more than one file on a batch-file icon, their order as arguments will be seemingly random, theoretically mirroring their ordering in your hard disk’s file table.
3.148.107.255