batch_files_explained.

txt

26/02/2002

The Power of PC/MS-DOS Batch Files Part 1: Getting Started One of the keys to getting the most from your IBM-compatible computer is learning to make the most of the operating system. PC/MS-DOS, while not as simple to learn as the operating systems for some other computers, has the potential to let you customize your computing and increase your productivity. When Microsoft designed the original PC/MS-DOS, the personal computer was still something of an unknown quantity. Few people anticipated the millions of personal computers that would be sold. Fortunately for users, PC/MS-DOS included a powerful capability: batch processing. This series of articles will explore the depths of PC/MS-DOS batch processing, teaching you how to automate many of the functions of your PC. You'll also learn how to use batch files to make your PC do things you never thought possible. BATCH FILE BASICS There are three types of programs that PC/MS-DOS can run directly. You are already familiar with two of them. Files with the extensions .COM and .EXE run when you enter the filename at your system prompt. Batch files, with the extension, .BAT, are the third type. A batch file is nothing more than a series of DOS commands, separated by carriage returns. When you enter the name of the batch file, DOS carries out the commands, one at a time. Once a batch file is running, you can stop it by holding down the <Ctrl> key while you press the <Break> key. If you do this, a message will appear on the screen: Terminate batch job (Y/N)? If you press a Y, the batch file will abort. Pressing N continues the batch file's operation.

Page 2 You can use any DOS command in a batch file, from simple ones like COPY to commands seldom used, like ASSIGN. When you call a batch file by entering its file name, PC/MS-DOS opens the file, and carries out the first command. Once the operation of that command is completed, the system prompt (A>, C>, etc.) reappears, and the next command in the batch file executes automatically. There is no limit to the length of a batch file. The computer will continue to carry out the commands until it reaches the end of the file. CREATING BATCH FILES There are five basic requirements for the structure of any 1

batch_files_explained.txt batch file:

26/02/2002

1. It must be a pure ASCII file, meaning that no characters other than the commands you give, plus carriage returns, can be used in the file. 2. The filename can be any legal filename, but cannot have the same name as a .COM or .EXE file in the same directory, or the same name as any DOS internal command, such as COPY or DIR. 3. It must have the extension .BAT.

4. The file must have an end-of-file marker following the last command in the file. 5. Each command must be on a separate line in the batch file, separated from adjacent commands by a carriage return. Creating an actual batch file is simple. There are two basic methods I recommend. Each has its advantages and disadvantages. The first method uses the DOS COPY command. Use this method for creating short, simple batch files. First, give the command: COPY CON [DRIVE][PATH][FILENAME]. Here's a sample command: COPY CON C:\BATCH\STARTUP.BAT <Enter> This command will create the file, STARTUP.BAT, in the \BATCH directory in drive C:. When you press <Enter> the cursor will move to the next line on the screen and you can begin writing your batch file. Type in the first command in your series of commands. You can correct your spelling by backspacing and retyping, as long as the cursor is on the current line. When the line is correct, press <Enter> to move the cursor to the next line.

Page 3

Now type in additional commands, as needed for your batch file, following each line by pressing <Enter>. This adds a carriage return character to the end of the line, telling PC/MS-DOS to carry out the command on that line. Once you have typed in all the commands to be used in that particular batch file, press <Enter> once more at the end of the last line. Now press <F6> or hold down the <Ctrl> key while you press the <Z> key. Either operation will place an end-of-file character in your file. Press <Enter> again and the computer will write the file to the disk. Test this procedure by creating a batch file which displays a directory. Follow the steps below to create this file in the current drive and directory. At the system prompt, type: COPY CON D.BAT <Enter> DIR <Enter> <F6> or <Ctrl>+<Z> <Enter> 2

batch_files_explained.txt

26/02/2002

Your drive light will come on, and the file will be written to disk. Now, check your work and test the file. Press the <D> key, then press <Enter>. You should see a directory on your monitor. Notice that you have simplified the command which displays a directory. Now you only have to type a single letter, instead of three. While the COPY CON method works fine, it's not as convenient for longer batch files which might contain many commands. If you make a mistake with the COPY CON method, there is no way to fix it. You have to retype the entire batch file. For this reason, use this method only for short, simple files. When you need to create a longer batch file, use a text editor. Just about any text editor or word processing program will work. The only requirement is that the editor must be able to save pure ASCII files. If you use PC-WRITE, your batch files will automatically be saved in ASCII. WordStar users must open batch files in the Non-Document mode. Microsoft Word users can create batch files, then save them in ASCII format by choosing the "No" option in the "Transfer Save" menu. Check the user's manual for your word processor for its procedures. If you're not sure about the method your editor uses, try creating a batch file. Save it, then exit the program and use the TYPE command to display the file on your monitor. If you see your file, without any extra characters on the screen, you know that it is pure ASCII, and can be used as a batch file.

Page 4

Whichever method you use, remember to use the .BAT extension and don't give your file a name which would conflict with another executable file in its directory. If your batch file has a name which is the same as a .COM or .EXE file, or a DOS internal command, it simply won't execute. A SPECIAL BATCH FILE: AUTOEXEC.BAT When you boot up your computer, several things happen. First, the ROM BIOS in your PC checks the system's memory, then looks for a disk in drive A: or for a hard disk drive. It then loads the system files from the disk into memory. These files include COMMAND.COM plus two hidden files. One these files are loaded, it looks for a file called CONFIG.SYS and carries out any functions contained in that file. Finally, it looks for a batch file named AUTOEXEC.BAT. If the file exists, PC/MS-DOS carries out the commands in that file. If there is no AUTOEXEC.BAT file, you see the standard request for the current date and time on your screen. An AUTOEXEC.BAT file can contain any commands you want to use every time you boot your PC. Suppose, for example that you always wanted to start the program, Microsoft Word, when 3

batch_files_explained.txt

26/02/2002

you turned on your PC. Just create a batch file, named AUTOEXEC.BAT on your boot disk, or in the root directory of your hard disk, using one of the techniques above. This file has only one line: WORD Naturally, you could substitute the command you use to start any program you choose. When PC/MS-DOS finds an AUTOEXEC.BAT file, it bypasses the date and time sequence and immediately carries out the command in the file. Now, suppose you need to change directories on your hard disk before starting the program. Using Word as an example again, here's a sample file: CD WP WORD This time, the AUTOEXEC.BAT file tells the PC to change to the \WP directory, then start Microsoft Word. It's easy to see how you could adapt this to your own needs. Now, let's add something else. Many users install memoryresident programs before loading an application. SideKick is a popular memory resident program. Here's a sample file:

Page 5 CD UTILITY SK CD \WP WORD Line-by-line, here's what this AUTOEXEC.BAT file does: 1. 2. 3. 4. Changes to the \UTILITY directory on your hard disk. Loads SideKick. Changes to the \WP directory. Loads Microsoft Word.

Once again, you can substitute any directory name or command for the ones used in this sample file. Try creating your own AUTOEXEC.BAT file, using commands you select. OTHER SIMPLE BATCH FILES Batch files can be extremely useful in saving keystrokes. I often create them just to avoid typing long filenames or commands. Let's look at some ways to help yourself out with batch files. When you looked at the section on AUTOEXEC.BAT files, you learned how to start a program automatically when you booted your system. You can use other batch files to start programs with just a keystroke or two. Let's keep using Microsoft Word as an example. As before, I'll assume that we're working with a hard disk. Floppy disk users can just leave out the directory change commands in their batch files. Here's a simple batch file, named W.BAT that starts the program with a single keystroke. 4

batch_files_explained.txt CD WP WORD

26/02/2002

Now, when you use this file by typing a <W> and pressing <Enter>, Microsoft Word will run. When you exit from the program, however, you'll still be in the \WP directory on your hard disk. Add a third line to return you to the root directory when you exit Word. W.BAT will look like this: CD WP WORD CD\ When you leave Word, PC/MS-DOS knows that the batch file still has another command, so it returns to it and carries out the next command in the file. Suppose that you normally move to another program after exiting Word. You can have your batch file do this

Page 6 automatically. Let's try starting Lotus 123 after exiting Word. Here's a batch file to do just that: CD WP WORD CD \LOTUS 123 CD\ You can easily see how many keystrokes are saved by using a batch file instead of typing in all the commands. And that's just the beginning. Batch files are actually simple computer programs. By writing these files, you are learning simple computer programming. In this first part of the series, you've learned how to create simple batch files which save keystrokes. But batch files can do much more. Using the full power of PC/MS-DOS batch files, you can actually create real programs. In future parts of this series, you will learn how to create menus to help you or others run a PC. You will also learn how you can dial your phone using batch files, create software installation programs, control your printer, and perform many other operations with a single keystroke. More than that, batch files can create systems to protect your PC and its files from prying eyes and fingers. You can even create a database system with batch files which will let you have almost instant access to any information. Batch files can use a number of special commands to teach your PC to do things you never thought possible. Best of all, they are easy to use. Part 2: Batch File Menus 5

batch_files_explained.txt

26/02/2002

Whether you use a hard disk or floppies on your PC, learning to create a menu system can save valuable minutes and make your PC easier to use. In addition, if you help other people with their computers, installing a menu system can help you avoid constant phone calls for help. Batch files are an ideal method for creating menus. Batch file menu systems are easy to write, easy to change, and extremely powerful. You can incorporate as many features into your menu as you like, allowing you or anyone else to access programs with a single keystroke. USING THE ECHO COMMAND

