Read how to use this Interactive page

Troubleshooter:
How to use this Batch Troubleshooter

Troubleshooter
Using this page

 
Terms in or and symbols, all show more details on demand:

Common problems:
Some common Batch problems and questions

Troubleshooter
Session index

 
We round up the for common Batch file problems. They're captured from our experience of answering thousands of Batch file questions in (if your own problem isn't covered, see our Batch Reference and Batch Course):

Click link for details  Brief description
Operating System Batch Language syntax varies with Operating system
Window stays open MS-DOS window doesn't close (or closes too soon)
Long File Names "Quote" long file/folder names containing  Space s
Internal name error Don't give a Batch file an command name
External name error Don't give a Batch file an command name
Batch File Extension Use .BAT (in 95/98/ME), and .CMD (in NT/2000/XP)
Plain text format Batch files must be plain text files
Environment memory Increase memory to fix out of environment problems
Invalid switch Invalid switch - / or Invalid parameter - / messages
Missing parameter(s) Add any parameters, or use a  ?  parameter pop-up box
Delays and waits Need to delay or wait? Our Batch Reference shows how
ECHO.{demo} Commands ed for demonstration in our examples
MS-DOS window crash Pop-up message: illegal operation, Batch file halts
Wrapped/missed lines Cut-and-paste all text correctly
Third-party utilities We regard SED, GAWK, and 4Dos as standard extras
MS-DOS Window Real-mode syntax may be different or restricted
Batch Links Up-to-date Web links for Batch resources

