Windows Batch Files for Fun and Profit
- Why Batch Files?
- Creating and Using Batch Files
- Batch File Programming
- Displaying Information in Batch Files
- Argument Substitution
- Argument Editing
- Conditional Processing with If
- Processing Multiple Arguments
- Working with Environment Variables
- Processing Multiple Items with the For Command
- Using Batch File Subroutines
- Prompting for Input
- Useful Batch File Techniques
Why Batch Files?
While Windows Script Host is a powerful scripting and programming environment, the old-fashioned batch file can still be a useful, powerful tool in the Windows XP environment. Why? Whereas Windows Script Host programs use objects as tools to perform Windows management and data-processing tasks, batch files use entire programs as their tools. WSH scripts give you great control of the details of a task, whereas batch files let you work at a grosser, macro level. So, just as it's an advantage to have both small and large wrenches in your toolbox, it's an advantage to know how to write both scripts and batch files. Furthermore, like Windows Script programs, batch files serve as a form of documentation, because they capture critical business management information—procedures and configuration data—in written form.
In my work as both a software developer and writer, I've found that the batch files I write fall into three categories:
- Tiny files to manipulate the command-line environment. For example, I have several little batch files that change the working directory to the correct folder for specific projects, and perhaps add a directory to the search path. This way, I can open a Command Prompt window, type one word, and be ready to work with a particular project's files.
- Medium-sized files that perform a specific series of commands that I find myself typing over and over. For example, I frequently have to send updated versions of a particular set of files to a client. I use a batch file to update a ZIP file and e-mail the results so the whole job is taken care of with one command.
- Monster batch files that perform a long sequence of tasks and handle a variety of command-line options. In my work, these tend to involve custom-developed command-line programs for data-processing applications or Microsoft-provided utilities used to manage Windows—both the standard tools and those provided with the Windows Resource Kits. For example, I have a batch file that documents all the Internet domains managed by my Windows 2000 Server's DNS service. This batch file could reconstruct the entire set of domains if it is necessary to move to a new server. This kind of job is a snap for a batch file but would be a nightmare to reenter through the GUI.
In Chapter 11, I discussed all the commands built in to the CMD shell. In this chapter, I'll discuss the commands that are particularly useful in batch files and will give you some examples of the three categories of batch files I find useful.