Saturday, October 22, 2016

Batch files

Chapter 13 - Batch files

 

As you have probably realized by now, while using the Command Prompt is in many circumstances more efficient than using the GUI, it nonetheless involves a great deal of repetitive typing. However, there are way to automate commands, and the easiest way to automate commands from the Command Prompt is to use a batch file. With a batch file, you can launch a dozen commands (or more) in sequence simply by typing the name of a single file from the command line.

In this chapter we'll discuss how to use a simple batch file. 

 

WHAT IS A BATCH FILE?

 

To put it simply, a batch file is a text file containing a sequence of commands, one in each line. When you launch the batch file from the command line, Command Prompt reads the file, executing each of the commands in sequence. (That means Command Prompt first executes the command on the first line, then the second, then the third, and so on until it reaches the end of the file.) 

Using a batch file, you can automate tedious jobs, or tasks that require typing several command in sequence. For instance, let's say you have a daily task on your Windows computer that requires you to enter twelve commands in sequence to complete it. You could type out each command one by one, with the attending risk of making a typing error. Or you could put the commands into a batch file named JOB.BAT, and run it from the command line. Command Prompt will execute each of the commands in sequence, and you needn't worry about any typographical errors. 

 

CREATING BATCH FILES

 

How do you create a batch file?

Any text editor (an application that saves files as plain text files) will work to create batch files. The most popular application for creating batch files is the Microsoft Notepad utility included with Windows. Notepad has been included with every version of Windows since version 1.0 was released in 1985. (Which, I suspect, makes Notepad older than many of the readers of this book!) Notepad is very bare bones, but it will make a clean text file for you to use as a batch file. You'll need to make sure you save it as a BAT file instead of a TXT file - go to the File menu, and then to Save As, change the "Save As Type" to "All Files", and type the file name with a BAT extension.

It's a bad idea to use a full-featured word processor like Microsoft Office Word or LibreOffice Writer to create your batch file. The standard save formats of full-featured word processors are obviously not text files, and even when saving a Word document as a TXT file, it tends to be formatted incorrectly. If you want a more full-featured text editor, there are several free programs available - Notepad++ is one of the more popular ones.