Page 7 To create a menu system, you need to be able to write information on the screen with your batch file. PC/MS DOS gives you a command which makes this easy: ECHO. Here's how it works: You can use the ECHO command in two ways. Each uses a different format. The first format allows you to tell your PC whether or not you want to see the commands in your batch file listed on the screen. Usually you don't, and the command used to disable screen writing is: ECHO OFF When you include this command in a batch file, commands in that file will not appear as they are executed. This makes for a cleaner screen appearance. To turn the ECHO function back on, just include the command: ECHO ON. The second format for the ECHO command allows you to place messages on the screen. You'll use this function to write your menu on the monitor. The syntax is: ECHO [message] For example, to write the line "Master Menu" on the screen, include the command: ECHO Master Menu as a line in your batch file. You can control the position of the message by including spaces. If you want to center a line on the screen, simply subtract the number of characters in your message from 80, then divide the result in half. Place that number of spaces in front of your message. To make a menu or other text screen attractive, you need to be able to add blank lines. The ECHO command can do this as well, but there's a trick to it. Until DOS Version 3.3 appeared, creating blank lines wasn't simple. Instead of simply following the ECHO command with a space, which creates a blank line in DOS 3.3, earlier versions of DOS require a special method. This method will work with any version of DOS from 2.0 to 3.3. To create a blank line, place the ECHO command on a line in your batch file. Next press the space bar once, then hold down the <Alt> key while you type 255 on the number pad. The numbers at the top of the keyboard won't work. Doing this inserts the ASCII character number 255, which is a blank character. This fools DOS into thinking that there is a message, and creates a blank line on the screen. 6

batch_files_explained.txt

26/02/2002

This method works with the COPY CON method for creating batch files, and with most word processors. If your text editor doesn't support this function, either use another editor or simulate a blank line by inserting a period following the ECHO command. One final note on the ECHO command: You cannot use the DOS redirection characters (< and >) in an ECHO statement. If

Page 8 you do, the error message, "Bad command or filename," will appear. CREATING THE MENU SYSTEM Now that you know how to use the ECHO command to create messages on the screen, you're ready to create a menu. For the purposes of this article, let's assume that you want your menu to call Microsoft Word, Lotus 123, QMODEM, and the game ROGUE. You can also include a menu choice to return to DOS in the menu. Naturally, you will use the programs on your disk as replacements for those in this sample program. Using the COPY CON command as described in the first part of this series, or your favorite text editor, create the file MENU.BAT in the root directory of your hard disk or on a floppy disk. Don't include the comments in parentheses, and substitute names of programs. ECHO OFF (Turns off the echoing of batch file commands) CLS (Clears the screen) ECHO [Alt-255] (Create a blank line as described above. Use as many of these blank lines as you like.) ECHO[35 spaces]Master Menu ECHO [Alt-255] ECHO[32 spaces]Do you want to: ECHO [Alt-255] ECHO[15 spaces]1. Use your word processor? ECHO[15 spaces]2. Use Lotus 123? ECHO[15 spaces]3. Use your communications program? ECHO[15 spaces]4. Play Rogue? ECHO[15 spaces]5. Return to the DOS prompt? ECHO [Alt-255] ECHO At the DOS prompt, type the number of your selection ECHO and press [Enter]. Be sure to place a carriage return at the end of the last line of the file, then save it in ASCII format, or press <F6> if you are use the COPY CON command. To call your menu screen when you boot your computer, include the command, MENU, as the last line of your AUTOEXEC.BAT file. Once again, you can customize this menu screen any way you like. Include as many menu choices as you need, and insert blank lines and spaces to make the screen as attractive as possible. When MENU.BAT is executed, it will write the menu on the monitor, then the system prompt will reappear. 7

batch_files_explained.txt EXECUTING YOUR MENU CHOICES

26/02/2002

Page 9 Once you've written the MENU.BAT file, you need to write individual batch files for each menu choice. These files will call a program when you or the user enters a menu selection. Name the files to match your menu selections. In the sample menu presented here, the files would be named 1.BAT, 2.BAT, and so on. Each of these files will contain the commands needed to call the program. Here's 1.BAT: ECHO OFF CLS CD WP WORD CD\ MENU (This line turns off the ECHO function) (Clear the screen) (Change directories...not needed for floppies) (Call Microsoft Word) (Change to the root directory after quitting Word) (Return to the menu)

Naturally, you'll include the commands needed to perform the functions in your menu, rather than the ones used here. Floppy disk users can ignore the CD commands in their batch files. Create a separate file for each menu choice. The last menu choice, which you should include in any menu system, takes the user to the DOS prompt, allowing him or her to use the computer for purposes not included in the menu. Here's a sample, 5.BAT, for this menu: ECHO OFF CLS CD\ This file will return the user to a clean screen and the system prompt. REFINING YOUR MENU SYSTEM Generating screens with the ECHO command is only one of the ways you can write information on the monitor. If you create a complex screen, you'll notice that when the batch file executes, the screen appears rather slowly. This is one of the drawbacks to the ECHO command. There's an alternative to the ECHO command for screen generation. Since you can use any DOS command in your batch files, you can use the TYPE command to place text on the screen. To do this, create your screen with your text editor or word processor. Save the screen as an ASCII file, then call it with the TYPE command in your MENU.BAT file. The menu will appear much faster, particularly if it is a complex one. You can even include boxes and other special characters if your text editor supports extended ASCII characters.

8

batch_files_explained.txt

26/02/2002

Page 10

Keep your text screens shorter than 23 lines to prevent unwanted scrolling when the TYPE command lists the file on the monitor. Here is a MENU.BAT file which performs the same function as the previous one, but this time it calls a screen created with a word processor. The screen file is named MENU.DOC. ECHO OFF CLS TYPE MENU.DOC This file is obviously much shorter, and the menu screen will appear very quickly on the monitor. The individual files which call the programs will be exactly the same. In many cases, you may want to eliminate the DOS prompt entirely from your menu. That's easy, using the PROMPT command. PC/MS-DOS allows you to customize a prompt to suit your needs. As an example, you could replace the last two lines in the original MENU.BAT file shown above with the following line: PROMPT Type your selection and press [Enter]: This line would replace the normal A> or C> prompt with the text following the PROMPT command. The normal cursor appears at the end of the new prompt. You can even eliminate the prompt completely. Do this by using the same <Alt>-255 keystroke combination used with the ECHO command. Just type PROMPT, then hold down the <Alt> key while you type 255 on the number pad. If you turn off or change the prompt, however, be sure to restore it to its original form in the menu selection file which returns the user to DOS. To do this, simply add a line to the batch file. This line should contain the command, PROMPT, and nothing else, and will restore the normal system prompt. MULTI-USER MENUS The menu-creation process can be further refined for computers used by more than one person. In many cases, you want to restrict certain users to a specific group of programs. This technique can even be used to create a simple password system. It's not extremely secure, but will limit unsophisticated users to a limited group of programs. Here's how to create this type of system. First, create a batch file called PASSWORD.BAT. sample: Here's a

9

batch_files_explained.txt Page 11

26/02/2002

ECHO OFF CLS PROMPT Please enter your password: Call this file from the AUTOEXEC.BAT file, after loading any memory-resident programs, and performing any other start-up functions. The screen will clear, and the prompt will ask for the user's password. If security isn't important, you could ask for the user's name instead. Now, create a menu for each user, giving it a filename which matches the password or name the user will enter. Using the techniques described above, you can limit access to a specific list of programs for each user. In this case, however, don't include a menu choice which exits to DOS. Instead, make the last menu choice call the PASSWORD.BAT file. If you need to change a user's password, simply change the name of the batch file which calls that user's menu. If the user needs to use certain DOS commands, such as COPY, DELETE, or BACKUP, you can allow the use of a limited set of DOS commands by including them in a directory, then changing to that directory with a batch file called from the user's menu. Once again, this system is not perfectly secure. Any user sophisticated enough to use the <Ctrl>+<Break> combination can exit to DOS. When he or she does that, however, the prompt will still ask for a password. If you use DOS 3.0 or a later version, you can add to the system's security. Use any utility program, such as Norton Utilities or PC-Tools to change your password batch files to hidden files. Anyone doing a directory will not see the files on the screen, but DOS knows they are there and will execute them normally. Earlier versions of DOS cannot execute hidden files. As the installer or main user of a multi-user PC, you can bypass the password system by having a batch file with your password simply reset the prompt and exit to DOS. This will allow you or another user full access to the system. The next part of this series will introduce a number of other DOS commands which are especially useful in batch operations. Using these commands, you will gain even more control over your PC and its peripherals, increasing the power of your batch files.

Page 12

Part 3: Expanding Batch File Operations 10

batch_files_explained.txt

26/02/2002

