A batch file is a text file that stores commands that are executed by the Command Interpreter. It is generally used to simplify the execution of many commands for a given task. When the batch file is run (by double clicking on this file within Windows Explorer), a shell program (command.com or cmd.exe) reads the file and executes the commands one line at a time. Batch files generally have the extension of.BAT (all versions of Windows) or.CMD (Windows NT).
When would you use a batch file? Whenever you have a need to open several programs for a given task. For example, when it comes time to pay the monthly bills you generally would open a browser to access online banking, open a spreadsheet to track payments, and the Calc program for calculations. A single batch file can easily open all three with a single click. Within it, you would create the following commands:
NOTE: The following examples and file paths are from Windows 7. XP paths may be different for some programs as well as for MS Office (Office 2007 is used in the example below) on your Computer.
Also, due to some sites not allowing the use of back slashes, the examples below use forward slash for folder paths. When creating your batch files, use a back slash in the folder path.
- start /d C:/Windows/System32 calc.exe
- start /d “C:/Program Files/Mozilla Firefox” firefox.exe
- start /d C:/finance/spreadsheets budget.xls
When creating a batch file, use the Notepad program (or any other text editor) and save it with a.BAT extension (not the default.TXT extension).
Let’s quickly review each command listed above. First, the Start command instructs Windows to open a separate window within which the program executes.
Second, the /d is called a Switch and instructs the Windows to read the following information as a file or command path for locating the program. If there are spaces in the path, the complete path will need to be placed in double quotes.
Third, the name of the file to be executed is added, including its extension.
And fourth, if there is a file or URL to be opened, then this is where it is placed. For example, the budget spreadsheet budget.xls.
The above is a simple example. Batch files can handle more complex tasks. Below is an example of a complex batch file…
- @echo off
- color 3
- title Conditional Shutdown
- set /p name=enter a name:
- echo Hi, %name%
- echo 1.Shutdown
- echo 2.Quit
- set /p choice=enter your choice 1,2:
- if %choice%==1 goto shutdown
- if %choice%==2 exit
- set /p sec=enter the number of seconds that you wish the computer to shutdown in:
- set /p msg=enter the shutdown message you wish to display:
- shutdown -s -f -t %sec% -c “%msg%”
- echo shutdown initiated at %time%
- set /p cancel=type cancel to stop shutdown
- if %cancel%==cancel shutdown -a
- if %cancel%==cancel goto start