Jump to content

Batch file

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by 1230049-0012394-C (talk | contribs) at 19:00, 21 February 2011 (Undid revision 414205657 by 59.99.211.107 (talk)). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Batch file
Filename extension
.bat .cmd .btm
Internet media typeapplication/x-bat
Type of formatScripting
Container forShell scripts

In DOS, OS/2, and Microsoft Windows, a batch file is a text file containing a series of commands intended to be executed by the command interpreter. Similar to job control language and other systems on mainframe and minicomputer systems, batch files were added to ease the work required for certain regular tasks by allowing the user to set up a batch script to automate many commands. When a batch file is run, the shell program (usually COMMAND.COM or cmd.exe) reads the file and executes its commands, normally line-by-line. Batch files are useful for running a sequence of executables automatically and are often used to automate repetitive or tedious processes.[1] Unix-like operating systems (such as Linux) have a similar type of file called a shell script.[2]

DOS batch files have the filename extension .bat. Batch files for other environments may have different extensions, e.g. .cmd or .bat in the Microsoft Windows NT-family of operating systems and OS/2, or .btm in 4DOS and 4NT related shells. The Windows 9x family of operating systems only recognize the .bat extension. In OS/2 a file with a .cmd extension can also be a Rexx file.

Variants

In MS-DOS, a batch file can be started from the command line by typing its name (along with any required parameters) and pressing the "enter" key. When MS-DOS loads, the file AUTOEXEC.BAT is automatically executed, so any commands that need to be run to set up the MS-DOS environment for use could be placed in this file. Computer users would have the autoexec file set up the system date and time, initialize the MS-DOS environment, load any resident programs or device drivers, or initialize network connections and assignments.

DOS

In MS-DOS, the extension ".bat" signified a file which could be executed by the command interpretor COMMAND.COM, by running line by line as if it was a list of commands to be entered, with some extra batch file specific commands for basic programming functionality, including a GOTO command for changing flow of line execution.

Early Windows

Microsoft Windows was introduced in 1985 as a GUI Operating System alternative to text-based operating and was designed to run on MS-DOS. In order to start it the WIN command was used and could be added to the end of the AUTOEXEC.BAT file to allow automatic loading of Windows. In the earlier versions one could run a .bat type file from Windows in the MS-DOS Prompt.

Windows was run from MS-DOS and used COMMAND.COM to run .bat files on the following operating systems:

OS/2

The IBM OS/2 operating system supported DOS-style batch files. It also included a version of REXX, which was a more advanced batch file scripting language. IBM and Microsoft started developing this system but during the construction of it broke up after a dispute, as a result of this IBM referred to their MS-DOS like console shell without mention of Microsoft; naming it just DOS, although this seemingly made no difference on the way batch files worked from COMMAND.COM.

OS/2's batch file interpreter also supports an EXTPROC command. This passes the batch file to the program named on the EXTPROC file as a data file. The named program can be a script file; this is similar to the #! mechanism.

Windows NT

Windows versions other than the NT line of operating systems were run from MS-DOS and used the same command interpreter, COMMAND.COM, to execute batch files. However, the operating systems in the Windows NT series run directly from booting the hard drive and aren't based on MS-DOS. In order to replace COMMAND.COM, cmd.exe was introduced which allowed execution of .cmd files as well as .bat files in the same way, and used slightly different commands than COMMAND.COM, meaning that the new cmd.exe was not backwards compatible with older batch files for use with COMMAND.COM.

Microsoft released a version of cmd.exe for Windows 9x and ME called WIN95CMD to allow users of older versions of Windows to use certain cmd.exe-style batch files.

Currently, cmd.exe is the command interpreter for batch files on the latest version of Windows.

Filename extensions

  • .bat: The first extension used by Microsoft for batch files. This extension runs with MS-DOS and all versions of Windows, under COMMAND.COM or cmd.exe, despite the different ways the two command interpreters execute batch files.
  • .cmd: The extension used by operating systems in the Windows NT family and sent to cmd.exe for interpretation. It does not work on computers relying on COMMAND.COM so prevents cmd.exe scripts from being executed in the wrong Windows environment. It is also used by IBM's OS/2 for batch files.
  • .btm: The extension used by 4DOS and 4NT. The scripts run on 4DOS and 4NT are faster, especially with longer ones, as the script is loaded entirely ready for execution, rather than line-by-line.[3]

Differences between .cmd and .bat execution in the Windows NT family

The only known difference between .cmd and .bat file execution is that in a .cmd file the ERRORLEVEL variable changes even on a successful command that is affected by Command Extensions (when Command Extensions are enabled), whereas in .bat files the ERRORLEVEL variable changes only upon errors.[4]

Example

This example batch file is a simple program that displays a hello world program and then waits for the user to press a key before ending.