If you're like most PC/MS-DOS users, you use a few basic DOS commands regularly. Other commands you may not use, however, have the power to make your PC even more useful and efficient. Including these commands in your batch files can add new flexibility and let you control your PC better, making it an even more powerful tool. Here are some little-known DOS commands especially suited for batch files. The ASSIGN Command This very powerful DOS command tells your PC to send all calls for one disk drive to another. Programs often look for data on a specific drive. This is especially true with public domain and shareware programs. These programs assume that the disk containing data files is in drive A: or B:. Hard disk users often have difficulties running these programs. When the program wants to open a file on drive A: and that file is on drive C:, the program can't find the file and often just exits to DOS. Using ASSIGN, you can tell your PC to look on drive C: for files, no matter what the program tells it to do. Here's the format for that command: ASSIGN [D1 = D2] To send all calls for drive A: to drive C:, the command would be: ASSIGN A = C There are a few restrictions to the use of ASSIGN. You can't use it while using the PRINT command. In addition, FORMAT will not run when ASSIGN is in use. Notice, too, that colons aren't used after the drive names when you use the ASSIGN command. After using this command, you must turn off the drive assignment before going on to other computer operations. Simply issue the command, ASSIGN, without any drive parameters. You can do this automatically in a batch file. For an example, let's assume you want to run the game program, CASTLE, which looks for a data file in drive A:. You have CASTLE and its data file on Drive C:, which would abort the program when it couldn't find the data file. Here's a batch file to solve the problem:

Page 13 ASSIGN A = C CASTLE ASSIGN This file, which you might call PLAY.BAT, solves the problem, and returns you to the normal configuration when you exit from the game. You can also use the ASSIGN command to lock out your hard 11

batch_files_explained.txt

26/02/2002

disk if you are testing a questionable program. Just give the command, ASSIGN C = A, and the PC won't try to write any data to your hard disk. Just remember to get rid of the assignment before resuming normal operations. The ECHO Command In part 1 of this series, you learned to use this command to display screen messages. ECHO can perform other functions, however, which are useful in batch files. For example, you might want to make the computer beep at some point during the execution of a batch file. To do this, include the following command as a line in your file: ECHO ^G Type ECHO, press the space <Ctrl> key while you press character, ASCII number 7, command executes, you hear bar once, then hold down the the <G> key. This adds a to your command. Whenever this the familiar beep.

You can also use the ECHO command with the DOS redirection characters < and > to send text to your printer or to your serial ports. Here's a good example: You may need to print labels with your return address on them. It's easy, using a batch file containing the following lines: ECHO Your Name >PRN ECHO 123 Your Street >PRN ECHO Anytown, Anystate 12345 >PRN Add blank lines before and after the text. Adjust the number of blank lines to suit your printer and the labels you use. You'll have to experiment to get it just right. Call this batch file RETURN.BAT, or any other name you like. Whenever you execute the file, it will print your return address, saving you from starting your word processor to create an address label. You can also create similar files for other addresses. The MODE Command

Page 14

The MODE command allows you to control your monitor, your serial ports, and your printer. The command is very seldom used, due to its hard-to-remember syntax. This makes it a natural for batch files. To use the MODE command in batch files, the DOS utility MODE.COM or MODE.EXE must be in your current PATH, or on the floppy disk containing your batch file. If DOS can't find the program, an error message will appear on your monitor. If your PC has a CGA or EGA display adapter, you can use the MODE command to change from one display mode to another. If you want to change from the normal mode to a forty-character color screen, include the following line in a batch file: 12

batch_files_explained.txt MODE CO40

26/02/2002

Check your DOS manual for other screen modes. You can include this command in a long batch file, or use it alone in a file called 40.BAT. The syntax for the MODE command format used to set up your serial port is very complex. Using a batch file, you can avoid having to memorize this syntax. To set your COM1: port to 1200 baud, with even parity, seven data bits, and one stop bit, just use the following line in any batch file: MODE COM1: 1200,E,7,1 Later, you will learn how to incorporate this command line in a batch file telephone dialing system. Many users have a printer connected to a serial port. In this case, DOS needs to know where the printer is, since it assumes that the printer is connected to LPT1:. Include the following line in your AUTOEXEC.BAT file and your PC will automatically send all printer output to COM1:. MODE LPT1: = COM1: If your printer, on the other hand, is connected to LPT2:, the second parallel port, use the following line: MODE LPT1: = LPT2: Finally, you can use the MODE command to set your printer's mode of operations, controlling the number of characters per line, the number of lines per inch, and whether or not you want the computer to keep trying if the printer sends an error message to the computer. Here's the syntax: MODE LPT#: [characters\line], [lines/inch], [P]

Page 15

Following this syntax, to set your printer for 80 characters per line, 8 lines per inch, and to retry on errors, use the following command in a batch file: MODE LPT1: 80,8,P The PAUSE Command Many time, during the execution of a batch file, it is useful to have the batch file stop operations while you do something, like load paper into the printer. The PAUSE command halts the operation of a batch file temporarily. Like many other batch file commands, PAUSE allows you to include a message. As an example, you can create a batch file which tells the user to put a blank, formatted disk in drive B: before a COPY operation. Here is the command to use: PAUSE Place a blank, formatted disk in drive B: 13

batch_files_explained.txt

26/02/2002

When DOS encounters this line in a batch file, it displays the following information on the screen: Place a blank, formatted disk in drive B: Strike a key when ready... The batch file stops until the user presses any key. When a key is pressed, the batch file moves to the next line and executes the command there. The command might be to COPY a file or files to the disk the user inserted in drive B:, as requested by the PAUSE message. The PROMPT Command In the previous part of this series, you learned to use the PROMPT command to replace the standard DOS system prompt with a message. This command can also be use to create other customized prompts. Including one of these PROMPT commands can add productivity to your work. This format of the PROMPT command uses the <$> character in combination with a letter to change your normal prompt. Here's an example: PROMPT $n$g This sets the prompt to the normal A> or C>, depending on the default drive you've set. If you'd rather see a prompt which displays the current directory, include this variation in your AUTOEXEC.BAT file: PROMPT $p$g

Page 16

There are a number of other characters, which set the prompt. You can use them in any combination you choose, preceding each letter with a dollar sign. Character $t $d $p $v $n $g $l $b $_ (underscore) Display The current time The current date The current directory The DOS version number The current drive The ">" character The "<" character The "|" character A carriage return

Using a combination of these character commands, along with text, you can create customized prompts. Just for an example, let's look at a complex PROMPT command: PROMPT Hello, Mary$_It's $t$_You're in the $p directory$_Please enter a DOS command $g PROMPT commands must be entered on a single line, so don't include any carriage returns. When this PROMPT is included in a batch file it will produce a prompt which looks like 14

batch_files_explained.txt this on the monitor: Hello, Mary It's 9:25:32.21 (current time) You're in the \UTILITY directory (actual directory) Please enter a DOS command >

26/02/2002

Experiment with this command to create custom prompts for yourself, or to provide information to other PC users. Including a special PROMPT command in your batch files can increase your productivity and prevent confusion. The REM Command Working with batch files is actually a form of programming. As your batch files grow in length, they can become confusing. Inserting comments can help you understand how the file works. This is especially important when you need to change a complex batch file later. The REM command allows you to insert comments in your files. Any text in a batch file which follows a REM command can contain your comments. These comments will not be seen on the monitor, but will appear when you TYPE the file or print it out. I recommend using REM comments frequently in long and complex batch files you create.

Page 17 Here's an example: REM This batch file copies three files to Drive B: PAUSE Insert a blank, formatted disk in Drive B: COPY LETTER.DOC B: COPY RESUME.DOC B: COPY NOVEL.DOC B: REM The next line displays LETTER.DOC on the monitor. TYPE LETTER.DOC Using the DOS Redirection Characters Earlier in this series, the two DOS redirection characters, < and > were mentioned. These characters are a powerful way to tell your PC to send the output of files to a different place than they would normally go. Using redirection in your batch files can be a powerful tool. For example, you might want to print a text file from within a batch file. Using the TYPE command and a redirection character, it's easy. Here's a command which you can use to send any text file to a printer: TYPE [filename.ext] >PRN The ">" character redirects the output of the TYPE command from the monitor to the printer. You will use this frequently. Similarly, to send a directory to the printer, include the following command in any batch file: DIR >PRN 15

batch_files_explained.txt

26/02/2002

It's easy to see how useful this can be. When you redirect the output from a command to another device, such as the printer, it doesn't appear in its usual place. You can use the redirection character to send output to the following devices: PRN (a printer attached to LPT1:) LPT#: (A parallel port) COM#: (A serial port) CON (The monitor) NUL (Nowhere at all) The last device, NUL, is your computer's version of NeverNever-Land. Anything sent to the NUL device simply goes nowhere at all. Oddly enough, this is very useful in batch files. Many DOS commands you will use in batch files produce messages on the screen. The COPY command is a good example. Whenever you COPY a file or files, the familiar message, "#

Page 18 file(s) copied," appears on the screen when the operation is finished. There are many times when you don't want that message to show, especially when your batch file copies multiple files. Having the message appear slows down the operation, and clutters the screen you have so carefully created. Here's an example of the use of the NUL device: COPY LETTER.DOC B: >NUL Including the redirection character and the NUL device tells DOS to send the message, "1 file(s) copied," to the NUL device instead of to the monitor. It's very simple. Other uses for this function include getting rid of messages provided by many memory-resident programs. If you don't want to see the message, simply redirect it to the NUL device in the line used to call the program. You can even use this technique to introduce delays into your batch files. Simply COPY a file to the NUL device. The longer the file, the longer the delay. Here's an example: COPY LETTER.DOC NUL >NUL When DOS encounters this command, it reads the file, then copies it right into oblivion. The original file remains on the disk, but the time it takes to read the file will simply cause a delay in the execution of the batch file. The second NUL combined with the redirection character keeps the COPY command message off the screen. Command Line Parameters Since a batch file can contain commands which execute other batch files, it is useful to be able to include variables in your batch files. DOS allows you to do this with a parameter you include when you execute the original file. 16

