Batch (MS-DOS)

In DOS, OS/2, and also Microsoft Windows, batch file is the name given to a type of script file, a text file containing a series of commands to be executed by the command interpreter.

The commands may be built into the command processor (COPY), supplied with the operating system but not built into it (XCOPY invokes the Microsoft DOS program XCOPY.EXE), or may be any program (cp invokes the program cp.exe if present, an .EXE port of the Unix cp command, with essentially the same functionality as XCOPY.EXE).

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 script to automate them. 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. Unix-like operating systems (such as Linux) have a similar type of file called a shell script.

The filename extension .bat was used in DOS, and the Windows 9x family of operating systems. The Microsoft Windows NT-family of operating systems and OS/2 added .cmd. Batch files for other environments may have different extensions, e.g. .btm in 4DOS and 4NT related shells.

There have been changes to the detailed handling of batch files; some of the detail in this article is applicable to all batch files, while other details apply only to certain versions.

Contents

  • 1 Variants
    • 1.1 DOS
    • 1.2 Early Windows
    • 1.3 OS/2
    • 1.4 Windows NT
  • 2 Filename extensions
    • 2.1 Differences between .cmd and .bat execution in the Windows NT family
  • 3 Example
    • 3.1 Result
    • 3.2 Explanation
    • 3.3 Advanced Windows batch example – conditional shutdown
  • 4 Limitations and exceptions
    • 4.1 Null values in variables
    • 4.2 Quotation marks and spaces in passed strings
    • 4.3 Escaped characters in strings
    • 4.4 Sleep or scripted delay
    • 4.5 Text output with stripped CR/LF
    • 4.6 Setting a UNC working directory from a shortcut
    • 4.7 Character set
  • 5 Other Windows scripting languages
  • 6 See also
  • 7 References
  • 8 External links

Variants

Brief information on the function and parameters of commands are usually displayed by typing the command at the command prompt followed by “/?” and pressing the Enter key. In some cases “-?”, “?”, or just the command name without parameters (if parameters are required) will also elicit information. Some commands ported from Unix require “–help”.

DOS

In MS-DOS, a batch file can be started from the command line by typing its name followed by 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.

In MS-DOS, the extension “.BAT” identified a file containing commands which could be executed by the command interpreter COMMAND.COM 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:

  • Windows 1, 2 and 3.
  • Windows 95 and 98.
  • Windows ME (access to real mode MS-DOS was restricted).

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; they are true operating systems, not graphical user interfaces for underlying MS-DOS. An enhanced 32-bit command processor, cmd.exe, was introduced; it could execute scripts with either the .CMD or .BAT extension. Cmd.exe added additional commands, and implemented existing ones in a slightly different way, so that the same batch file (with different extension) might work differently with cmd.exe and COMMAND.COM. In most cases operation is identical if the few unsupported commands are not used. Cmd.exe’s extensions to COMMAND.COM can be disabled for compatibility.

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.

As of Windows 8, cmd.exe is the normal command interpreter for batch files; the older COMMAND.COM can be run from within a cmd.exe window in 32-bit versions of Windows able to run 16-bit programs.

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 that 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.

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.

Example

This example batch file displays “Hello World!”, prompts and waits for the user to press a key, and terminates.

@ECHO off
ECHO Hello World!
PAUSE

To execute the file it must be saved with the extension .bat (or .cmd for Windows-NT type operating systems) in plain text format, typically created by using a text editor such as Notepad or a word processor in text mode.

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 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 displays Press any key to continue . . . and pauses the script’s execution until a key is pressed, when the script terminates as there are no more commands. In Windows, if the script is run within a Command Prompt window, the window remains open at the prompt as in MS-DOS, otherwise the command prompt windows closes on termination (unless the batch file has a command to prevent this).

Advanced Windows batch example – conditional shutdown

@echo off
color 0A
title Conditional Shutdown.