Unfortunately, Windows does not include a text editor you can use from the Command Prompt. It's possible to create text files from the Command Prompt by using the ECHO command and output redirection, but even then, there's no way to edit the file once it has been created. This is one area where Mac OS X and numerous Linux distributions have the advantage over the Windows Command Prompt, since they include the vi text editor, which lets you edit text files from the command line (assuming you master vi's syntax and commands, of course). 

 

BATCH COMMANDS

 

You can put practically any command in a batch file. There are, however, a set of ten commands that are particularly useful for adding functionality to batch files (and some of them only work properly when used in a batch file). Using them, you can create limited programs that accept user input, complete with assigned variables. These will be simple programs - to create really complex effects, you'd need to learn WMI (Windows Management Instrumentation) syntax or a programming language like C# or Visual Basic. Nevertheless, you can use these commands to create useful batch files. 

The ten batch file commands are ECHO, CALL, FOR, PAUSE, CHOICE, GOTO, REM, IF, SHIFT, SET. Some of them are beyond the scope of this book, but we'll take a look at the simpler ones in this chapter. 

 

ECHO

 

The ECHO command does just what its name indicates - it "echoes" back a line of text. Entered from the command line, the command will "echo" back whatever text follows the command. For instance, this command would generate an output of "HELLO!"

ECHO HELLO!

The ECHO command has two uses in creating batch files. First, you can use it to display directions on the screen, or an explanation of what the batch file is doing. Second, you can use it to generate cleaner output from your batch files. By default, the batch file displays every command on the screen, along with its output. However, prefixing any command with a @ symbol prevents it from appearing on the screen. And if you use the @ symbol with the ECHO OFF command, it makes the prompt disappear for the duration of the batch file:

@ECHO OFF

This is useful if you don't want your batch file to clutter up the screen while it runs. 

 

PAUSE

 

The PAUSE command does exactly what its name says. It pauses processing of the batch file until you press a key to continue. Issuing the PAUSE command from the Command Prompt generates this output:

Press any key to continue...

The Command Prompt will wait until you press a key to return control to the prompt. When inserted into a batch file, PAUSE stops the execution of the file, which is useful when you want to view some output before it scrolls off the top of the screen. 

 

REM

 

The REM command doesn't actually do anything.

Despite that, it is quite useful. REM stands for "remark", and when used in a batch file, the Command Prompt will ignore any text that comes after it. This is handy for inserting "remarks", or notes, into your batch file. Why would you want to do that? The REM command allows you to document your batch files. If you write a batch file and need to edit it a year later (because, say, some server names or IP addresses changed) you might look at some of the commands and wonder why you put them in there. REM lets you make notes as you write the batch file, so you can examine them later and remember why you put the file together the way that you did. 

The second use of the REM command is for testing. Using REM, you can "comment out" a command by prefixing REM before it. The Command Prompt will then treat the command as a remark and ignore it. This comes in handy when you are testing a batch file that does not work properly, allowing you to pin down which part of it isn't working as you thought. 

 

GOTO

 

The GOTO command tells the Command Prompt to jump to a new location in the batch file. If you programmed old BASIC or Microsoft QBASIC programs, you might remember using GOTO statements with the numbered lines of code. GOTO in the modern Command Prompt works a bit different. GOTO jumps to a text line designated by a colon character (:) and resumes processing the commands in order. For instance, consider a GOTO command that looks like this in your batch file:

GOTO :SELECT

If you have a command like this, GOTO will jump to the line in the batch file beginning with :SELECT.

 

CHOICE

 

The CHOICE command does exactly what its name implies - it presents you with a choice. Typing the CHOICE command at the prompt generates an output that looks like this: 

[Y, N]?

This looks rather similar to other Yes or No choices offered by other Command Prompt commands. By itself, CHOICE does nothing. You need to use it in conjunction with other commands (particularly the SET command) in order to make it useful. However, you can alter the appearance of the CHOICE command with a few convenient command switches. The /M switch lets you add a custom message to the CHOICE command (with the message itself in quotation marks). This command is generates a message of "Hello! Press Y or N":

CHOICE /M "Hello! Press Y or N"

If you want to have different options than to press Y or N, you can modify the options with the /C switch. This command prompts the user to press 1, 2, or 3, rather than Y or N:

CHOICE /C 123

You can also use the CHOICE command with a default option, and set it to choose that default option after a timeout measured in seconds. This version of the CHOICE command sets the default option to Y, after waiting 90 seconds for user input:

CHOICE /D Y /T 90

Using these switches, you can customize the choice offered by CHOICE to fit your needs. 

 

SET

 

The SET command is a powerful tool that ties together the GOTO and CHOICE commands, allowing you to offer real choices in your batch files. By itself, the SET command primarily works with "environment variables." Environment variables are a number of system variables with preset values that control the way both the Command Prompt and Windows itself work. To see the environment variables for your system, use the SET command from the prompt without any switches:

SET

This generates quite a long list of output - Windows uses numerous environment variables. To quickly find the value for any one variable, you can use the ECHO command. However, you need to use the ECHO command with special characters. The TIME variable displays the system time, so you might be tempted to use this command:

ECHO TIME

However, this will only display the word "TIME" on the screen. To use ECHO to display system variables, you'll need to enclose the variable within a pair of percentage characters (%), like this:

ECHO %TIME%

This time, rather than just spitting out "TIME", the output will look like this:

22:13:30.56

You can also use the SET variable to create your own environment variables. To create a variable entitled "TODAY" with a value of "Wednesday", use this command:

SET TODAY=Wednesday

Then if you use that variable with ECHO, it will return with a value of "Wednesday":

ECHO %TODAY%

Assign your own variables might seem like a pointless game, but it becomes useful when working with your own batch files. Using the SET command, you can create a batch file that will execute instructions based on the user's choices. With the /P switch, you can instruct SET to create a new variable based upon the user's input - in effect, the /P switch combines CHOICE and SET into a single command. Let's say you wanted to create a variable named INPUT, and offer the user a choice between Option 1 and Option 2. The SET command to create such a choice would look something like this:

SET /P INPUT="Press 1 for Option 1, and Press 2 for Option 2: 1,2: "

Combined with the GOTO and the IF commands, this lets you create batch files that offer choices. (Note that the message text has to be in quotation marks, and the actual option keys themselves need to be enclosed in colon characters, as shown in the example.)

 

IF

 

The IF command ties together batch processing. The IF command responds to the variable created by the SET command. For every potential value of the previously created variable, you can then tell the IF command to perform a specific task. Generally, the best use of the IF command is to issue the GOTO command, which will then route Command Prompt to the section of the batch file containing the necessary commands. 

This example shows the best use of the commands we've explored in this chapter. This batch file offers the user a choice between pressing "C" for a listing of the root directory of the C drive and "D" for a listing of the root directory of the D drive. Depending upon which choice the user takes, he is moved to a different portion of the batch file, which then executes the necessary commands:

@echo off

set /p input="Press C for C:\, and press D for D: C,D: "

if %input%==1 goto C

if %input%==2 goto D

:C

dir C:\

goto end

:D

dir D:\

goto end

:end

By following this example, you can create your own batch files using variables and choices.

No comments:

Post a Comment