batch_files_explained.txt

26/02/2002

By typing the name of the batch file, a space, then the parameter, you can tell DOS that you have included a variable in your command. You have used this feature before with commands like: FORMAT B: or CHKDSK A:. The drive designator in each of those commands is a replaceable parameter which you can change each time you give the command. These parameters, when used with batch files can represent anything you wish, a drive name, a file, or the command which starts another batch file. The replaceable parameter is represented in the batch file itself with a per cent sign (%), followed by a number

Page 19 between 1 and 9. Whenever your file encounters this sign it substitutes your command line parameter for the sign. For example, to create a batch file which copies all files from either drive A: or drive B: to your hard disk, which is drive C:, using a simple command, use C.BAT below: ECHO OFF CLS COPY %1:*.* C: To use this batch file, give the following command: C A or C B With three keystrokes, you can save typing in the entire command sequence. Notice that the parameter is expressed in the batch file with a number (%1). You can use up to nine command line parameters (%1 to %9), separated by spaces in your batch files. This opens up many possibilities. You can expand the C.BAT file above to accept a path parameter as well. This lets you specify a directory on your hard disk, allowing you to copy the files to a specific directory. Here's the new C.BAT: ECHO OFF CLS COPY %1:*.* C:\%2 Now, give this command: C A TEMP This time, your batch file copies all files from drive A:, the first parameter, to the \TEMP directory on drive C:. Each time you execute the batch file, you can use different parameters to control the process. Here's the command this batch file has replaced: COPY A:*.* C:\TEMP It's easy to see how many ways you can use command line 17

batch_files_explained.txt parameters to control functions in batch files. A Batch File Telephone Dialing System

26/02/2002

Now that you've learned some of the DOS commands which are especially useful in batch files, it's time to use some of these commands for a practical application. Since most of us call a small list of people regularly while we're using

Page 20 the computer, creating a batch file dialing system makes sense. This system requires a Hayes-compatible modem, and can dial an unlimited number of people, depending only on how many files you want to create. First, create a directory called \PHONE in the root directory of your hard disk. Include this new directory in your PATH so you can access it from any other directory. If you use a floppy-based PC, format a floppy disk to hold your dialing system. Now, using either the COPY CON command or your favorite text editor, create the following batch file, naming it CALL.BAT: ECHO OFF CLS CD\PHONE REM Leave this line out for floppy systems. ECHO Calling %1...... MODE COM1:1200,E,7,1 >NUL %1 CD\ REM Leave this line out for floppy systems If you have a 300 or 2400 baud modem, simply substitute that number in the fourth line of the file. Notice that line four uses the >NUL redirection routine to eliminate the screen message produced by the MODE command. Now, create a separate batch file for each person you want to include in your dialing system. Name the files so they will be easy to remember, and give each file the .BAT extension. For example, you might create BILL.BAT, MOM.BAT, DOCTOR.BAT, or any other filename you might use. Just remember that the filename must be no more than eight characters long. Here's a sample file, named BILL.BAT ECHO OFF CLS ECHO ATDT5551234 >COM1: Naturally, you would substitute the correct phone number for the person you're calling. If you are in a non-tone dialing area, substitute ATDP for ATDT to use pulse dialing. Finally, if your modem is connected to another COM port, use that port designator in place of COM1:. Create as many files as you like, storing them all in the \PHONE directory or on your floppy disk. 18

batch_files_explained.txt

26/02/2002

If your modem uses a different dialing command than the Hayes-compatible ATD? command, make another substitution in the ECHO line.

Page 21

Here's how the system works: To call Bill, or another person in your system, give the command, CALL BILL, and press <Enter>. The first batch file, CALL.BAT, clears the screen, tells you who you are calling, then sets the communications parameters with the MODE command. Next, it executes the batch file with the name you used as a replaceable parameter, Bill in this case. BILL.BAT executes, using the ECHO command to send the dialing command and the telephone number to your modem. At this point, you can listen to the progress of the call on your modem's speaker, or just pick up the phone and wait for an answer. You can use your dialing system anytime you see the system prompt. Many programs allow you to exit temporarily to DOS, so you can also make phone calls while using any of these programs. You can use DOS batch files as a simple programming language to create programs like the dialing utility above. The advantage to batch programming is its simplicity. Creating a telephone dialing system in most other programming languages would take hours. Using batch files, the program is finished in minutes. A Batch File Database Following a similar format to the telephone dialing system, you can create a simple database system to store names and addresses, using simple batch files. First, create a new directory called \FILE on your hard disk or format a floppy disk to be used for this system. One again, if you install this system on your hard disk, be sure to include it in your PATH for easy access. Write the following batch file, LOOKUP.BAT, to serve as the main program: ECHO OFF CLS CD\FILE REM You can leave this line out for floppy systems. ECHO Searching....... TYPE %1.ADD REM This command line parameters displays the file CD\ REM Again, leave this line out for floppy systems. When creating this file, leave off the REM commands and the text following them. Now, for each person you want to include in your database, create a plain ASCII file which looks like this: ANYNAME DOE

19

batch_files_explained.txt

26/02/2002

Page 22 1235 SOME STREET ANYTOWN, STATE ZIP (555) 555-5555 <Enter> REM These lines add blank lines. <Enter> REM as you need.

Use as many

Give the file a distinctive name you'll remember. Use the extension, ADD. Store the file in the same directory or on the same disk as LOOKUP.BAT. Now, to view the information on your monitor, just enter the command: LOOKUP NAME Your LOOKUP.BAT file will find the filename you specify on the command line and display the information. Of course, you might not remember just which file you want to check. It's easy to write another batch file which will show you a list of files. You might call this one FINDFILE.BAT: ECHO OFF CLS CD\FILE REM Not used in floppy systems. DIR *.ADD/W CD\ REM Not used in floppy systems. By entering the FINDFILE command you will see a display of your filenames for this system. Notice the fourth line of the batch file. It reads DIR *.ADD/W. The *.ADD section tells DOS to show only those files which have the extension you use for your data files. This helps keep extraneous information off the screen. Now, suppose you want to print one of your files. Here's another batch file to do that. Let's call this one PRINTIT.BAT. ECHO OFF CLS CD\FILE REM Not used in floppy systems. COPY %1.ADD PRN CD\ REM Not used in floppy systems. All you have to do is enter a command like this one: PRINTIT NAME The file you name on the command line will go directly to your printer. If you have included the right number of blank lines in your original files, you can use this PRINTIT.BAT to print address labels. You'll have to experiment to get your files just right for your particular printer and labels.

20

batch_files_explained.txt Page 23

26/02/2002

Finally, you can write one more batch file which will print your entire list of files, creating mailing labels if you have formatted the files properly. Call this one PRINTALL.BAT. ECHO OFF CLS CD\FILE REM Not used in floppy systems. COPY *.ADD PRN >NUL CD\ REM Not used in floppy systems. Enter the command, PRINTALL, and every one of your files will be printed automatically. This address system is only one way you can use your batch file database. Another possibility is a recipe database. By storing files containing your recipes, you can use the same batch files to call up your favorites, print them out, or even print the entire recipe database. Just remember that any files you store in your batch file database must be pure ASCII files, created with either the COPY CON command or your favorite word processor or text editor. If you use a word processor, be sure to save the files in ASCII format. The possibilities for different kinds of data storage are endless. You also have the advantage of not being restricted to defined fields and field sizes, as you do with a regular database. In the next part of this series, you will learn several advanced batch file techniques, including ways you can use batch files in your programming. That part will also cover the creation of a batch file system to control your printer. It will allow you to change your printer's output with a single command.

Part 4: Advanced Batch File Techniques The first two parts of this series on batch files introduced a number of techniques to help you automate many of the operations you perform frequently on your PC. This time, we're going to take a look at more advanced batch file functions, adding even more power to your batch processing. Like all programming languages, batch files can perform loops and conditional branching. Loops allow your batch program to perform the same function several times, using information you supply to control the process. Conditional

Page 24 branching lets your batch files test to see if a condition is true and, if it is, forces the batch file to execute a subroutine. Let's look at conditional branching first. 21

batch_files_explained.txt BATCH FILE IF....GOTO BRANCHING

26/02/2002

If you are familiar with any programming languages, such as BASIC, the IF....GOTO sequence is familiar to you. The IF part of the sequence lets you test something, while the GOTO command tells your program to skip to a subroutine and carry out the commands it finds there. This capability is central to all programming, including batch programming. Before looking at the IF command, it's important to understand how the GOTO command works. Unlike many languages, DOS batch programs use labels with the GOTO command. A label marks the beginning of the subroutine, letting DOS know where to begin processing after it encounters a GOTO line. Batch file labels always begin with a colon (:). The label follows the colon, without any spaces or other characters. Here are some examples of correct label format: :START :ABORT :QUIT A label should be placed on a line by itself, immediately preceding the first command in the subroutine. This sample batch file, called SAMPLE.BAT, will demonstrate the use of the GOTO command: ECHO OFF CLS ECHO This batch file demonstrates branching. GOTO ROUTINE1 ECHO The batch file will skip this line. ECHO It will skip this line as well. :ROUTINE1 CLS ECHO You are now in the first sub-routine. ECHO When you press a key, you will go to the next routine. PAUSE GOTO ROUTINE2 ECHO Again, the batch file will skip this line. ECHO And this one, too. :ROUTINE2 CLS ECHO Now you are in the second sub-routine. ECHO Notice that the file skipped several lines.

