Programming4us
         
 
 
Windows

Windows 7 : Understanding Batch File Basics (part 1) - Creating Batch Files

12/6/2010 6:10:51 PM
As you’ve seen so far, the command line is still an often useful and occasionally indispensable part of computing life, and most power users will find themselves doing at least a little work in the Command Prompt window. Part of that work might involve writing short batch file programs to automate routine chores, such as performing simple file backups and deleting unneeded files. And if you throw in any of the commands that enhance batch files, you can do many other interesting and useful things.

When you run a command in a command-line session, the Command Prompt executes the command or program and returns to the prompt to await further orders. If you tell the Command Prompt to execute a batch file, however, things are a little different. The Command Prompt goes into Batch mode, where it takes all its input from the individual lines of a batch file. These lines are just commands that (in most cases) you otherwise have to type in yourself. The Command Prompt repeats the following four-step procedure until it has processed each line in the batch file:

1.
It reads a line from the batch file.

2.
It closes the batch file.

3.
It executes the command.

4.
It reopens the batch file and reads the next line.

The main advantage of Batch mode is that you can lump several commands together in a single batch file and tell the Command Prompt to execute them all simply by typing the name of the batch file. This is great for automating routine tasks such as backing up the Registry files or deleting leftover .tmp files at startup.

Creating Batch Files

Before getting started with some concrete batch file examples, you need to know how to create them. Here are a few things to bear in mind:

  • Batch files are simple text files, so using Notepad (or some other text editor) is probably your best choice.

  • If you decide to use WordPad or another word processor, make sure that the file you create is a text-only file.

  • Save your batch files using the .bat extension.

  • When naming your batch files, don’t use the same name as a Command Prompt command. For example, if you create a batch file that deletes some files, don’t name it Del.bat. If you do, the batch file will never run! Here’s why: When you enter something at the prompt, CMD first checks to see whether the command is an internal command. If it’s not, CMD then checks for (in order) a .com, .exe, .bat, or .cmd file with a matching name. Because all external commands use a .com or .exe extension, CMD never bothers to check whether your batch file even exists!

After you’ve created the batch file, the rest is easy. Just enter any commands exactly as you would at the command line, and include whatever batch instructions you need.

Tip

If you find yourself creating and using a number of batch files, things can get confusing if you have the files scattered all over your hard disk. To remedy this, it makes sense to create a new folder to hold all your batch files. To make this strategy effective, however, you have to tell the Command Prompt to look in the batch file folder to find these files. To do that, you need to add the batch file folder to the PATH variable.


REM: Adding Comments to a Batch File

The first of the batch file–specific commands is REM (which stands for remark). This simple command tells the Command Prompt to ignore everything else on the current line. Batch file mavens use it almost exclusively to add short comments to their files:

REM This batch file changes to drive C
REM folder and starts CHKDSK in automatic mode.
C:
CHKDSK /F

Why would anyone want to do this? Well, it’s probably not all that necessary with short, easy-to-understand batch files, but some of the more complex programs you’ll be seeing later in this chapter can appear incomprehensible at first glance. A few pithy REM statements can help clear things up (not only for other people, but even for you if you haven’t looked at the file in a couple of months).

Caution

It’s best not to go overboard with REM statements. Having too many slows a batch file to a crawl. You really need only a few REM statements at the beginning to outline the purpose of the file and one or two to explain each of your more cryptic commands.


ECHO: Displaying Messages from a Batch File

When it’s processing a batch file, Windows 7 normally lets you know what’s going on by displaying each command before executing it. That’s fine, but it’s often better to include more expansive descriptions, especially if other people will be using your batch files. The ECHO batch file command makes it possible for you to do just that.

For example, here’s a simple batch file that deletes all the text files in the current user’s Cookies and Recent folders and courteously tells the user what’s about to happen:

ECHO This batch file will now delete your Internet Explorer cache files
DEL "%localappdata%\microsoft\windows\temporary internet files\*.*"
ECHO This batch file will now delete your recent documents list
DEL "%appdata%\microsoft\windows\recent items\*.lnk"

The idea here is that when Windows 7 stumbles on the ECHO command, it simply displays the rest of the line onscreen. Sounds pretty simple, right? Well, here’s what the output looks like when you run the batch file:

C:\>ECHO This batch file will now delete your Internet Explorer cache files
This batch file will now delete your Internet Explorer cache files
C:\>DEL "%localappdata%\microsoft\windows\temporary internet files\*.*"
C:\>ECHO This batch file will now delete your recent documents list
This batch file will now delete your recent documents list
C:\>DEL "%appdata%\microsoft\windows\recent items\*.lnk"