:start
echo Welcome, %USERNAME%
echo What would you like to do?
echo.
echo 1. Shutdown in specified time
echo 2. Shutdown at a specified time
echo 3. Shutdown now
echo 4. Restart now
echo 5. Log off now
echo 6. Hibernate now
echo. 
echo 0. Quit
echo.

set /p choice="Enter your choice: "
if "%choice%"=="1" goto shutdown
if "%choice%"=="2" goto shutdown-clock
if "%choice%"=="3" shutdown.exe -s -f
if "%choice%"=="4" shutdown.exe -r -f
if "%choice%"=="5" shutdown.exe -l -f
if "%choice%"=="6" shutdown.exe -h -f
if "%choice%"=="0" exit
echo Invalid choice: %choice%
echo.
pause
cls
goto start

:shutdown
cls
set /p sec="Minutes until shutdown: "
set /a min=60*%sec%
shutdown.exe -s -f -t %min%
echo Shutdown initiated at %time%
echo.
goto cancel

:shutdown-clock
echo.
echo the time format is HH:MM:SS (24 hour time)
echo example: 14:30:00 for 2:30 PM
echo.
set /p tmg=enter the time that you wish the computer to shutdown on: 
schtasks.exe /create /sc ONCE /tn shutdown /st %tmg% /tr "shutdown.exe -s -t 00"
echo shutdown initiated at %tmg%
echo.

:cancel
set /p cancel="Type cancel to stop shutdown: "
if not "%cancel%"=="cancel" exit
shutdown.exe -a
cls
schtasks.exe /end /tn shutdown
cls
schtasks.exe /delete /tn shutdown
cls
echo Shutdown is cancelled.
echo.
pause
exit

When doing conditions with IF command, batch commands can use:

  EQU : Equal (=)
  NEQ : Not equal (≠)

  LSS : Less than (<)
  LEQ : Less than or Equal (≤)

  GTR : Greater than (>)
  GEQ : Greater than or Equal (≥)

Limitations and exceptions

Null values in variables

Variable expansions are substituted textually into the command, and thus variables which contain nothing simply disappear from the syntax, and variables which contain spaces turn into multiple tokens. This leads to syntax errors or bugs.

For example:

IF %foo%==bar ECHO Equal

if %foo% is empty, parses as the erroneous construct:

IF ==bar ECHO Equal

and if %foo% contains “abc def”, then the syntax is also wrong:

IF abc def==bar ECHO Equal

The usual way to prevent this problem is to surround variable expansions in quotes so that an empty variable expands into the valid expression IF ""=="bar" instead of the invalid IF ==bar. The text that is being compared to the variable must also be enclosed in quotes, because the quotes are not special delimiting syntax; these characters represent themselves.

IF "%foo%"=="bar" ECHO Equal

The delayed !VARIABLE! expansion available in Windows 2000/XP/Vista/7 may be used to avoid these syntactical errors. In this case, null or multi-word variables will not fail syntactically because the value will be expanded after the IF command is parsed:

IF !foo!==bar ECHO Equal

Quotation marks and spaces in passed strings

  • For some commands, spaces are treated as delimiters in commands, unless those spaces are enclosed by quotation marks. A single quotation mark (“) is not included as part of the string. However, an escaped quotation mark (“””) can be part of the string.
  • For other commands, spaces are not treated as delimiters and do not need quotation marks. If quotes are included they become part of the string.

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

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

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

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 replace all occurrences of one quote characters by 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 cannot be printed as text using the ECHO command unless 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

The delayed !VARIABLE! expansion available in Windows 2000/XP/Vista/7 may be used to show special characters stored in environment variables because the variable value will be expanded after the command was parsed:

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

Sleep or scripted delay

The PAUSE command halts script activity indefinitely until a key is pressed; small programs and workarounds were written to implement a timed pause. Many workarounds using scripting commands only worked in some environments, depending upon the CHOICE function not available in older command interpreters, PING only available if TCP/IP was installed, and so on. Simple small programs were readily available; a typical example is the 94-byte WAIT.COMexecutable; WAIT 5 would wait for 5 seconds, then return control to the script. Most such programs are 16-bit .COM files incompatible with 64-bit Windows, but are not needed since Windows Vista and later introduced the TIMEOUT command.

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.