Page 25 ECHO Pressing a key will take you to the third routine. PAUSE GOTO ROUTINE3 ECHO Another line skipped. ECHO Still another skipped line. :ROUTINE3 CLS ECHO Now you have reached the third subroutine. 22

batch_files_explained.txt

26/02/2002

ECHO This is the last subroutine. ECHO When you press a key, you will exit to DOS. PAUSE CLS Create this simple batch file, using the COPY CON command or your favorite text editor. Remember to save the file in ASCII format. Once you have created the file, run it. You will notice that the lines between the GOTO commands and the labels do not execute. Once DOS encounters the GOTO, it immediately jumps to the label, skipping all intermediate lines. When creating a label, use from one to eight characters. Avoid punctuation, and always use labels which are meaningful, to help you understand your batch file later. Unlike other languages, DOS allows you to use reserved words, like COPY and DELETE as labels in your batch files. For clarity's sake, however, it's best to avoid labels which are also the names of DOS commands. CONDITIONAL BRANCHING WITH THE IF COMMAND By itself, the GOTO command has limited usefulness. There is usually no reason to use GOTO unless you are testing to see if a condition is true or not. That's where the IF command comes in. Most programming languages use a command similar to the DOS IF command to test for a wide variety of conditions. In batch files, you are limited to testing just a few things: 1. Whether one string of characters equals another. 2. Whether or not a file exists. 3. The ERRORLEVEL of a program. In this article, we'll look at the first two conditions. The third is of limited usefulness to most DOS users. The first condition which can be tested with the IF command, whether one string is equal to another, is the most common. If you remember the discussion on command-line parameters, you know that a batch file can use up to 10 parameters when you give the command to execute the batch file. An example of this might be the command, FORMAT A:. The A: part of

Page 26 this command is a replaceable parameter, used by DOS to identify the drive to be formatted. By using the IF command in your batch files, you can check to see whether a command-line parameter equals a string you have specified in the batch file. Here's an example, which we'll call TEST1.BAT: ECHO OFF CLS IF %1. == . GOTO WRONG IF %1 == HELLO GOTO CORRECT GOTO END :CORRECT 23

batch_files_explained.txt

26/02/2002

CLS ECHO You typed HELLO. ECHO The batch file branched to the CORRECT routine. PAUSE GOTO END :WRONG CLS ECHO You didn't include a parameter in your command. ECHO To get to the subroutine, type the command: ECHO TEST1 HELLO, then press [Enter]. PAUSE GOTO END :END ECHO You typed something other than HELLO as a parameter. ECHO DOS recognizes the difference between upper and lower case. ECHO Try again. PAUSE CLS Let's take a look at some of the lines in this file. The first two lines are familiar, turning off ECHO and clearing the screen. The next line is new and uses the IF command. When you use the IF command to check command-line parameters and no parameter is given when the batch file is called, DOS normally returns the error message: SYNTAX ERROR. The line in TEST1.BAT which reads: IF %1. == . GOTO WRONG GOTO END tests to see if no parameter was given. The period (.) is used to supply a single character following the %1 parameter. Without it, the error message INVALID NUMBER OF PARAMETERS would appear. This line branches to the :WRONG subroutine if no parameter was used on the command line. The next line checks to see if the command-line parameter was HELLO. If it was, the batch file branches to the routine named :CORRECT.

Page 27 Following the second IF line is a line which reads, GOTO END. This line comes into play if neither of the conditions in the previous lines is true. If, for example, the command-line parameter was GOODBYE, the batch file would branch to the :END routine, skipping the rest of the file. It's important to include a line which branches around other lines if a condition isn't true. Otherwise, the batch file would simply go right into the :CORRECT subroutine. The IF command recognizes upper and lower case letters as different. So, typing hello in lower case letters would not satisfy the condition in the second IF line. Finally, notice that each subroutine in this batch file includes a GOTO END line. Again, this forces the program to branch around succeeding subroutines, avoiding errors. Create this batch file, then run it. The first time, do not include the parameter HELLO on the command line. Next, add hello to the command, using lower-case letters. Finally, 24

batch_files_explained.txt

26/02/2002

include the correct form of the parameter, HELLO. You will see the messages in the appropriate subroutine. Be sure to use two equal signs (==) in your IF lines. This is critical. Creating a Practical Application Using Branching While the sample batch file above demonstrates the use of the IF and GOTO commands, it doesn't serve any useful function. Let's create a batch file which solves a serious problem. It's all too easy to accidentally format a hard disk, particularly with versions of DOS earlier than 3.0. By simply typing the command FORMAT and pressing a key, all your hard disk files can be destroyed. DOS 3.0 and later add a warning message, but an unwary user or a malicious intruder can still easily format any hard disk. You can protect yourself against this disaster with the following batch file. It's called FORMAT.BAT. Since PC/MSDOS will execute a .COM file before a .BAT file, you need to rename the DOS formatting utility. Change to your DOS directory, and give the following command: REN FORMAT.COM FRMT.COM This is the first step in your protection scheme. Renaming the FORMAT.COM allows your FORMAT.BAT file to take over when the command, FORMAT, is given.

Page 28 Now, create the following batch file, storing it in a directory on your hard disk which is included in your path statement. Do not include the REM statement explaining how to enter the Ctrl+G command. Name the file FORMAT.BAT. ECHO OFF CLS IF %1. == . GOTO NOPARM IF %1 == A: GOTO CORRECT IF %1 == a: GOTO CORRECT IF %1 == B: GOTO CORRECT IF %1 == b: GOTO CORRECT IF %1 == C: GOTO ABORT IF %1 == c: GOTO ABORT IF %1 == D: GOTO ABORT IF %1 == d: GOTO ABORT GOTO WRONG :NOPARM ECHO ^G REM ***Hold down Ctrl and press the G key*** ECHO You must enter a drive designator to format a disk. ECHO Enter the command this way...FORMAT A:... using the ECHO drive designator for the correct drive. PAUSE GOTO END 25

batch_files_explained.txt

26/02/2002

:CORRECT ECHO Preparing to format a floppy disk. PAUSE FRMT %1 GOTO END :ABORT ECHO ^G ECHO ^G ECHO You have specified a hard disk for formatting! ECHO You cannot format your hard disk from this batch file! ECHO Use an alternate method! PAUSE GOTO END :WRONG ECHO ^G ECHO You have entered an invalid drive designator... ECHO Try again. Don't forget the colon. (:) GOTO END :END CLS Let's take a look at the IF statements in this file. First, using the technique discussed earlier, the file checks to see if a parameter has been included in the command line. If not, it branches to a subroutine called :NOPARM, which tells the user to include a drive designator.

Page 29

Next, the batch file checks to see if the parameter entered on the command line is a floppy drive. It tests for upper and lower case entries for drives A: and B:. If any floppy disk drive designator is given, the file branches to the :CORRECT subroutine. There, the FRMT command is given, executing the renamed formatting utility. The original command line parameter %1 passes to the FRMT.COM program. The next four lines check to see if the user entered the name of a hard disk, either drive C: or drive D:. Again, both upper and lower case are tested. If these drives are on the command line, the batch file branches to the :ABORT subroutine. That routine sounds an alarm and refuses to format the hard disk. Finally, if the user has specified an invalid drive, or left off the colon (:) following the drive letter, the GOTO WRONG line sends the program to another routine, which explains the error. Notice that each routine ends with a GOTO END line. This is very important, and keeps the batch file from accidentally drifting into another routine. You can customize this hard disk protection system to fit your particular configuration. Just alter it to reflect the drives on your own PC. You should be able to think of a number of other ways to use this feature of the IF command. Branching is an excellent way to add power to your batch files. 26

batch_files_explained.txt TESTING FOR THE EXISTENCE OF A FILE

26/02/2002

The IF command can also check whether or not a particular file exists. This can be very useful. For example, if you wanted to copy files from a floppy disk onto your hard disk, but only if that file already exists on the hard disk, this use of the IF command can save you time. You might do this to update files on the hard disk. Here is a batch file which does just that. COPYIF.BAT. Call it

ECHO OFF CLS IF EXIST C:\%1\%2 GOTO EXECUTE GOTO WRONG :EXECUTE ECHO Copying A:%2 to C:\%1 directory... COPY A:%2 C:\%1 PAUSE GOTO END

Page 30 :WRONG ECHO That file does not exist in the C:\%1 directory. PAUSE GOTO END :END CLS After creating COPYIF.BAT, try it out. Put a floppy disk in drive A: which contains files which are also in a directory on your hard disk. Use the DIR command to get a list of files. following command: COPYIF [DIRECTORY NAME] [FILENAME] Substitute appropriate information in the command to fit your particular directory and files. When the batch file runs, it will check the directory (%1) for the file (%2), then copy the file from drive A: if it finds the file also in the directory on drive C: Try this again, but name a directory which doesn't contain the file you name on the command line. You can see how the IF command works here. This is a useful if directory directory useful batch file, but it might even be more it only copied the file from drive A: into the if that file did NOT already exist in the you name. Now type the