@ECHO off
ECHO Hello World!
PAUSE
ECHO on

To execute the file it must be saved with a .bat or .cmd extension in plain text format (with a program like Notepad).

Result

When executed (either from Windows Explorer or Command Prompt) this is displayed:

Hello World!
Press any key to continue . . .

Explanation

The interpreter executes each line in turn, starting with the first. The @ symbol at the start of the line turns off the prompt from displaying for that command. The command ECHO off turns off the prompt permanently, or until it is turned on again. Then the next line is executed, the ECHO Hello World! command outputs Hello World!, as only off and on have special functions. Then the next line is executed, the PAUSE command literally 'pauses' the script's execution, and displays the output Press any key to continue . . . . After a key is pressed, the script continues onto the next line, ECHO on, which turns the prompt back on for use. Then the end of the script is reached so execution stops. If the script started from the Command Prompt, then it will remain open at the prompt. If the script started from Windows Explorer, then upon finishing the window will close.

Advanced batch example - conditional shutdown

@echo off
color 3
title Conditional Shutdown
set /p name=enter a name:
:start 
cls
echo Hi, %name%
echo. 
echo 1.Shutdown
echo 2.Quit
set /p choice=enter your choice 1,2: 
if %choice%==1 goto shutdown
if %choice%==2 exit
 
:shutdown
cls
set /p sec=enter the number of seconds that you wish the computer to shutdown in: 
set /p message=enter the shutdown message you wish to display: 
shutdown -s -f -t %sec% -c "%message%"
echo shutdown initiated at %time%
set /p cancel=type cancel to stop shutdown 
if %cancel%==cancel shutdown -a
if %cancel%==cancel goto start

Limitations / Exceptions

Null values in variables

Some commands can fail syntactically and terminate the script, if the variables in the command contain a null value. For example this test will work properly only if the value of %foo% is 1 character or greater:

IF %foo%==bar ECHO Correct.

But if the value of %foo% is null, the command will evaluate as an invalid command:

IF ==bar ECHO Correct.


The typical way to deal with this is to always enclose the tested variables in quotes, or include some other unchanging character on both sides of the evaluation. For example, these tests are syntactically correct and evaluate as False if %foo% contains a null value:

IF "%foo%"=="bar" ECHO Correct.
IF 1%foo%==1bar ECHO Correct.

A null value in %foo% results in the commands being parsed as:

IF ""=="bar" ECHO Correct.
IF 1==1bar ECHO Correct.

Quotes and spaces in passed strings

  • For some commands, spaces are treated as delimiters in commands, unless those spaces are enclosed by quotes. A one-character quote (") is not included as part of the string. However, an escaped quote (""") can be part of the string.
  • For other commands, spaces are not treated as delimiters and don't need quotes. If quotes are included they become part of the string.

This can cause conflicts where a string contains quotes, and is to be inserted into another line of text that must also be enclosed in quotes:

C:\> Set foo="this string is enclosed in quotes"

C:\> Echo "test 1 %foo%"
"test 1 "this string is enclosed in quotes""

C:\> Eventcreate /T Warning /ID 1 /L System /SO "Source" /D "Example: %foo%"
ERROR: Invalid Argument/Option - 'string'.
Type "EVENTCREATE /?" for usage.

Under Windows 2000/XP/Vista/7, the solution is to do a search and replace on the one character quote and replace it with three quotes:

C:\> Set foo="this string is enclosed in quotes"

C:\> Set foo=%foo:"="""%

