C.2 Batch FilesThe Other Way to Do It

C.2 Batch Files The Other Way to Do It

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) are a natural extension of the environment.

Consider the following four DOS commands:

c: CD \windows\temp 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 C.3.2, later in this appendix), 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 appendix, 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.

C.2.1 Variables and the Environment

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 C.3.2, later in this appendix.

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, two at the beginning, or one on each end. See the following topics for details.

C.2.2 Flow Control

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.

C.2.3 Command-Line Parameters

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 C.3, later in this appendix, 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\temp\output.txt notepad c:\windows\temp\output.txt

Save this batch file as compare.bat, and execute it like this:

compare c:\windows\tips.txt c:\windows\faq.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.[A]

[A] 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.

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 C.2.4, next, for the use of the if statement), at which point the batch file ends (using the exit command).

C.2.4 Conditional Statements

There are three versions of the IF statement, which allow you to compare values and check the existence of files, respectively. 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 the existence of a file:

IF EXIST c:\windows\tips.txt GOTO SkipIt

If the file c:\windows\tips.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 test 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 was no error, execution will simply continue to the next command.

Here's a revised version of the file-compare example first shown in Section C.2.3 earlier in this appendix:

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\temp\output.txt IF ERRORLEVEL 0 GOTO Problem IF NOT EXIST c:\windows\temp\output.txt GOTO Problem notepad c:\windows\temp\output.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.

C.2.5 Loops

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

C.2.6 Simulating Subroutines

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 use this if performance is an issue.

This is useful in cases like the for...in...do statement (described in the proceeding 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 as it runs 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.



Windows XP Annoyances
Fixing Windows XP Annoyances
ISBN: 0596100531
EAN: 2147483647
Year: 2005
Pages: 78
Authors: David A. Karp

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net