DOS can do this as well. To change COPYIF.BAT to perform this function, just change the third line to read: IF NOT EXIST C:\%1\%2 GOTO EXECUTE Make this change in your COPYIF.BAT file, and save it with the new name COPYNOT.BAT. Try this new batch file the same way you did before. Now it only copies the file from drive 27

batch_files_explained.txt

26/02/2002

A: if it doesn't exist on drive C: in the specified directory. A batch file like COPYNOT.BAT is one way to prevent overwriting an existing file. BATCH FILE LOOPS WITH FOR...IN...DO No programming language is complete without a way of creating loops. A loop is a way of repeating a routine as long as a certain condition exists. DOS allows a limited use of loops in batch files, using the FOR...IN...DO command series. These loops are limited to dealing with filenames as the limiting structures. Here is the syntax:

Page 31

FOR %%variable IN (set) DO command That's slightly confusing. The %%variable is a dummy variable, composed of a single character. An example is %%A. All this really does is give DOS a handle to work with. The (set) described in the syntax is a list of files. Most often, this set uses DOS wildcards (? & *) to represent groups of files. For example, typical sets might include (*.*), (C:\*.*) or (C:\WP\DOC\*.BAK). You can include multiple entries inside the parentheses. To act on all .DOC,.BAK, and .TXT files, the set would be (*.DOC,*.BAK,*.TXT). You can use either commas or spaces to separate the individual files or wildcard entries. Just remember that the set you specify is the group of files you want to act upon. Finally, the command part of this structure can be any DOS command. To make this complex command series clearer, let's create a sample batch file. What this file will do is delete all the files with the extension .BAK in the \WP\DOC subdirectory on drive C: This is something most users do from time to time. Naturally, you can substitute any other directory when you create the file. Call the file KILLBAK.BAT. ECHO OFF CLS ECHO This file will delete all .BAK files from C:\WP\DOC. ECHO If you do not want to do this, press [Ctrl]+[Break]. PAUSE FOR %%A IN (C:\WP\DOC\*.BAK) DO DEL %%A ECHO All files with the extension .BAK have been deleted. PAUSE CLS You can use any DOS command in place of DEL. If, for example, you wanted to copy all files with the extension .COM from drive A: to drive B:, the command would look like 28

batch_files_explained.txt this: FOR %%A IN (*.COM) DO COPY A:%%A B:

26/02/2002

Similarly, to print out all your .BAT files in the \BATCH directory on your hard disk, the command would look like this: FOR %%A IN (*.BAT) DO COPY C:\BATCH\%%A PRN

Page 32

It's easy to see how useful this looping command structure can be in your batch files. You can repeatedly perform a DOS command, controlling the files it operates on by changing the variables in the FOR...IN...DO command structure. Experiment with these commands in your batch files. CONTROLLING YOUR PRINTER WITH BATCH FILES In the last part of this series of articles, I promised that I would include a method of controlling your printer using batch files. While the current crop of dot-matrix printers have some wonderful capabilities, making use of them can be a chore. You can either write a short program in BASIC to send commands to the printer, or use a special printer utility program. Both of these systems work, but take time you could spend more productively. The problem lies in DOS. In its wisdom, Microsoft wrote PC/MS-DOS in a way that prevents you from sending the Escape character (ASCII 27) to your printer. You can send almost any other character to the printer in a batch file with the ECHO command and the redirection character (>). Any other character, that is, except the Escape character. Most printer commands are preceded with the Escape character, so it's normally impossible to control your printer from the system prompt. For this printer control system to work, then, you need a program which can do what DOS can't do. Fortunately for all of us, Calvin R. Shields has placed such a program in the public domain. A short program, written in assembly language, it also illustrates another use of batch files. Create the following batch file, using your favorite method. Be very careful to type the program exactly as it appears here, including the blank lines. Call it MAKE-ESC.BAT. GOTO START A 100 XOR DX,DX MOV AX,001B INT 17 MOV BX,0080 MOV CL,[BX] XOR CH,CH JCXZ 011F 29

batch_files_explained.txt INC DEC JCXZ BX CX 011F

26/02/2002

Page 33 INC MOV XOR XOR INT LOOP INT BX AL,[BX] DX,DX AH,AH 17 0114 20

R CX 21 n esc.com w q :START DEBUG < MAKE-ESC.BAT Notice the first line of the file, which sends the program to the :START subroutine. There, this batch file calls the DOS DEBUG program, using the redirection character to make DEBUG assemble the program, ESC.COM, from the assembly language routines included in the batch file. This is a very creative use of batch files. Before running this batch file, make sure that DEBUG.COM or DEBUG.EXE (depending on your version of DOS) is in your current path. If you are using floppy disks, copy the DEBUG program onto the disk containing MAKE-ESC.BAT. Run the batch file. You will see a brief error message, caused when DEBUG finds the first line of the program. Ignore this message. Once the file runs, you will have a 33-byte program called ESC.COM on your disk. This program does what DOS can't do: it sends the Escape character to your printer, which must be connected to the parallel port, LPT1:. To make ESC.COM work, all you have to do is give the command, ESC, followed by a space and the command you want to send to the printer. For example, the command which resets an Epson-compatible printer looks like this: ESC @ <Enter>

The simplicity of these commands makes controlling your printer easy. But who can remember all the commands? That's where batch files come into the picture. To create a system for setting your printer's characteristics, all you have to do is write a short batch file which gives the commands needed to set the printer. Name each batch file with an easy-to-remember name.

30

batch_files_explained.txt

26/02/2002

Page 34 The batch files which follow will work with any Epson or Epson-compatible printer. If you use another type of printer, substitute the command for your printer in the batch file. Let's start with the reset command, which will put the printer in the start-up mode. Call this file RESET.BAT. ECHO OFF CLS ESC @ Here's another file. This one sets the printer to its Near Letter Quality mode. Call it NLQ.BAT. ECHO OFF CLS ESC X1 I've included the ECHO OFF and CLS lines to keep your screen clear when you issue the commands. Here's another sample. ECHO OFF CLS ESC E By consulting your printer's manual, you can find all the commands which make your printer jump through its hoops. Write a separate batch file for each command, and you will soon have a printer control system which can handle every function. You can also combine functions by entering the commands, one-at-a-time. If your printer is an Epson compatible, the batch files in LISTING 1 will handle almost every possible function. Again, if you use another kind of printer, consult your manual for the appropriate commands. Place the batch files and the ESC.COM program in a directory which is in your current path. Then, whenever you need to send a command to your printer, just give the name of the appropriate batch file as a DOS command. The next part of this series will show you how to make batch files even more flexible, using additional commands and external programs. There are a number of commercial, public domain, and shareware programs which can add power to your batch programming. ##End main copy## Call this one BOLD.BAT.

31

batch_files_explained.txt Page 35

26/02/2002

LISTING 1 These batch files are designed to be used with the ESC.COM program in the main article. If your printer is Epsoncompatible, the system will work as written. If you have another brand of printer, substitute the appropriate commands. Create these files using the COPY CON command or use your favorite text editor in its ASCII Mode. RESET.BAT -- Sets the printer to its default mode. ECHO OFF CLS ESC @ PICA.BAT -- Sets pica (10 characters/in.) ECHO OFF CLS ESC P ELITE.BAT -- Sets elite (12 characters/in.) ECHO OFF CLS ESC M CONDENSE.BAT -- Sets condensed type. ECHO OFF CLS ESC ^O REM **<CTRL>+<O>** TINY.BAT -- Sets microtype (20+ characters/in.) ECHO OFF CLS ESC M ESC ^O REM **<CTRL>+<O>** ESC S1 ESC 1 ITALIC.BAT -- Sets italic mode ECHO OFF CLS

Page 36 ESC 4

32

batch_files_explained.txt UNITALIC.BAT -- Cancels italic mode ECHO OFF CLS ESC 5

26/02/2002

WIDE.BAT -- Sets double-width type ECHO OFF CLS ESC W1 UNWIDE.BAT -- Cancels double-width ECHO OFF CLS ESC W0 NLQ.BAT -- Sets Near Letter Quality mode. ECHO OFF CLS ESC x1 UNLQ.BAT -- Cancels Near Letter Quality ECHO OFF CLS ESC x0 6LPI.BAT -- Sets 6 line/in. spacing. ECHO OFF CLS ESC 2 8LPI.BAT -- Sets 8 line/in. spacing. ECHO OFF CLS ESC 0 10LPI.BAT -- Sets 10 line/in. spacing.

Page 37

ECHO OFF CLS ESC 1 BOLD.BAT -- Sets Boldface. ECHO OFF 33

batch_files_explained.txt CLS ESC E NOBOLD.BAT -- Cancels Boldface. ECHO OFF CLS ESC F UNDRLINE.BAT -- Underlines all text. ECHO OFF CLS ESC -1 NO-UNDER.BAT -- Cancels underlining. ECHO OFF CLS ESC -0 2STRIKE.BAT -- Starts double-strike mode. ECHO OFF CLS ESC G 1STRIKE.BAT -- Starts single-strike mode. ECHO OFF CLS ESC H ##End Listing 1##