C:\> Echo "test 1 %foo%"
"test 1 """this string is enclosed in quotes""""

C:\> Eventcreate /T Warning /ID 1 /L System /SO "Source" /D "Example: %foo%"
SUCCESS: A 'Warning' type event is created in the 'Source' log/source.

Escaped characters in strings

Some characters have special meaning to the command line, such as the pipe | character. These can not be printed as text using the ECHO command unless it is escaped using the caret ^ symbol:

C:\> Echo foo | bar
'bar' is not recognized as an internal or external command,
operable program or batch file.

C:\> Echo foo ^| bar
foo | bar

However, escaping does not work as expected when inserting the escaped character into an environment variable, and the variable ends up containing a live pipe command when merely echoed. It is necessary to escape both the caret itself and the escaped character for the character display as text in the variable:

C:\> set foo=bar | baz
'baz' is not recognized as an internal or external command,
operable program or batch file.

C:\> set foo=bar ^| baz
C:\> echo %foo%
'baz' is not recognized as an internal or external command,
operable program or batch file.

C:\> set foo=bar ^^^| baz
C:\> echo %foo%
bar | baz

Sleep / Scripted Delay

The PAUSE command halts script activity indefinitely. For something like "Wait 30 seconds or until a key is pressed" the CHOICE command can be used, with a timeout on the choice selection, like it was possible in MS-DOS already. Alternatively in Windows Vista/7 there is also TIMEOUT which is exactly for this purpose.

A fixed timed delay is also not possible using only batch file commands, but a hack is for the computer to ping itself and pipe the results to NUL (the null device), which results in a delay of 1 second per ping. This only works when TCP/IP and associated commands are installed by default (Windows 2000/XP/Vista/7):

REM Wait 12 seconds..
ping -n 13 127.0.0.1 > nul

This necessarily needs to specify one ping more than seconds to wait, since there is a one-second delay between pings, so this always waits a second less than pings are performed.

Again, TIMEOUT is a better option on Windows Vista/7.

Text output with stripped CR/LF

Normally all printed text automatically has the control characters for "carriage return" and "line feed" appended to the end of each line.

batchtest.bat:
@echo foo
@echo bar

C:\>batchtest.bat
foo
bar

It does not matter if the two echo commands share the same command line; the CR/LF codes are inserted to break the output onto separate lines:

C:\> @echo foo&@echo bar
foo
bar

A trick discovered with Windows 2000/XP/Vista/7 is to use the special prompt for input to output text without CR/LF trailing the text. In this example, the CR/LF does not follow Line 1, but does follow Line 2 and Line 3:

batchtest.bat:
@echo off
set foo=Line 1
echo y | set /p tmp="%foo%"
echo Line 2
echo Line 3

C:\>batchtest.bat
Line 1Line 2
Line 3

C:\>

This can be used to output data to a text file without CR/LF appended to the end:

C:\> echo y | set /p tmp="Line 1"> data.txt
C:\> echo y | set /p tmp="Line 2">> data.txt
C:\> echo y | set /p tmp="Line 3">> data.txt
C:\> type data.txt
Line 1Line 2Line 3

However, there is no way to inject this stripped CR/LF prompt output directly into an environment variable.

Setting a UNC working directory from a shortcut

It is not possible to have a command prompt that uses a UNC file path as the current working directory, like this:

\\server\share\directory\>

The command prompt requires the use of drive letters to assign a working directory, which makes running complex batch files stored on a server UNC share more difficult. While a batch file can be run from a UNC file path, the working directory will default to "C:\windows\system32\"

In Windows 2000/XP/Vista/7, a workaround is to use the PUSHD and POPD command with command extensions. Quoting the help for PUSHD in Windows 7, If Command Extensions are enabled the PUSHD command accepts network paths in addition to the normal drive letter and path. If a network path is specified, PUSHD will create a temporary drive letter that points to that specified network resource and then change the current drive and directory, using the newly defined drive letter. Temporary drive letters are allocated from Z: on down, using the first unused drive letter found.

If not enabled by default, command extensions can be temporarily enabled using the "/E:ON" switch for the command interpreter.

So to run a batch file on a UNC share, assign a temporary drive letter to the UNC share, and use the UNC share as the working directory of the batch file, a Windows shortcut can be constructed that looks like this:

Target: %COMSPEC% /E:ON /C "PUSHD """\\SERVER\SHARE\DIR1\DIR2\""" & BATCHFILE.BAT & POPD"

The working directory attribute of this shortcut is ignored.

Future

Microsoft has not officially released information pertaining to the future of Command Prompt (host for .bat and .cmd files) yet, but the company is now starting to include Windows PowerShell in releases for newer operating systems, which has all the core functions of Command Prompt and more (and instead of .bat and .cmd files, it runs .ps1 files). Yet it is important to remember that it is not certain this will replace Command Prompt, and that Microsoft is still making important tools for Command Prompt specifically, instead of for PowerShell (such as servermanagercmd.exe, which incorporates the entire set of Server Manager functions for Windows Server 2008).[5]

Other Windows scripting-languages

In addition to traditional batch files, the need for more powerful capabilities has led to the development of other Windows-specific scripting languages:

  • .kix: KiXtart was developed by a Microsoft employee in 1991, specifically to meet the need for commands useful in a network logon script while retaining the simple 'feel' of the traditional batch file.
  • .vbs and .js: Released in 1998, Windows Script Host (consisting of cscript.exe and wscript.exe) runs scripts written in VBScript or JScript. It can run them in windowed mode (with the wscript.exe host) or in console-based mode (with the cscript.exe host). They have been a part of Windows since Windows 98.
  • .ps1: In 2006, Microsoft released a further raw-text script processor, Windows PowerShell, which can operate with Windows XP (SP2/SP3) and above. PowerShell can operate both interactively (from a command-line interface) and also via saved scripts, and has a strong resemblance to Unix shells.[6]

In addition to these, as of 2010 cross-platform scripting tools such as Perl, Python, Ruby and Rexx can run under Windows.

If the appropriate extension is set in the PATHEXT environment, the file will run without need of typing in the extension.

See also

References