This is an InfoBox. We use it to include incidental extra details, or reminders. An InfoBox works like a dynamic footnote you call up with your mouse. The details don't intrude into the main text, but are easily consulted. Your cue to find them is either a or a term in purple text. All these InfoBox notes are built into the page, so they work online or offline. We use a distinctive, bold purple cue for InfoBox information where it's more appropriate than the symbol. Either way, you'll know there are more details you can read whenever you want, simply by hovering your mouse over it. We normally gloss every occurrence of a term (except where it's in the left-margin side headings or a LookUp box) Each instance of the symbol will often disclose different information (where it's appropriate). The same term in purple always shows the same information, wherever on the page you find it (and we normally gloss every occurrence of a term, except where it's in the left-margin side headings or a LookUp box). The same LookUp box window will be used by any clickable item on this page. More mouse clicks won't open extra windows, so you needn't bother to close a LookUp window yourself. When you leave this Session, any LookUp window you still have open will close. MS-DOS (=the MicroSoft Disk Operating System) included Batch processing from version 1.0 (August 1981). It was added to help IBM engineers run long lists of commands to test MS-DOS on the IBM Personal Computer original prototype. The Batch language developed steadily through later versions of MS-DOS, and is always installed in Windows 95, 98, and ME (but many users don't know this).
 NT/2000/XP  An enhanced version of the MS-DOS Batch Language comes with Windows NT/2000/XP.
Each MS-DOS window, or DVM (Dos Virtual Machine), is a shortcut to the file COMMAND.COM, which runs MS-DOS commands (this file contains the Batch processing code, as well). A DVM also relies on the files WINOA386.MOD and VGAFULL.3GR, plus a special hardware mode of your CPU, called V86 (=Virtual 86 mode, the "86" relates to a simpler precursor of the Pentium). Each DVM window is like a small PC, simulated inside your main PC. There's more to an MS-DOS window than there first seems!
 NT/2000/XP  The normal command processor is CMD.EXE (a 32-bit program that doesn't need or use V86 mode).
A Windows 95/98/ME DVM (short for Dos Virtual Machine, also called an MS-DOS window) is a Shortcut to the command processor (COMMAND.COM). It also uses the files WINOA386.MOD and VGAFULL.3GR, together with a hardware mode of your CPU, called V86 (=Virtual 86 mode, the "86" relates to a simpler precursor of the Pentium). A DVM is a PC simulated inside your PC!
 NT/2000/XP  A CMD.EXE window is a 32-bit process. It doesn't use V86 mode.
Options that you add to command-lines are known as switches. Switches are commonly indicated by the  /  (forward slash) character, but sometimes you'll find that a  -  is used instead, as for example in: ftp -help (displays help). A command-line prompt, which looks like this:  , waits for you to type a new command. A command typed at the prompt executes as soon as you press the  Return  key. When several windows are open, only one has focus (it has a standard dark blue Title bar). The window with focus is the one that receives any keystrokes from your keyboard. You give a window focus by clicking on it with the mouse (or clicking its Taskbar button). You can also use  Alt Tab  to put up a menu that will cycle the focus through all windows. Our Batch Reference is built into our pages so it works both offline and online. Every time a Batch command or term (in dark blue) occurs in the text, you can click on it to see a pop-up box with details and examples. This same fast LookUp feature applies throughout each Lesson in our MS-DOS Batch Course. The path is where to find a file or folder on a disk or network. Always "quote" a path used with Batch commands if it contains  Space s. Windows uses the backslash  \  separator in paths (the forward slash  /  is used for switches). Don't confuse this sense of path as a pointer to a file or folder with the PATH command or PATH environment variable (which holds the list of paths that are searched for executable files). If you're not sure how to type the pipe | operator, use  Alt + 1   2   4  (digits on the Number keypad), or see Lesson 16 of our Batch Course for details of how to code and use pipes. In Windows 95/98/ME, the command processor is COMMAND.COM. It runs MS-DOS commands, and it contains the code to process your Batch commands.
 NT/2000/XP  The command processor to use is CMD.EXE. This also contains the Batch processing code, which has been enhanced (that's why its Batch syntax differs from Windows 95/98/ME).
CMD.EXE is the standard command processor for Windows NT/2000/XP. It's in the Windows\SYSTEM32 folder. In CMD.EXE, the usual Batch commands have the same names as in Windows 95/98/ME, but they have more features. Their syntax can be different, as a result. We indicate some of the differences to expect (watch for  NT/2000/XP  flash). The GUI or Graphical User Interface is shorthand for the Windows interface with all its windows, icons, mouse, and point-and-click way of working. The alternative is a CLI or Command Line Interface (commands typed at a prompt), which is the usual interface for working with Batch files. Batch files can also be run by clicking on them (see Lesson 19 of our Batch Course for how to write Batch files to run properly in the GUI). By real-mode we mean a 16-bit mode of the x86 series CPUs. The normal Windows features are absent. Multi-tasking of programs is not enabled and a text-based screen is used. Long file and long folder names are not recognised. Windows 95/98/ME runs briefly in real-mode during boot-time (while commands in CONFIG.SYS and AUTOEXEC.BAT are processed). The MS-DOS version in Windows 95/98 can be used in real-mode, but Windows Millennium is not intended for this. The opposite of real-mode is protected-mode (32-bit mode used for the Windows GUI). UNC=Universal Naming Convention: a way to specify a folder on a file server. UNC names are file names (or other resource names) that begin with the string \\, which indicates that they are located on a remote computer. With UNC names for files or folders, Batch commands will work across networks.  Note  Windows needs a backslash  \  separator in its UNC paths (the  /  is reserved for switches). Always "quote" a UNC path if it contains  Space s. We post the majority of our solutions to alt.msdos.batch and alt.msdos.batch.nt, and post under author name William Allen consistently, in order to simplify Google Groups news archive search. An ironic allusion: in the last scene of Casablanca (film 1942), the police chief Renaud (Claud Rains) speaks the line: Major Strasser has been shot. Round up the usual suspects  although, of course, he has just seen Strasser shot before his eyes by Rick (Humphrey Bogart). In Windows NT/2000/XP, use the /? help switch to read more about the Batch commands you think you know. There are full details of the new features and lots of useful syntax examples. Try: call /?, for /?, if /?, set /?, and cmd /?, too, and read how much has been added to the Batch Language. You can download this ZIP package from our Course Syllabus/Index page or the link in any Windows NT/2000/XP LookUp box. It's intended as a guide to workarounds for Windows NT/2000/XP users who can't find a Windows 95/98/ME machine to use for our free MS-DOS Batch Course. Within our 95/98/ME Batch File Course, we indicate some of the differences to expect (watch for  NT/2000/XP  flash) We use Batch files and Batch scripts as interchangeable terms. Batch file is the more traditional term. Batch script emphasizes the relation to other, more recent scripting languages, for example Windows Script Host. Microsoft ftp can be scripted from a text file consisting of ftp commands: for example: ftp -i -s:Script.txt
For help: (a) ftp -help or ftp -? at the MS-DOS prompt for command-line switch syntax; (b) type ftp, and at the ftp prompt, type ? for a full list of commands; (c) at the ftp prompt, use help lcd for help with a specific ftp command, such as lcd (change local current folder). Use bye to close your ftp session and return to MS-DOS.
A third-party utility is a program not written by you, nor included with the operating system, nor supplied by the operating system manufacturer. So, in this case, you and Microsoft are the "first" and "second" parties). AWK is an interpreted language for text processing, named from the initials of its developers, who are: Alfred Aho, Peter Weinberger, and Brian Kernighan. There are two main types of program language: Interpreted: The source code is re-read and then executed line-by-line on each occasion you use the program. Compiled: The source code must be converted to program code (just once, by a compiler), then only the compiled code file is used for any later actual run. A compiled language runs faster, but it's harder to debug and edit. An interpreted language runs more slowly, but it's simpler and faster to debug and edit. DEBUG.EXE is a scriptable hexadecimal editor and assembler (allows you to write programs in assembly language). There are many examples (which don't crash!) of using DEBUG.EXE in the batch files in our Batch Library (for example, see item Dates and Times). There's a link to our Batch Library at the bottom of this page. We cover debugging methods throughout our Batch Course (including Lesson 1). Lesson 2 has an exercise using the command /y step-by-step debug-mode shell to diagnose errors in Batch files. The undocumented TRUENAME lists the short-form path of a short-named file. It doesn't work with long file/folder names. Note that start is an internal command in Windows  NT/2000/XP , and it has many extra switches available. The ping command sends a test packet to a remote server to see if it's operating. Some servers reject pings for security reasons, however. See our Batch Reference (link near top of page) for an unusual use of the ping command to insert fixed time delays in Batch files. For help with ping, use ping -?. The tracert command uses multiple pings to trace the current internet route to a remote server in a series of "hops". Routes revealed vary from time-to-time. For tracert help, use tracert -?. A child shell is a COMMAND.COM or CMD.EXE process run from a parent shell. See Lesson 2 of our Batch Course for a full account of using child shells, which explains the use of the return-code and debug-mode shells (these are available only in Windows 95/98/ME). The pop-up box looks like this (note image below is a small-scale version):

Click the top right  ?  and drop it on any item to get Windows tooltip-style help. Right-click tooltip box to copy or print:

If ECHO isn't OFF when the CLS is executed, remaining commands will be ECHOed to the screen, undoing the effect of CLS. This would stop the window closing. Strictly speaking, an @ (to suppress ECHO of current command line) in this @ECHO OFF isn't necessary in this special case, since the following CLS will clear any command ECHO. Numeric codes in $e[1;33;41m mean:

 Foregrounds   Backgrounds 
30=Black 40=Black
31=Red 41=Red
32=Green 42=Green
33=Yellow 43=Yellow
34=Blue 44=Blue
35=Magenta 45=Magenta
36=Cyan 46=Cyan
37=White 47=White
 1=Set Foreground bold
The colour-clearing PROMPT doesn't actually display anything that you will see. It sends an escape sequence to the ANSI screen driver, but ECHO must be ON for this to happen. This PROMPT no longer has any effect once the MS-DOS window closes.


Operating system:
Before you read on

OS syntax
Using this page

 
Don't forget that you can see extra information on demand:

Syntax varies between operating systems

We state what operating system our Batch scripts are written for (it's usually Windows 95/98/ME). They'll typically need some changes to work, in say Windows , where the more advanced Batch syntax of often allows simpler solutions.

 NT/2000/XP  The microsoft.public.win2000.cmdprompt.admin and alt.msdos.batch.nt specialise in detailed Windows NT/2000/XP discussions.

Typical error messages

If you use an unsuitable script in Windows , error messages may include:

When you take our Windows 95/98/ME Batch File Course, there's an detailing some syntax differences between and 95/98/ME. To read a brief summary (or download it now), click here.


Window stays open:
Before you read on

Window close
Using this page

 
Don't forget that you can see extra information on demand:

Running your Batch files by clicking on them

If you want to run your Batch files by clicking on them in Windows Explorer, you may prefer that the (or ) closes as soon as the script finishes.

MS-DOS window fails to close automatically

Window close
Use CLS
example

However, Windows normally gives you a chance to read any text left on screen by not closing the automatically. So, to make sure it does close, you need to make sure there's no text left on screen. You can do this by:

@ECHO OFF

:: body of code here

:: Final instruction
CLS

should be the last to affect the screen

Window close
Use CLS
example

The needn't literally be the last instruction. For example, this uses a followed by a the end of the code, so is the last instruction that affects the screen.

It's important that command is OFF when the is executed, so if you have ON (for debugging), remember to include an extra @ECHO OFF as shown.


:: Main code here

:: Ensure ECHO is off, clear screen, jump to end of code
@ECHO OFF
CLS
GOTO EOF

:: Other code (for example, Batch Subroutines)

:EOF {End-of-file}

The will close automatically as soon as either example finishes.

 Note  Learn how to write Batch Subroutines with a StudyPack from our Batch Library.

In some cases an is needed too

Window close
Use CLS+EXIT
example

In rare cases, it may be necessary to add an command after the .

@ECHO OFF

:: body of code here

:: Final instructions
CLS
EXIT

Coloured backgrounds may leave window open

Window close
ANSI colours
background

In Windows 95/98, you can load ANSI.SYS from CONFIG.SYS, then use ANSI Escape sequences for colours, with say, the command, as in this :

C:\CSW>prompt $e[1;33;41m$p$g

C:\CSW>REM This shows effect

C:\CSW>

A command would clear the entire screen to the current background colour     . This has a similar effect to text left on screen - the window doesn't close automatically.

Clear the background colour to close window

Window close
ANSI colours
clearing

To have the close itself, clear the background colour like this:


:: body of code here

:: Final code to close window
PROMPT $e[m
ECHO ON
    
@ECHO OFF
CLS

 Note 1  The Blank Line in the code is important, don't forget it.

 Note 2  Windows ME can't use ANSI.SYS (except from its emergency boot disk), so this problem shouldn't arise. For more details, see Microsoft Knowledge Base.

Window closes but you want it to stay open

Window close
Keep it open
with PAUSE

Sometimes, the reverse problem occurs: you want the to stay open, but it closes. In this case, you can use a command to halt the Batch file:

@ECHO OFF

:: Main code

:: Insert PAUSE to halt flow at this point
ECHO. Halting operation
PAUSE>NUL
GOTO EOF

:: Other code (for example, Batch Subroutines)

:EOF {End-of-file}

 Note  The of output to the : PAUSE>NUL allows you to replace the default message with your own, using an command.


Long file names:
Before you read on

Long names
Using this page

 
Don't forget that you can see extra information on demand:

Long File Names

Long names
Use quotes

Long file or folder names that contain  Space s must be enclosed in "double-quotes" when used in Batch commands. If you don't do this, each fragment of the file or folder name is treated as a separate parameter. You also need to "quote" any long file or folder names passed as command-line parameters, for example:

       %0 (batch name) %1 (1st parameter) %2 (2nd parameter)  
C:\CSW>MyBatchFile.bat "C:\Program files" "C:\CSW\My File.txt"

Also applies to immediate mode (and scripted) Batch operations, for example:

ftp> put "File name one.txt"

Use "quotes" if variables may contain  Space s

When you expand environment variables in command lines, they must also be "quoted" if they may contain long file or folder names or with  Space s, for example:

xcopy "%SRC%\*.*" "%DEST%\*.*" /s /y

For more details of how works, use: xcopy /? | more at the , and click anywhere in this Session or in our Batch Course.

 Remember  Our Course Reference supplements the /? help, it doesn't replace it. In xcopy /? | more the to lets you read /? help one screenful at a time.

Typical error messages

If you fail to "quote" Long file or folder names, you'll see error messages such as:


name:
Before you read on

Internal name
Using this page

 
Don't forget that you can see extra information on demand:

name error

Internal name
Conflicts

The command processor that Batch files, ( or ) has the program code for commands. These commands take precedence over Batch files; don't use Batch file names that conflict with them. This example shows what happens if you name a Batch file ECHO.BAT and try to run it:

ECHO.BAT doesn't run and an happens

C:\CSW>type echo.bat
@ECHO OFF
ECHO. This Batch file is called ECHO.BAT

C:\CSW>echo
ECHO is on

C:\CSW>echo.bat
bat

C:\CSW>c:\csw\echo.bat
 This Batch file is called ECHO.BAT
C:\CSW>_

 Note  Even using the full name, ECHO.BAT, simply generates an (of bat). Using the full to the file C:\CSW\ECHO.BAT does run the Batch file, however.

Typical error messages

If you use an command as a Batch file name, you'll meet problems such as:

Treat the Windows 95/98/ME commands as reserved names that you don't use for Batch file names. The list of reserved command names to avoid is as follows:

Reserved words to avoid for Batch file names

Internal name
Reserved

BREAK, CALL, CD, CHCP, CHDIR, CLS, COPY, CTTY, DATE, DEL, DIR, ECHO, ERASE, EXIT, FOR, GOTO, IF, LFNFOR, LH, LOADHIGH, LOCK, MD, MKDIR, PATH, PAUSE, PROMPT, RD, REM, REN, RENAME, RMDIR, SET, SHIFT, TIME, TRUENAME, TYPE, UNLOCK, VER, VERIFY, and VOL.

To find out what any of the commands do, read the CommandName /? help.

Some are obsolete or rarely used (eg ), or are used only at boot-time.


name:
Before you read on

External name
Using this page

 
Don't forget that you can see extra information on demand:

name error

External name
Conflicts

commands are standard executable files in your system that the Batch Language relies on; don't use Batch file names that conflict with them. Problems will be most evident when a Batch file tries to use an command it shares a name with.

Typical error messages

If you use an command name, for example FIND.BAT (which will conflict with the command), you'll meet problems such as:

Treat the Windows 95/98/ME commands as reserved names that you don't use for Batch file names. The list of reserved command names to avoid is as follows:

Reserved words to avoid for Batch file names

External name
Reserved

attrib, chkdsk, choice, cscript, debug, deltree, diskcopy, doskey, edit, extract, fc, fdisk, find, format, keyb, label, mem, mode, more, move, mscdex, nlsfunc, scandisk, sort, start, subst, sys, xcopy, and xcopy32 (component of ).

To find out what any of the commands do, read the CommandName /? help.

Avoid other standard executable names

Avoid Batch file names that conflict with TCP/IP commands: ftp, ping, tracert. For examples using scripted from a Batch file, see our Batch Library. Be alert for conflicts with any other executable names in your system .


Batch file extension:
Before you read on

Extension
Using this page

 
Don't forget that you can see extra information on demand:

Use .BAT or .CMD

Extension
Use .BAT .CMD

Batch files in Windows 95/98/ME are by , and should have a .BAT file extension. Batch files in Windows are normally by , and may have extension .BAT or .CMD (use .BAT if the Batch file is written to run on Windows 95/98/ME as well as Windows ).

 Note  Windows has a version of for legacy use, but it has fewer features than and is better avoided.

Take care with Notepad

Take care saving Batch files with Notepad. If you save Notepad files carelessly, you may add a spurious .TXT extension. Use Save as type = All Files (*.*).

Typical error messages

If you use the wrong extension for Batch files, you'll usually see the error message:


Plain text format:
Before you read on

Plain text
Using this page

 
Don't forget that you can see extra information on demand:

Use plain text format for Batch files

A Batch file must be a plain text file. Write them with a text editor such as Windows Notepad (use Save as type = All Files (*.*) to avoid a spurious .TXT extension). If you use a WordProcessor, such as WordPad, Save as type = Text Document.

Typical error messages

If you save a Batch file as a WordProcessor document, you'll meet problems such as:

Syntax highlighting can help avoid syntax errors

Plain text
Highlighting
example

Some specialised editors, such as TextPad, have Batch syntax highlighting, thus:

@ECHO OFF
:: Skip to end if not enough parameters
IF [%2]==[] GOTO EOF
:: Skip to end if files don't exist
IF NOT EXIST %1 GOTO EOF
IF NOT EXIST %2 GOTO EOF
:: Compare, test for *** in fc output
fc /L /Lb1 %1 %2 | find "***">NUL
:: Report findings
IF ERRORLEVEL 1 ECHO. Files %1 and %2 identical
IF NOT ERRORLEVEL 1 ECHO. Files %1 and %2 differ
:EOF {End-of-file}

 Note 1  The example uses to compare two text files whose names are passed as command line parameters, %1 and %2, after checking the files exist. The highlighting is user-configurable: we highlight s and our standard labels, such as EOF, too.

 Note 2  In a practical version, if insufficient or non-existent parameters are supplied, you should generate an error message instead of merely skipping to the end of file.

Our Batch Course (Lesson 20) covers using s with to return s.


Environment memory:
Before you read on

Environment
Using this page

 
Don't forget that you can see extra information on demand:

Windows 95/98/ME default size is small

Environment
Change default

Most Windows 95/98/ME Batch files use environment variables, which are stored in a region of memory reserved by . The default amount reserved is quite small (about 160 bytes), and if you work with Batch files you may want to increase it.

In Windows 95 or Windows 98, you can change the default environment memory by altering the file CONFIG.SYS in your root folder. To reserve 2048 bytes (adequate for most purposes) add the following two lines (the first is a comment) to CONFIG.SYS:

;2048 bytes environment space and 255 character command line
SHELL=C:\WINDOWS\command.com C:\WINDOWS /e:2048 /p /u:255

If you already have a SHELL= line in your CONFIG.SYS, you should add any changes to it, rather than add a second SHELL= line. Changes take effect at the next reboot.

In Windows Millennium, you can increase the default Environment with a setting in SYSTEM.INI (in your Windows folder) – for example, to set a default 2048 bytes:

  1. Open C:\WINDOWS\SYSTEM.INI in Notepad
  2. Find the section headed: [NonWindowsApps]
  3. Add a new line below: CommandEnvSize=2048 and save the file again
Any changes to SYSTEM.INI take effect at the next reboot.

Changing environment size in a window

Environment
Change window

In Windows 95/98/ME, you can change the environment memory allocated in a particular or in the Shortcut to a specific Batch file. Open the Properties dialogue (right-click the Shortcut or Desktop icon, and click Properties).

Click the Memory Tab. Use the initial environment pull-down box to set a size that's enough for your variables, say 2048 bytes (or more if you wish).

See Lesson 19 of our Batch File Course for full details of how to configure a Batch Shortcut in this way (with an interactive walk-through).

Windows NT/2000/XP reserves ample memory

 NT/2000/XP  You don't need to do this in Windows , because reserves ample environment memory. If you receive out of environment messages, older software may be using the provided for backwards compatibility.

Change environment for one command

Environment
One command

You can alter environment memory with the /e , for example:

command.com /e:2048 /c MyBatchFile.BAT

will run MyBatchFile.BAT in a with 2048 bytes environment memory. To read about other , use command.com /? (the /y debug-mode shell and the /z return-code shell are not available in Windows ).


Typical error messages

If there isn't enough environment memory, characters may be lost from environment variables as they are truncated. You'll usually see the error message:


Invalid switches:
Before you read on

Invalid switch
Using this page

 
Don't forget that you can see extra information on demand:

Invalid switches or parameters

Invalid switch
example

A Batch command may fail with an Invalid switch - / or Invalid parameter - / message:

C:\CSW>dir "c:\program files\*.EXE" /s /b /d
Invalid switch - /D

C:\CSW>xcopy "c:\my data\*.*" f:\keep\*.* /s /d /x
Invalid parameter - /x
0 File(s) copied

C:\CSW>

Was the switch invalid?

In the example above, the answer is clear. Although the in the commands are correctly "quoted", the /d and the /x are indeed invalid.

For valid and , see the /? help: for example dir /? | more (the added to shows /? help one screenful at a time).

Mistakes in UNC paths

Invalid switch
UNC mistakes

An Invalid switch / or Invalid parameter / may also arise from a bad network :

C:\CSW>dir //OTHER/C/DATA/*.*
Invalid switch - /

C:\CSW>xcopy //OTHER/C/DATA/*.* C:\DATA\*.*
Invalid parameter - /
0 File(s) copied

C:\CSW>_

Use  \  (not  / ) in paths

Here, and are being used with an incorrect network . Windows needs a backslash  \  separator in network . In the example, everything following the incorrect  /  is interpreted as an invalid . For an easy drag-and-drop method to find network correctly, see our Batch Reference

The correct network syntax for the and commands above is:

dir \\OTHER\C\DATA\*.* and xcopy \\OTHER\C\DATA\*.* C:\DATA\*.*


Missing parameters:
Before you read on

Parameters
Using this page

 
Don't forget that you can see extra information on demand:

Missing parameter(s)

Parameters
Check if needed

Batch files are frequently written to use command-line parameters. These are text tokens added after the Batch file name, on the same command line, and are used in the Batch file as %1 (first parameter), %2 (second parameter), and so on through %9. Make sure you supply parameters (often file names or ) if a Batch file expects them:

MyBatchFile.bat "C:\My data\File One.ext" FileTwo.ext

Missing parameters may terminate a Batch file

@ECHO OFF
:: Skip to end if not enough parameters
IF [%2]==[] GOTO EOF

:: Main body of code would go here

:EOF {End-of-file}

 Note  The example checks for at least two command line parameters, and skips to the end of file if they aren't found (it's better to warn the user if parameters are missing). If you're unfamiliar with command-line parameters, see Lesson 12 of our Batch Course.

Parameter pop-up box

Parameters
Pop-up Box

You can add command-line parameters in the Cmd-line field of the Program Tab of a Shortcut to the Batch file. If you use the special  ?  as the parameter in the Cmd-line field of a Shortcut, Windows displays an Input Box (each time the Shortcut is used) in which you type any required parameters.

See Lesson 19 of our Batch Course for more details of how to configure a Batch Shortcut in this way (you can see an explanation of each of the many fields in the Properties dialogue with the usual Windows click-drag-and-drop method).

Typical error messages or symptoms

With Batch files, it's better to test for valid parameters, and warn the user if they're missing. If you leave out the command-line parameters that a Batch file expects, you may meet these problems:

Make sure you supply any command-line parameters a Batch file needs.


.{demo}:
Before you read on

Demo commands
Using this page

 
Don't forget that you can see extra information on demand:

Inactivating commands with .{demo}

Demo commands
Inactivated

Many Batch files carry out critical operations, such as deleting or renaming sets of files, or running powerful commands. Typically, a Batch file will calculate the command lines needed for these operations, and then execute them.

To allow you to see what a Batch file would do, but without actually doing it, we often write Batch files to the calculated commands. It can be confusing to see valid commands ed without executing, so we add a {demo}, too, after the .

Building a complex rename command

For example, a command line to rename a file to the current date (which had been calculated in environment variables), might be built up in stages, eventually becoming:

:: Remove the ECHO.{demo} to activate command
ECHO.{demo}REN %3 %CY%%Y%-%MO%-%D%.*

Watch the ed command you build

Instead of executing the command on the file passed in %3 (say, FileName.EXT), the Batch file displays the command (expanding the variables) to show what would happen:

{demo}REN FileName.EXT .*

Activate the command when it looks right

Demo commands
Re-activate

The {demo} reminds you that the command is merely being ed. When you are satisfied that the commands generated in this way will do exactly what you want, you can remove the ECHO.{demo} prefix from them. Then, the generated commands will execute (not simply with a {demo} warning) when the Batch file is run.

:: Rename command now active
REN %3 %CY%%Y%-%MO%-%D%.*

The above command isn't ed on screen, it's executed.

 Note  To create variables containing current date elements, see our Batch Library.


MS-DOS window halts:
Before you read on

DVM crash
Using this page

 
Don't forget that you can see extra information on demand:

An illegal operation

DVM crash
Illegal ops

Sometimes a Batch file crashes the (or ) in which it's running, and you see a pop-up window with an illegal operation message like this:

Example of illegal operation pop-up window

When you click the  Details>>  button in an actual case, you'll see a message such as:

Minor syntax errors may be responsible

DVM crash
Illegal ops
syntax error

The typical causes are:

:: Copy yesterday's 23:00-24:00 data
TYPE %3 | find /i "%YDAY">%FN%.AWL

Warning: syntax error in code above

An actual example

The above example actually happened in developing one of the Batch files used to maintain this Website. The matching second  %  character needed to expand the variable YDAY is missing (and the crashed at 902B:007C). The correct coding is:

:: Copy yesterday's 23:00-24:00 data
TYPE %3 | find /i "%YDAY%">%FN%.AWL

Diagnostic s and s will help

DVM crash
Illegal ops
breakpoints

The correctly restored  %  character is highlighted - such mistakes are easy to make. You can diagnose these problems by inserting breakpoints with combinations of commands and ed messages (with paired ECHO ON and @ECHO OFF to display sections of Batch code at work). See Lessons 8, 9, and 10 of our Batch Course.


Wrapped/missed lines:
Before you read on

Cut-and-paste
Using this page

 
Don't forget that you can see extra information on demand:

Take care when you cut-and-paste Batch code

Cut-and-paste
2-space check

If you cut-and-paste the text of a Batch file from one of our posts, make sure you include all the lines. And make sure none of the lines wrapped wrongly in your newsreader. We normally prefix all lines with two  Space s, so you can spot if lines have wrapped incorrectly. This simplified example shows correct and incorrect versions:

Correct version aligns

Correct version (each line begins with    = two  Space s:
====Begin cut-and-paste (omit this line)
  @ECHO OFF
  FOR %%F IN (C:\WORK\*.TXT) DO IF (%OK%)==(GoAhead) TYPE %%F

====End cut-and-paste (omit this line)

Wrong version wraps

Cut-and-paste
Bad line-wrap

Wrong version (third line doesn't begin with    because second line has wrapped):
====Begin cut-and-paste (omit this line)
  @ECHO OFF
  FOR %%F IN (C:\WORK\*.TXT) DO IF (%OK%)==(GoAhead)
TYPE %%F


====End cut-and-paste (omit this line)

There's no need to prefix your own lines with  Space s in this way, it's simply a safeguard we adopt for posts of Batch file examples.

Typical error messages (missing lines)

If lines are missing, you may see only a part of the output you expected. You may also see error messages such as:

Typical error messages (wrapped lines)

If lines are wrapped accidentally, you'll see error messages such as:


Third-party utilities:
Before you read on

Third-party
Using this page

 
Don't forget that you can see extra information on demand:

Third-party utilities

Third party
Best avoided

As far as possible, we avoid utilities. The main advantage of using the Batch Language is that it runs on any machine with the relevant operating system. If your Batch files can't run on a normal installation, you lose one of their key features.

However, a few utilities are worth learning to use because they are in fairly wide use, or perform functions that aren't feasible without them. But bear in mind that the more utilities you rely on, the less generally useful your Batch skills will be.

Third party
SED and GAWK

Our posts sometimes use one of these three (the SED and GAWK links are for the versions we use ourselves, and are not necessarily the most up-to-date ones):

In each case, place the SED.EXE, GAWK.EXE, or PV.EXE executable in a folder in your system to use a Batch file that is dependent on any of these utilities.

The 4Dos alternative command processor

Third party
4Dos now free

The 4Dos is an alternative command processor for . It is intended to replace , and has a wide range of powerful Batch features. It used to be a commercial product, but from 24th August 2004 the Windows 95/98/ME version of 4Dos became free. You can download it from the 4Dos Website.

Using 4Dos in its own Custom window

Third party
4Dos now free
custom window

For those who want to try 4Dos now it's free, but are reluctant to go as far as replacing their standard , we've published Our 4Dos Guide. This explains how to install a set of 4Dos components in a Custom . Installed in this way, you can learn to use 4Dos without altering your Windows operating system.

Typical error messages

If a Batch file can't find a utility it depends on, you'll see the error message:


MS-DOS Window:
Before you read on

Batch window
Using this page

 
Don't forget that you can see extra information on demand:

Batch files work well in an MS-DOS window

Batch window
Extra features

We normally write to run in an in the Windows . In an you can use many extra features: with Long File and Folder names; the command; and useful extra with commands such as .

Configuring the window

We explain how to configure an that is ideal for running Batch files in the Introduction to our Batch File Course.

Typical error messages

An unsuitable script run in (or a badly-configured window) may report:


Batch Web Links:
Before you read on

Batch links
Using this page

 
Remember, hover your mouse over any, or any term to see an

Batch Web Links

Our own interest was originally stimulated by the highly intuitive techniques developed by Tom Lavedas, whose Website is well worth studying. For general links, Frank-Peter Schultze keeps an up-to-date, detailed list of Batch Bookmarks that's very useful.

Learning for yourself

Newcomers to the Batch Language in Windows 95/98/ME can learn its syntax with our interactive, Web-Based Batch Course with built-in reference. When you've completed our Course, use our documented Batch Library and Batch Reference.

Finding old Usenet posts

We've posted thousands of Batch file solutions to Usenet . You can search through our previous posts on Google (but not all posts are archived).

with any Batch questions

If you have Batch questions, or can't find an old post of ours, please . Your email subject line should contain: Allenware.com website. Please be sure to say whether you are using Windows 95/98/ME or Windows NT/2000/XP.

William Allen and Linda Allen
© Copyright 2003- Allen & Company. All rights reserved ©