26/02/2002

Campbell -- Batch Power

Page 38

The Power of PC\MS-DOS Batch Files by George Campbell Part 4: Adding More Power

In the first three parts of this series on batch files, you 34

batch_files_explained.txt

26/02/2002

learned many of the techniques possible with PC/MSDOS batch processing. By now, you're probably using batch files to perform many functions you used to do, one command at a time, from the system prompt. In this article, which will be the last part of this series, you'll learn ways you can expand your batch processing even further. Although PC/MSDOS batch files have the power to make your PC do things you didn't expect, there are limitations to batch operations. Here are some ways to get around those limitations: GETTING KEYSTROKES FROM EXTERNAL FILES One of the major limitations of a PC/MSDOS batch file is the inability to insert keystrokes into the batch file from the keyboard. You can't stop a batch file, ask for user input, then continue with the execution of the batch file. There are many times when you might want to do just that. PC/MSDOS has several commands which insist on user input. FORMAT, DISKCOPY, and DEL *.* are three of those commands. If your goal is complete automation of a command with batch files, these three operations will stall your batch file until you type a letter. Fortunately, there's a way to bypass this limitation. you need to do is create an external ASCII file which contains the keystroke. Here's a good example: All

In my own work, I often place files in a directory on my hard disk, called C:\TEMP. Once I'm finished working with those files, I want to delete them from the disk. To do this means using the DEL *.* command. PC/MSDOS, however, insists that I confirm the command by typing a Y. If I give the command from a batch file, I still have to type the letter.

Campbell -- Batch Power

Page 39

To get around this problem, you can create a file which contains just the letter, Y and a carriage return. I call the file YES.ASC. Create this file by entering the keystrokes shown below: COPY CON YES.ASC Y <Enter> F6 <Enter> With that file stored on the disk, you can tell a batch file to take its input from the file and send it to any program called by the batch file. Using the example above, here's a batch file, named KILLTEMP.BAT, which deletes all files from the directory C:\TEMP: ECHO OFF CLS DEL C:\TEMP\*.* <YES.ASC Create this file, using either the COPY CON command, or your text editor. Substitute a directory name which applies to 35

batch_files_explained.txt your computer for the one shown here.

26/02/2002

This batch file works by using redirection. The "less than" symbol (<) tells PC/MSDOS to take directions from the file, YES.ASC rather than from the keyboard. When the command DEL *.* gives the message "Are you sure (Y/N)," it sees the character "Y" included in the YES.ASC file, and thinks you've typed the letter on the keyboard. You can use this technique with any DOS command which asks for a confirmation from the user. Be very careful, however, not to use the method if there is any danger of deleting important files. External text files can be used to create all sorts of useful DOS utilities. Take the FORMAT command, for example. This program in DOS requires user keystrokes which slow down the process of formatting new floppy disks. If you hate the job of formatting a pile of floppies, you can create a disk formatting utility which will format floppy disks continuously, prompting you to insert a new floppy disk and press a key. To make this batch file work, you need to create a very short text file which contains the keystrokes needed for the PC-MSDOS FORMAT.COM program. Call this file RESPONSE.ASC, and create it with the following commands: COPY CON RESPONSE.ASC <Enter> <Enter> N <Enter> F6 <Enter>

Campbell -- Batch Power

Page 40

Once you've created that file, you can set up a .BAT file to format diskettes continuously. Since this file is rather long and complex, I suggest using your text editor or word processor to create the file. Remember to save the file as a pure ASCII file. Call this file CFORMAT.BAT. ECHO OFF IF .%1 ==. GOTO NOPARM IF %1 == c: GOTO NOHARD IF %1 == C: GOTO NOHARD CLS GOTO START :START ECHO Alt+255* ECHO COMPUTER SHOPPER'S CONTINUOUS FORMAT UTILITY ECHO Alt+255* ECHO Alt+255* ECHO Alt+7* Echo Insert a new disk in drive %1 or press Ctrl+Break PAUSE CLS ECHO Alt+255* ECHO Alt+255* ECHO Alt+255* ECHO Now formatting....do not disturb disk in drive %1! FORMAT <RESPONSE.ASC %1 >NUL 36

batch_files_explained.txt

26/02/2002

GOTO RETURN :NOPARM ECHO Alt+255* ECHO Alt+255* ECHO YOU MUST ENTER A DRIVE NAME. EXAMPLE:(CFORMAT A:) PAUSE GOTO QUIT :HARD ECHO Alt+255* ECHO Alt+255* ECHO YOU CANNOT FORMAT A HARD DISK WITH THIS UTILITY. ECHO NOW RETURNING TO DOS.... PAUSE GOTO QUIT :RETURN GOTO START :QUIT CLS * Hold down the <Alt> key while you type the number on the numeric keypad. This batch file uses many of the techniques presented in earlier parts of this series, including replaceable parameters, subroutines, and conditional branching. It also uses the RESPONSE.ASC file to feed responses to the

Campbell -- Batch Power

Page 41

FORMAT.COM program. The line which reads, FORMAT <RESPONSE.ASC %1 >NUL, is the key to this utility. It calls the DOS FORMAT routine, then directs the program to take its responses from the text file you created. Finally, the >NUL at the end of the line keeps the normal screen messages from FORMAT.COM off the screen. To use this program, copy CFORMAT.BAT and RESPONSE.ASC to the disk or directory which contains FORMAT.COM. When you give the command, CFORMAT, add the drive name for your floppy disks. If you don't include a drive name in your command, the program will abort and remind you. If you specify drive C:, the batch file branches to the :NOHARD subroutine and aborts with a warning. The utility formats the disk, then returns to the beginning, beeps to remind you to change disks, and formats the next disk when you press a key. If you have a hard disk drive and two floppy drives, another version of this file can format disks in both drives, speeding up the process even further. Create this file in the same way, but name it CFORMAT2.BAT. ECHO OFF CLS goto START :START CLS ECHO Alt+255* ECHO Alt+255* ECHO COMPUTER SHOPPER'S CONTINUOUS FORMAT UTILITY ECHO Alt+255* 37

batch_files_explained.txt

26/02/2002

ECHO Alt+7* ECHO Be sure to turn your TURBO mode off. ECHO Alt+255* ECHO ECHO Insert new disks in drives A: and B: ECHO Alt+255* ECHO To exit, press Ctrl+Break. PAUSE CLS ECHO Alt+255* ECHO Alt+255* ECHO Alt+255* ECHO Now formatting....do not disturb disk in drive A: FORMAT <RESPONSE.ASC A: >NUL ECHO Now formatting....do not disturb disk in drive B: FORMAT <RESPONSE.ASC B: >NUL GOTO RETURN :RETURN GOTO START :QUIT CLS

Campbell -- Batch Power

Page 42

* Hold down the <Alt> key while you type the number on the numeric keypad. This file works in the same way, blank disks in both drive A: and routine runs, it beeps to remind timed this routine, and it saves disk formatting time. but automatically formats drive B:. Each time the you to change disks. I about 30% of the normal

You can use the same redirection technique to automate other utility programs which require keyboard input. Try writing your own batch file to make the DISKCOPY command run continuously. You'll need to write a text file, containing the keystrokes needed for that command, plus a batch file similar to the ones used for the FORMAT command. CREATING BATCH FILE PRESENTATIONS AND DEMOS Since batch files can automate many functions on your PC, creating demos and presentations is a natural use for these PC-MSDOS programs. A presentation or demo is typically a series of screens, displayed in order. Using batch files to make the process automatic can let you concentrate on your presentation, and not on operating the PC. The first step in creating a demo is to create the screens you want to display. Use your word processor or text editor to create as many screens as you like. If you use Word Perfect or another program which can do line drawing and boxes, you can enhance these screens. Many word processors can also use the <ALT>+numeric keypad technique to display extended ASCII characters, adding even more visual possibilities. Keep each screen down to 24 lines of text or less, so the whole screen can be displayed without scrolling. Save your screens in ASCII format, naming them SCREEN1.TXT, 38

batch_files_explained.txt

26/02/2002

SCREEN2.TXT, etc. Number the files in the order you want to follow with your demo or presentation. Now, create the batch file you'll use to display your screens. Call it DEMO.BAT, or any other name you like. Again, use your text editor or word processor to create the file. Leave out the REM commands and messages when you create the file. ECHO OFF CLS PROMPT Alt+255 REM Eliminates the DOS prompt. TYPE SCREEN1.TXT PAUSE>NUL REM Shuts off the "Press a key" message. CLS

Campbell -- Batch Power

Page 43

TYPE SCREEN2.TXT PAUSE>NUL CLS TYPE SCREEN3.TXT . . . . TYPE SCREEN(n) CLS PROMPT REM Restores the dos prompt. Expand this batch file to include all of your presentation screens. When you run DEMO.BAT, it will clear the screen, turn off the DOS prompt and load the first screen. To change screens, just press any key on the keyboard. The screen will clear and the next screen will appear. You can use the same program to create presentations for other users, as well. Just leave the >NUL off the PAUSE lines in the batch file. Now you can mail a disk containing your demo to another user. When that user types the command, DEMO, your screens will display, with the line, "Strike a key when ready," at the bottom of each screen to prompt the user for a keystroke. Even unskilled PC users won't have any trouble displaying your demo with this system. You'll find other uses for this presentation system. I use it for displaying the documentation for shareware programs, and for sending letters and other documents to PC users. BATCH FILE EXTENSION SOFTWARE There are a number of commercial, public domain, and shareware programs designed to enhance your use of batch programming. Using these external programs, you can add even more power to your batch files. You may already have one or more such programs in your software library. Here's a brief rundown on some of the best: THE NORTON UTILITIES This powerful collection of utilities contains several 39