The following syntax does correctly expand to the path of the current batch script.

 %~dp0

Character set

Batch files use a DOS character set, as defined by the computer, e.g. Code page 437. The non-ASCII parts of these are incompatible with the Unicode or Windows character sets otherwise used in Windows so care needs to be taken. Non-English file names work only if entered through a DOS character set compatible editor. File names with characters outside this set won’t work in batch files.

To get output in Unicode into file pipes from an internal command such as dir, one can use the cmd /U command. For example cmd /U /C dir > files.txt will create a file containing a directory listing with correct Windows characters, in the UTF-16LE encoding.

Other Windows scripting languages

The cmd.exe command processor that interprets .cmd files is supported in all 32- and 64-bit versions of Windows up to at least the 2011 Windows 8 preview. COMMAND.EXE, which interprets .BAT files, was supported in all 16- and 32-bit versions up to at least Windows 8 preview.

While the more powerful 2006 Windows PowerShell is favored in later versions of Windows that support it, Microsoft was also using .cmd files as far as, at least, Window Server 2008. An example is servermanagercmd.exe which incorporates the entire set of Server Manager functions for Windows Server 2008.

There are other, later and more powerful, scripting languages produced by Microsoft for Windows:

  • KiXtart (.kix) – 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 a .cmd file.
  • Windows Script Host (.vbs and .js) – released in 1998, (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.
  • Windows PowerShell (.ps1) – released in 2006 by Microsoft and can operate with Windows XP (SP2/SP3) and later versions. PowerShell can operate both interactively (from a command-line interface) and also via saved scripts, and has a strong resemblance to Unix shells.[11]

Cross-platform scripting tools including Perl, Python, Ruby and Rexx are available for Windows.

Script files will run if the filename without extension is entered. There are rules of precedence governing interpretation of, say DoThis if several of DoThis.cmd, DoThis.bat, DoThis.exe, etc. exist; by default DoThis.com has highest priority. This default order may be modified in newer operating systems by the user-settable PATHEXT environment variable.

Komentar
  1. Delsie Adjei mengatakan:

    Hello Web Admin, I noticed that your On-Page SEO is is missing a few factors, for one you do not use all three H tags in your post, also I notice that you are not using bold or italics properly in your SEO optimization. On-Page SEO means more now than ever since the new Google update: Panda. No longer are backlinks and simply pinging or sending out a RSS feed the key to getting Google PageRank or Alexa Rankings, You now NEED On-Page SEO. So what is good On-Page SEO?First your keyword must appear in the title.Then it must appear in the URL.You have to optimize your keyword and make sure that it has a nice keyword density of 3-5% in your article with relevant LSI (Latent Semantic Indexing). Then you should spread all H1,H2,H3 tags in your article.Your Keyword should appear in your first paragraph and in the last sentence of the page. You should have relevant usage of Bold and italics of your keyword.There should be one internal link to a page on your blog and you should have one image with an alt tag that has your keyword….wait there’s even more Now what if i told you there was a simple WordPress plugin that does all the On-Page SEO, and automatically for you? That’s right AUTOMATICALLY, just watch this 4minute video for more information at. WordPress Seo Plugin

  2. lista de email mengatakan:

    nice article. i am a huge fan of your work and i’m always coming here to see what’s new. thanks. lista de email lista de email lista de email lista de email lista de email

  3. ÿþd mengatakan:

    If you’re serious about getting tons of free targeted traffic to your site, watch this 1 minute video for free at http://doneforyoutrafficz.com

  4. Clora mengatakan:

    The dictionary is the only place where success comes before work. Think about this. Let’s say you are promoting a site like this website in various places and you’re trying to attract as much traffic as you can. You are commenting on other blogs, you’re making forum posts in several forums, you are paying for putting banners in other blogs, anything possible to promote your blog. Using this tool, you can automatically convert any keyword in your blog to an affiliate link instantly. You can also cloak your affiliate links, track them and manage them right from your WordPress text editor. There is still much more to this so if you are interested, check it out http://www.ninjaaffiliate.org/

  5. zbjigsaw mengatakan:

    This vivid QR code will add much style and color for the bland world of machine readable codes.. He was a carpenter there and had raised his own little additional family. Should you be searching for a bag that could carry significant amount of items with the littlest work, then it is about time for you personally to go on and try making use of a Jute Large Carry Bag. It creates a stunning effect on any glamorous occasion. [url=http://www.goosejacketonline.e]kensington canada goose[/url] There are many sellers claimed that their luggages are made of the highest quality sheepskin. Thomas Gucci viene interpretato da Kim Coates..
    A compelling feminist, MacKinnon initially recognized this metaphor through watching pornographic videos and seeing the way the actors and viewers responded to the woman being filmed. They, like us, had a built-in surveillance system-the automatic brain (AB)-that had its antennae up 24/7 watching for anything that could be dangerous, threatening, or put them in a vulnerable position. This is specifically helpful for the ache in this part of the again that is brought about by way too much stress and tension. Coach handbags are the most popular designer handbags on the market today. [url=http://www.expeditionparka.ca]canada goose jackets[/url] Of course the designs are decorated precious metal or near diamond and the same time they are produced by hand, they appreciate are taken for granted. Choose a wheat corn and soy free food to prevent allergies and highest nutrient values.
    Their square patent leather purse is another exceptionally accepted design that is a staple for any casual or business statement you are trying to achieve. The next day in the Wizard Kelly Community Park, Oscar sets up a Proud Snax Stand with a cardboard stand of himself, he wanted Vincent to see that he doesn’t any stupid operation, but Trudy’s father dumps garbage on the stand leaving Oscar to follow him saying “That is not a trash can”! Penny was with her best friend Dijonay Jones sitting down on a bench sad and bumbed out by her whole family fighting and arguing as they were playing Green Light, Red Light. Drying the fruit also retains the majority of nutrients, and can enhance and strengthen the flavor as the water is removed. The concept behind the Tony Burch brand is creating clothes that are not only beautifully made, but also at an attainable price. [url=http://www.drebeatsbydrescheap.com]beats by dre store[/url] comparable Louis Vuitton bags, Catherine Gardner fu to mail out the grace and tower silk. His next acting credit back is for The Rugrats Movie (1998).
    http://www.expeditionparka.ca

  6. Boypedupe mengatakan:

    скачать решебник атанасян
    примеры решения задач по генетике
    гдз к сборнику степановой 10-11 класс 1996 г

    [url=http://bestfreegdz.ru/file/reshebnik-po-angliyskomu-yazyku-8-klass-kuzovlev-rider-buk-2011-52.html]решебник по английскому языку 8 класс кузовлев ридер бук 2011[/url]
    [url=http://downloadgdzonline.ru/file/dubovik-yurik-vischa-matematika-7a.html]дубовик юрик вища математика[/url]

    Выходец из купеческой семьи, в молодости служил мелким чиновником.
    Я уже не говорю о похищенном сокровище.
    Противник реакции и религиозного фанатизма.
    Входит в состав зубных паст, косметических кремов.
    Просто таким уж он был создан.

    [url=http://bestfreegdz.ru/file/uchebnik-fizika-zakon-gessa-19.html]учебник физика закон гесса[/url]
    [url=http://free-gdz-foryou.ru/file/reshebnik-matematika-1-klass-moro-3c.html]решебник математика 1 класс моро[/url]
    [url=http://downloadgdzonline.ru/file/gdz-po-fizike-testy-e9.html]гдз по физике тесты[/url]

    Только сейчас звонил сосед.
    В средние века к вайшии причисляли только торговцев.
    Либби уже ринулась за календарем, забыв про телефон.
    В пассажирском лайнере предусмотрено такое дублирование всех.
    Увы, ему.

Beri Komentar Disini

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s