What a mess! The problem is that Windows 7 is displaying the command and ECHOing the line. Fortunately, Windows 7 provides two solutions:

  • To prevent Windows 7 from displaying a command as it executes, precede the command with the @ symbol:

    @ECHO This batch file will now delete your Internet Explorer cache files
  • To prevent Windows 7 from displaying any commands, place the following at the beginning of the batch file:

    @ECHO OFF

Here’s what the output looks like with the commands hidden:

This batch file will now delete your Internet Explorer cache files
This batch file will now delete your recent documents list

Tip

You might think that you can display a blank line simply by using ECHO by itself. That would be nice, but it doesn’t work. (Windows 7 just tells you the current state of ECHO: on or off.) Instead, use ECHO. (that’s ECHO followed by a dot).


PAUSE: Temporarily Halting Batch File Execution

Sometimes you want to see something that a batch file displays (such as a folder listing produced by the DIR command) before continuing. Or, you might want to alert users that something important is about to happen so that they can consider the possible ramifications (and bail out if they get cold feet). In both cases, you can use the PAUSE command to halt the execution of a batch file temporarily. When Windows 7 comes across PAUSE in a batch file, it displays the following:

Press any key to continue . . .

To continue processing the rest of the batch file, press any key. If you don’t want to continue, you can cancel processing by pressing Ctrl+C or Ctrl+Break. Windows 7 then asks you to confirm:

Terminate batch job (Y/N)?

Either press Y to return to the prompt or N to continue the batch file.

Other -----------------
- Discovering the Microsoft Azure Platform
- SOA with .NET and Windows Azure : Microsoft Messaging Queue (MSMQ)
- Windows 7 : Working at the Command Line (part 3)
- Windows 7 : Working at the Command Line (part 2)
- Windows 7 : Working at the Command Line (part 1)
- Windows 7 : Getting to the Command Line (part 2) - Running CMD
- Windows 7 : Getting to the Command Line (part 1)
- Windows Azure : Programming Access Control Service (part 10) - Deploying the Web Service in Windows Azure
- Windows Azure : Programming Access Control Service (part 9) - Configuring a Web Service Client to Acquire and Send SAML Tokens
- Windows Azure : Programming Access Control Service (part 8)
- Windows Azure : Programming Access Control Service (part 7) - Integrating ACS with a SAML Token Provider
- Windows Azure : Programming Access Control Service (part 6)
- Windows Azure : Programming Access Control Service (part 5)
- Windows Azure : Programming Access Control Service (part 4)
- Windows Azure : Programming Access Control Service (part 3)
- Windows Azure : Programming Access Control Service (part 2)
- Windows Azure : Programming Access Control Service (part 1)
- Windows 7 : Working with Registry Entries (part 3)
- Windows 7 : Working with Registry Entries (part 2)
- Windows 7 : Working with Registry Entries (part 1) - Changing the Value of a Registry Entry
 
 
Most View
- System Center Configuration Manager 2007 : Hierarchy Planning
- DirectX 10 Game Programming : The 2D Resurgence - Textures
- Windows Phone 7 Game Development : The World of 3D Graphics - The Depth Buffer
- Performing Administrative Tasks Using Central Administration (part 14)
- Windows Server 2008: Using the Task Manager for Logging and Debugging (part 2)
- Windows 7: Troubleshooting Tools (part 2) - Running the Memory Diagnostics Tool
- Overview of Process Management in Microsoft Visio 2010 (part 2) - New process flow templates
- iPad SDK : Working with Documents - Desktop Synchronization
- iPad SDK : New Input Methods - Gesture Recognition
- Coding JavaScript for Mobile Browsers (part 1) - Code Execution
Top 10
- Implementing Edge Services for an Exchange Server 2007 Environment : Utilizing the Basic Sender and Recipient Connection Filters (part 3) - Configuring Recipient Filtering
- Implementing Edge Services for an Exchange Server 2007 Environment : Utilizing the Basic Sender and Recipient Connection Filters (part 2)
- Implementing Edge Services for an Exchange Server 2007 Environment : Utilizing the Basic Sender and Recipient Connection Filters (part 1)
- Implementing Edge Services for an Exchange Server 2007 Environment : Installing and Configuring the Edge Transport Server Components
- What's New in SharePoint 2013 (part 7) - BCS
- What's New in SharePoint 2013 (part 6) - SEARCH
- What's New in SharePoint 2013 (part 6) - WEB CONTENT MANAGEMENT
- What's New in SharePoint 2013 (part 5) - ENTERPRISE CONTENT MANAGEMENT
- What's New in SharePoint 2013 (part 4) - WORKFLOWS
- What's New in SharePoint 2013 (part 3) - REMOTE EVENTS