batch_files_explained.txt

26/02/2002

programs design to enhance your batch operations. If you have this software, try out the following programs from the collection: ASK: This program does what DOS can't do, accepting keyboard input from users during the execution of a batch file. Especially useful in batch file menus, like the ones described in the first part of this series, ASK allows you

Campbell -- Batch Power

Page 44

to get a keystroke, then branch accordingly. This eliminates the need for additional batch files to call programs. BEEP: While you can cause your PC to beep in batch using the ECHO Ctrl-G command, Norton's BEEP command allows you to specify what kind of tone you get. You can even create files to play simple tunes using this command. SA: Short for Screen Attributes, this program allows you to alter your computer's screen characteristics. You can set up screen colors and other attributes by including this command, plus parameters in your batch files. This one is especially useful for the presentation system discussed above. For more information on THE NORTON UTILITIES, contact Peter Norton Computing, Inc., 2210 Wilshire Blvd., #186, Santa Monica, CA 90403. Phone: (800) 451-0303, Ext. 40. EXTENDED BATCH LANGUAGE This is a shareware program, designed specifically to increase the power of your batch files. Using it, you can accept user input, perform arithmetic functions, search for files, and control the appearance of your computer's screen, or use many more of the program's functions. This program is a complete programming language in itself. If you're serious about batch programming, this program is a must for your library. Like all shareware, you're free to try it out without charge. The author requests a registration fee of $49 if you continue to use the program. That fee brings you additional functions and a complete manual. EXTENDED BATCH LANGUAGE is available for downloading on GEnie and Compuserve, and can be found in the catalogs of most shareware distributors. It's also available directly from Seaware Corp., P.O. Box 1656, Delray Beach, FL 33444, Phone: (305) 392-2046. FSTSCRN2 This public domain program performs a very useful function. It converts an ASCII file, no more than 24 lines long, into a .COM file. By giving the name of the file as a command, you cause it to display on your monitor. What makes this program exciting is the way these converted 40

batch_files_explained.txt

26/02/2002

ASCII screens pop onto the monitor almost instantly. Use this program for menu screens, help screens, and screens used in the presentation system described above.

Campbell -- Batch Power

Page 45

Rather than displaying the screen with the TYPE command, just give the screen's filename as a command and you have instant response. FSTSCRN2 can add a professional look to your batch files. Download the program from CompuServe or GEnie. available on many local BBS systems. THEDRAW Designing attractive screens can be a problem. Using a word processor, especially when you want to include extended ASCII characters for simple graphics, can be a complicated process. THEDRAW is designed to solve just that problem. Written by California programmer, Ian Davis, it is a complete screen design utility. Using this program, you can create complex and attractive screens for menus, presentations, or demos -and you can do it quickly. The program even allows you to add color changes within your screen and, using ANSI.SYS in your CONFIG.SYS file, you can even create animated screens. THEDRAW screens are displayed with the TYPE command. Available on CompuServe, GEnie, and from most shareware distributors, the program is shareware, with a registration fee of $10. Contact the author directly at TheSoft Programming Services, 1929 Whitecliff Court, Walnut Creek, CA 94596. BOOTS This is a collection of three public domain utilities, which you can use in batch files to control booting your PC. WARMBOOT.COM simulates the <Ctrl>+<Alt>+<Del> keystroke combination and causes a warm boot of your PC. COLDBOOT.COM, the second program, simulates a cold boot. Instead of hitting the reset or power switch, you can reboot by giving the command, COLDBOOT. BOOTNOT.COM prevents a user from rebooting with the <Ctrl>+<Alt>+<Del> key combination. This is very useful, especially if inexperienced users might destroy data on your PC by accident. The other two programs can be included in batch files whenever you need to reboot your system. One possible use would be to remove memory-resident programs. I use it this It's also

41

batch_files_explained.txt

26/02/2002

Campbell -- Batch Power

Page 46

way to remove a memory-resident program or a RAM disk which might interfere with another program. BOOTS is available on GEnie and CompuServe for downloading. FIXBEEP Most users are quickly annoyed with the monotonous beep produced by their computers. If you've ever dreamed about replacing that beep with another sound, FIXBEEP is the answer. Written by Mike Blaszczak, FIXBEEP, allows you to change that sound to anything you want. The program is shareware, but the registration fee is only $5. Use fixbeep in your batch files to change the beep tone. You can alter the tone to signal different operations in your file, signalling the user to take action. For example, to change the normal beep to a short, high-pitched sound, include the following command in any batch file. FIXBEEP /F3000 /D50 This command would produce a tone with a pitch of 3000 hertz, lasting for half a second. FIXBEEP is available on The Source, CompuServe, and GEnie, as well as from the author. Contact Mike "Nifty James" Blaszczak, 112 Verlinden Drive, Monroeville, PA 15146. TOGGLE There are many occasions when you might want to turn the CapsLock or NumLock function on or off from a batch file. The two programs in TOGGLE, CAPLOCK.COM and NUMLOCK.COM, allow you to do just that. I use NUMLOCK.COM in the batch files which call my spreadsheet and accounting programs. It saves me from the mistakes I usually make by forgetting to press the NumLock key. TOGGLE is in the public domain, and is available for downloading on GEnie and Compuserve. E88 If your word processor can't save files in ASCII format, or if you would just like to have a simple, fast text editor

42

batch_files_explained.txt Campbell -- Batch Power Page 47

26/02/2002

for creating and altering batch files, E88 may be just the editor you need. It produces pure ASCII files, and has a text search function, along with block moves and other editing functions you'll find useful for batch programming. E88 is easy to learn, fast, and, for programming purposes, is often better than a full-fledged word processor. The program is shareware, but the author asks only $10 as a registration fee. E88 is available for downloading from GEnie and CompuServe, or you can contact the author at M.R.E. Software, 150 Jones St., West Point, MS 39773 SPECIAL OFFER As a service to the readers of this series on batch files, I'll be happy to send readers a disk containing all the public domain and shareware programs mentioned above. To cover the costs of copying and mailing, send $7.50 for a 5.25" floppy disk or $10 for a 3.5" disk to: George Campbell 1472 Sixth St. Los Osos, CA 93402 Be sure to mention the batch file articles, and specify your disk size. All of these programs contain their own documentation in an ASCII file which you can copy to your printer. If you use these programs regularly, please honor the shareware concept by sending the registration fee to the authors who request it. TIPS FOR EFFECTIVE BATCH PROGRAMMING 1. Plan your batch files before you begin to write them. Make a list of the functions you want to perform, then begin creating the file. Always give batch files easy-to-remember filenames to avoid errors. 2. Include lines which use the ECHO command to print screen messages. Users, yourself included, will benefit from screen messages which explain what's going on during batch file execution. 3. In any batch file which uses replaceable parameters, include an IF line to check whether or not a parameter was given with the command. If not, GOTO a subroutine which explains the correct syntax for the batch file. The CFORMAT.BAT in this article is a good example.

Campbell -- Batch Power

Page 48

4. If you have a hard disk, create a directory called C:\BATCH, and store all your batch files in that directory. 43

batch_files_explained.txt

26/02/2002

If you include the directory in your PATH command, you'll be able to access your batch files while you're in any directory on your hard disk. Here's a sample PATH command: PATH = C:\;C:\DOS;C:\BATCH Thanks to reader Roger Paulson for reminding me of this important tip. 5. You can give the command to execute another batch file in any batch file. To return to the original batch file, just give its filename as the last line of your second file. You can't call the current batch file, however, from within that file. 6. Use the <ALT>+255 technique to create blank lines with the ECHO command, and to eliminate the DOS prompt with the PROMPT command. This works with all versions of DOS, from 2.0 on. Be sure to leave a space between the command and the key combination, and always use the number pad to enter the numbers. Note: You can also insert any extended ASCII character, such as the ASCII graphics characters, using the same technique. Just substitute the correct ASCII code in place of the 255 code for a blank character. You'll find a chart showing these codes in your DOS manual. 7. Don't use the DOS redirection characters (< and >) in ECHO, PROMPT, or PAUSE lines in your batch files. DOS sees them as part of a command and will respond with the "Bad command or filename" error message. Substitute brackets ([]) or curly brackets ({}) instead. 8. When testing new batch files, you'll often encounter error messages. These usually mean you've misspelled a command or left out a space after ECHO, PROMPT, or PAUSE commands. Check for these errors first. 9. Memory-resident programs sometimes conflict with each other. If you encounter unusual problems after adding a memory-resident program's command to an AUTOEXEC.BAT file, try changing the order of the programs. You may have to try several orders to make your memory-resident programs cooperate. 10. Finally, experiment with batch files. Anytime you find yourself typing the same series of DOS commands, consider creating a batch file to automate your computing.

44