Академический Документы
Профессиональный Документы
Культура Документы
This Course is for Windows 95/98/ME users (click here Windows NT/2000/XP users). And
remember, you can work offline (for details, click here Work OffLine).
The MS-DOS Batch Language is the set of commands you can use in a Batch file. It's
an interpreted program language. You type commands to run them immediately ? or you can
list them in a text file (a Batch file or "script") to run them later.
By the way, whenever you see this symbol ? or a term in purple, you can hover your mouse
pointer over it to read extra details. Try it out on the previous paragraph ...
In a later Lesson, we'll see that Batch files can be run by point-and-click (often the best way to run
them). However, while we learn, we'll work with command lines typed at a prompt. How will you
know what to type? Click an Exercise button and see instructions in the corner of your screen.
This Course works wholly on-screen (no print-outs needed).
Let's start with some practice Exercises to see how this works. First, glance briefly at the preview
pane below (it lets you know what to expect). Then click the button on the right, marked ex 1, and
a small pop-up window will appear (for Exercise 1):
ex 1
This is the preview pane for Exercise 1. Each Exercise has a preview pane with either:
Glance at the preview pane before you do each Exercise. Review it briefly afterwards. This will
help fix what you've learnt in your memory.
If you refresh this page in your browser (don't do it now!), all the Exercise buttons will revert to
their unused normal appearance. So, for example, if you wanted to restart a Lesson from the
beginning, you could refresh the page to reset all the Exercise buttons.
You need to do all the Exercises in each Lesson (and in the order they occur). This is because
the Course is really in the Exercise windows, not in this main Lesson window. Glance at the
preview pane below, then click the button (for Exercise 2):
ex 2
Exercise 2 preview:
Note We try to make this Course usable with most versions ? of Windows, from Windows 95
onwards. The illustrations we show are normally for Windows 95. Later Windows versions are
similar, but may have additional features or different wording.
A Working Folder:
Making a new folder for our Course work
We'll need a folder on your hard drive to work in. We strongly suggest you make a new folder for
this, and you call itC:\CSW (the Lessons that follow all assume you will use this name). CSW
merely stands for Command-line Scripting in Windows, and (we hope) it's not a folder name
you're currently using (if you are, choose another name).
You're probably used to making new folders in Windows Explorer or My Computer. This is a
Batch Scripting Course, so let's make the folder in a completely different way.
We can't use a Batch file to do it, because we don't know how to write one yet! We can't type a
command at the prompt in the BatchWindow , because we haven't made the
special BatchWindow yet – that needs the C:\CSWfolder to be there first!
So we'll take a sneak preview of some advanced syntax (from Lesson 2 and Lesson 7, and create
our folder with a command executed in a single-use child shell in the Run dialogue box – soon,
you'll be using this jargon like an old hand!
NT/2000/XP (Exercise 3 shows only Windows 95/98/ME version). Syntax to use:
Glance through the preview, then try it out for yourself (Exercise 3):
ex 3
For Exercise 3, you may prefer to read all the mini-pages first, before going back to try it out
Remember, if an illustration is too big for its pop-up window, click its hyperlink again:
NT/2000/XP Did you remember to use cmd if you're using Windows NT/2000/XP?
Although command would have worked, it's better to get into the right habit now.
A Working Window:
The BatchWindow will be our main workplace
Now we'll make our BatchWindow . This is a customized DVM). It will be similar to the MS-DOS
Prompt window (installed in your Start + Programs menu). The difference is that we'll
customize the BatchWindow to make it ideal for learning to write Batch files.
To make a new DVM, all we need do is create a Windows Shortcut to the program
file COMMAND.COM. This file is located in your Windows folder (there may be a copy of it in
your root folder, too, but it's the one in the Windows folder that we'll use).
In either case, if your Windows folder isn't C:\WINDOWS, use your own folder name. And be sure
to type those slash characters: \ (path separator); and / (switch character) the right way
round (remember to hover your mouse over a purple term to read more).
The preview gives you an idea of what we're about to do. Glance through it, but don't try to
memorize it, everything is in the Exercise window mini-pages (Exercise 4):
ex 4
Exercise 4 preview:
Remember, if an illustration is too big for its pop-up window, click its hyperlink again:
NT/2000/XP Did you remember to use the alternative Windows NT/2000/XP syntax? If you
forgot, delete the Shortcut you created and repeat Exercise 4. By the way, the Icon appearance
will be different inWindows NT/2000/XP.
Note Our Shortcut is actually a tiny file, 967 bytes (characters) long. The full name Windows
95/98/ME gives the Shortcut is BatchWindow.pif ? (but the extension isn't displayed).
The /k switch we used in our command line suppresses the Copyright message that would
otherwise appear whenever you open the BatchWindow .
We'll configure the settings, including TrueType fonts, for our DVM Shortcut by using
its Properties sheet (a specialised editor window).
NT/2000/XP (Exercise 5 shows only Windows 95/98/ME version). The layout of the Properties
Sheet items inWindows NT/2000/XP differs. The TrueType fonts are under Lucida Console,
and sizes are in points (inExercise 5, try about 20 points).
We can open the Properties sheet by right-clicking on our new Desktop Shortcut without actually
opening the DVMitself yet. We'll do this to configure some settings before we open and use the
new DVM (Exercise 5):
ex 5
Exercise 5 preview:
Remember: you can click again on any of the illustration links to make their window larger.
Note 1 TrueType fonts are not supplied in Windows 95 unless you have the Microsoft Plus!
Pack for 95 (choose Custom Install, Visual Enhancements, MS-DOS font option).
Before we open the new BatchWindow , it's worthwhile reviewing a few things about window
sizes. As you know, an ordinary program window has three states:
Maximized
A Maximized window occupies all your monitor screen (except for the Taskbar), and its
control buttons look like this .
Restored
A Restored window occupies part of the screen. It's usually resizeable smoothly by
dragging its edges with the mouse. Its control buttons look like this .
Minimized
A Minimized window doesn't occupy any Desktop space. To use it, you either maximize
or restore it with its button on the Taskbar.
A DVM window, such as the BatchWindow , works differently. And a DVM window also has an
extra, fourth state (Full screen). A DVM window state can be:
Maximized
The size of a Maximized DVM is set by the Font size chosen. It won't normally fill your
screen exactly. If the Font size is too large, it may even more than fill the screen (so you
see only part of the contents, and there are scroll bars). Its control buttons have the
normal maximized look .
Restored
A Restored DVM window is resizeable smoothly by dragging its edges with the mouse.
But again, its maximum size is set by your choice of Font. And it may more than fill the
screen (you see only part, and there are scroll bars) if the Font is too large. Its control
buttons have the normal restored look .
Minimized
A Minimized DVM works like other minimized windows. It doesn't
occupy any Desktop space, and you access it by clicking its
Taskbar button .
Full screen
A DVM can also be used "Full screen" – a legacy mode ? of
your monitor (we won't normally use it). To switch between this
mode and the normal Windows
screen, remember the Alt Enter key combination: to use it, you hold down Alt and
press the Enter or Return key. We'll practise Alt Enter switching shortly so you won't
forget it, in case you switch to Full screen by mistake!
When you open the BatchWindow for the first time, it will typically open restored, so its control
buttons appear as , and have scroll bars. It should look like this:
NT/2000/XP In Windows NT/2000/XP, there is no Toolbar. You right-click on the Title bar,
then click Propertiesto reach the corresponding CMD.EXE window controls.
We need to lay out the screen properly, so that you can use the Course in the way intended
(which the diagram shows).
We'll have the main Lesson window taking up the full screen. Overlying it will be
the BatchWindow , the Exercise window, and any figure window (which will normally fit in the
top left).
Text you'll need to type will be shown in the Exercise window. You copy this to
the BatchWindow (or a Notepad window, which we'll also keep in the bottom left corner of the
screen).
With the windows arranged to fit properly, you'll find you can work quickly and smoothly. Switch
between windows (or return to the main Lesson window) by clicking their Taskbar buttons. All the
windows will "remember" their positions throughout a Lesson.
Note The layout works for 800x600 monitor resolution (or higher). With this technique, you'll
find it's easy to maintain concentration, since there's no need to glance away from the screen.
Indeed, if you work for long sessions in this way, you may consider using a lower ? resolution
than you'd normally use for casual browsing, to avoid eyestrain.
When you first open the BatchWindow , it may partly cover the Exercise window. In Exercise
6 we'll maximize it first (remember, for a DVM that's not Full screen size). Then we'll position it
properly. Its Shortcut will "remember" that size and position every time we open it at the start of a
Lesson. We'll work on the Desktop again (Exercise 6):
ex 6
Exercise 6 preview:
Remember: you can click again on any of the illustration links to make their window larger.
Types of Exercises:
There are three different types of Exercise
We said earlier that there are three types of Exercise in this Course. They are:
1. Mini-page: Preview shows a summary of steps (so you know what to expect)
2. DVM: Preview shows the relevant results of running Batch commands
3. Notepad: Preview shows relevant changes to a file we're writing in Notepad
All the Exercises so far have been the Mini-page type. Now we'll try a DVM Exercise.
DVM Exercises:
DVM Preview shows commands and results
In a DVM Exercise, the preview simulates the relevant part of the BatchWindow , showing the
commands you type, and the results you will see.
Preview repeated
The preview also appears in the Exercise window (after the instructions). You can scroll
the Exercise window down and compare the preview with your own results. It's easier than
looking back at this main window (which would overlie your DVM work).
When you scroll or click the Exercise window, you'll take focus off the BatchWindow (its Title
bar turns grey). You'll need to click on the BatchWindow again (or click its Taskbar button) to
return focus to it (the Title bar will turn dark blue again) before you can continue typing any more
text or commands in it.
In this Course, we won't be using Full screen mode, but we'll practise switching in and out of it
now, in a DVMExercise (just to become familiar with how to switch modes).
In Full screen mode, other windows are obscured (that's why we won't normally use it). We'll type
a brief reminder (of how to swap back) in the BatchWindow before we switch. We'll prefix our
note with REM. Glance at the preview pane below, then click the button and try it out for
yourself (Exercise 7):
ex 7
C:\CSW>_
In the BatchWindow , you can clear clutter from previous Exercises with the CLS command
(clear screen). Click the Exercise button and try it now (Exercise 8):
ex 8
C:\CSW>cls
C:\CSW>_
Environment memory:
Space for variables that a Batch file can use
We can use simple variables in our Batch files to hold strings of characters. They're stored in a
region of memory reserved by COMMAND.COM, called the environment (and so they're known
as environment variables). The default amount of memory for the environment is small, typically
about 512 bytes (one byte=one character).
NT/2000/XP Windows NT/2000/XP users should skip Exercise 9, it's not needed.
We'll use the BatchWindow Properties sheet to set a larger value, so we don't run into "out of
environment space" errors while we learn. For our purposes, an environment size of 2048 bytes
will be ample, so let's set that now(Exercise 9):
ex 9
Exercise 9 preview:
Remember to click again on an illustration link if you need to make its figure window larger.
Now all the Batch files we run in the BatchWindow will have enough memory for the variables
we'll be using. The memory setting we've just changed applies only to the BatchWindow . In a
later Lesson, we'll learn how to configure Shortcuts to individual Batch files to run them by point-
and-click with their own customised DVM settings.
National Keyboards:
Typing the right keys in the BatchWindow
When Windows was installed on your PC, the right keyboard drivers were installed by the setup
process, so that what you type is interpreted properly (always a good idea!).
The DVM keyboard driver is different from the one used in the GUI, and it has to be set up
separately. This may have been done correctly on your machine – or not! So our next task is to
check if there's a problem. And if there is, to fix it.
Note If you're using Windows Millennium, your keyboard driver should be correct. If it
isn't, don't ? use our solution. Instead, read the Microsoft Knowledge Base document:
Keyboard Command Does Not Work in Command Prompt (reference Q261417).
NT/2000/XP You should have no keyboard problems; the keyb command discussed
next isn't used. You can skip Exercise 10, Exercise 11, and Exercise 12 below.
The default driver is for United-States-layout keyboards. And users in, for example, the United
Kingdom, may find their systems are left with this default setup in a DVM window.
Let's try a test in the BatchWindow with another REM command (Exercise 10):
ex 10
C:\CSW>_
If your keystrokes are displayed properly, you don't need to fix anything (but you may want to
read throughExercise 11 and Exercise 12 anyway, without making changes).
The command to change the DVM keyboard setup is: keyb ?? where the ?? is your two-letter
Country keyboard code. For the United Kingdom, the two-letter code is uk.
The table below shows the two-letter codes for other countries in the main driver list:
Users whose national keyboards are very different from the United States layout are more likely
to find their systems were already set up properly. So, as our example, we'll suppose a United
Kingdom PC has been left inadvertently with the United States default driver (you must use
your own Country keyboard code for any changes, of course).
A user in the United Kingdom can configure the BatchWindow to use a UK format keyboard with
the commandkeyb uk
If you're a United Kingdom PC user who saw " and @ transposed when you typed them,
use keyb uk in the BatchWindow , then try the REM test again (Exercise 11):
ex 11
x x x (wrong line)
C:\CSW>rem @quotes@ and " symbol test
C:\CSW>keyb uk
C:\CSW>_
Using the keyb command in a DVM affects only your current session. Any change is lost when
you reboot. At this stage, we don't want to get involved with changing startup files, so we'll
simply configure the BatchWindow Properties sheet to run the keyb command for us any time
we open the window.
The change applies only to MS-DOS processes, such as the Batch file work we'll do in this
Course. It doesn't affect any of your usual Windows programs.
You need complete Exercise 12 only if the keyb command that you used actually did correct
errors in the way your keystrokes were rendered on screen (Exercise 12):
ex 12
Exercise 12 preview:
Don't do Exercise 12 unless the REM typing check failed when you tried it.
Managing windows:
That finishes configuring the BatchWindow
We've finished configuring the BatchWindow . You're now ready to start the Course.
We suggest you start each Lesson with no other windows open, so the Lesson button is in the
first position on your Taskbar. You'll be switching between multiple windows, so it will help if you
keep to standard positions for the Taskbar buttons.
NT/2000/XP Location of folders are different (both Exercise 13 and Exercise 14 show only
Windows 95/98/ME version), and if you're using Profiles, the locations are more complex. At this
stage of the Course, you may prefer to skip on to Exercise 17 now. The Windows
NT/2000/XP "All Users" locations are usually:
If you're using profiles, folder locations are more complex, and you should skip ? to Exercise
17 now. You can leave the BatchWindow Shortcut on your Desktop.
You could copy the Shortcut with Windows Explorer, but since this is a Batch Course, let's do it
from the BatchWindow command-line. We'll do this by sneaking a preview of two more
instructions. We'll do it in three steps. Don't bother to remember the details at this stage, there's
ample practice to come in the Lessons that follow!
First we'll copy the Shortcut to our new folder (Exercise 13):
ex 13
C:\CSW>copy %windir%\desktop\batchwindow.pif
1 file(s) copied
C:\CSW>_
If you get it right, the COPY command reports that one file was copied. If you didn't, try again
(check carefully against the line exactly as shown in the Exercise window). It's important to leave
a Space between the word copyand the rest (the file specification). Don't leave any Space s in
the file specification part, however.
We didn't say where to copy our Desktop Shortcut, so Windows copies it to the current folder
(the one shown in the prompt ), which is our new C:\CSW folder.
We didn't say what name to give the copy, either, so Windows gives it the same name
(BatchWindow.pif) as the original. Now let's copy the Shortcut from C:\CSW to the Start
Programs folder (Exercise 14):
ex 14
C:\CSW>_
Delete the copy left in ourC:\CSW folder
Again, if you get the syntax correct, the COPY command reports that one file was copied. If you
didn't, try again, checking carefully against the Exercise window. Once again, the Space s are
important in the syntax.
Since we didn't include a folder as part of the BatchWindow.pif name, Windows assumed that
the file was in the current folder (and it was, since we'd copied it there).
The COPY command will have left the copy Shortcut in C:\CSW, so let's delete it. It's always
worth keeping your disk free of unnecessary clutter (Exercise 15):
ex 15
C:\CSW>del batchwindow.pif
C:\CSW>_
Now you can open the BatchWindow from your Start Programs menu. Let's test it now, so
we know it will be ready for Lesson 1 (Exercise 16):
ex 16
Exercise 16 preview:
Confirm the window reopens in the standard position and at the correct size you've set.
On screen help:
Use /? for quick help with Batch commands
The syntax and the features of Batch commands aren't easy to remember when you are
beginning to learn them. Fortunately, all the commands have a standard system for getting quick
help, and reminding yourself what features are available for any particular command. You simply
type the CommandName followed by /? (the help switch).
Let's try it. The first command we used was MD to make a folder (Exercise 17):
ex 17
C:\CSW>md /?
Creates a directory.
MKDIR [drive:]path
MD [drive:]path
C:\CSW>_
NT/2000/XP The /? help is different from Windows 95/98/ME, and includes details of extra
features. InWindows NT/2000/XP it's particularly important to check the /? help.
We'll be making use of the /? help throughout the Course. It's worth checking command details
regularly in this way, until you become very familiar with them.
However, the /? help doesn't show actual syntax examples. It shows an idealised pattern
where [item] means itemis optional (it doesn't mean put brackets round the item when you use
the command). And you'll find that /? help uses this | that to mean either this or that, not both
(it doesn't mean type a vertical bar between them).
In other words, /? help can be confusing until you're more familiar with using commands! For this
reason, we've added some extra help.
To provide more help during the Course we've added our own Command Reference. From now
on, whenever you see a command name in dark blue, you can use the Course Reference. To do
so, click on the command itself. Try it,click on MD.
Our Course Reference is dynamic: new information doesn't appear until you've learnt to make
use of it. We haven't covered MD properly, so there's nothing much to say!
You'll also be able to use our Course Reference from a List Box at the top of each Lesson. It has
all commands covered up to (and including) those in the current Lesson.
To use it, click the tab to pull down the list, then click the item you're interested in.
Of course, MD is the only Batch term in the list at this stage! And we won't be using MD properly
until a later Lesson, so after this Introduction, it will disappear until we do.
With each Lesson, the Course Reference gradually shows more about each command. Advanced
details appear only when basic ideas have been covered properly.
The Reference List Box at the start of each Lesson includes commands to be covered in that
Lesson. Use it to brush up on commands only after you've learnt about them in the Lessons, and
when you want to practise on your own.
Use Course Reference to review and revise
The Lessons themselves lead you through new material. The clickable Reference is for you
to review, revise, andexpand on what you've already learnt. And it adds to the information
the /? system provides (it doesn't repeat or replace /? help), so use both.
That completes the Course Introduction. At the top of each Lesson that follows, there's a link back
to this Introduction (in case you need it), and a link to the Lesson Index, too.
Lesson 1 has 34 exercises and takes about 70 minutes. Open the BatchWindow now, so it's the
second button on the Taskbar, as explained in the Introduction ?
You should complete the Introduction (which is really Lesson Zero) first. It shows you how to
create and configure the customized MS-DOS BatchWindow and how to use our specially-
designed multi-window layout.
Remember, you can hover the mouse over ? or purple items to read further details,
and Work Offline if you prefer (click Work Offline for details). And bear in mind that this
Course is for Windows 95/98/ME(click here Windows NT/2000/XP users).
In Lesson 1, we'll cover some groundwork. This will also help you become fluent in using the
multiple Course windows on screen. We shall:
You can click on any item in dark blue (such as ECHO) to read about it in the Course Reference
window. Use it only to review and expand on what you've learnt in a Lesson. Don't try to learn
about new commands from their Reference window details.
A Batch script, also known as a Batch file, is a list of commands. It's executed by a command
processor (a special program). Windows 95/98/ME uses the command
processor COMMAND.COM (which is always installed so Batch files will always run).
Batch scripts must be plain text files, created with a text editor. With a Word Processor, such
as WordPad, which saves files in a special format, you must choose the option:
Save as type : Text documents otherwise your scripts will fail to work.
We shall always use Notepad for our Batch work in this Course. However, unlike
most Notepad files (normally.TXT type), our files will have the extension .BAT – this is how
Windows recognises them as the Batch file type.
NT/2000/XP In Windows NT/2000/XP you can use either .BAT or .CMD as the file
extension. CMD.EXE will interpret either file type. We use only .BAT in the Exercises, since this
will work for both Windows 95/98/ME andWindows NT/2000/XP.
• Click any dark blue term, such as ECHO, to look it up in the Course Reference
• Hover your mouse over any ? symbol, or any term in purple to see an InfoBox
Displaying text:
ECHO displays text messages on the screen
A good script displays clear instructions and progress reports on the screen. The command to
display text is ECHO, and almost all the scripts you write will use it.
Batch scripts are computer programs. And the traditional way to begin writing computer programs
is with a program that says: "Hello World". ECHO is just what we need. First, we'll practise in
immediate mode, in the BatchWindow , then write a simple script.
The Exercise window also repeats the simulated screen images, which show you what you can
expect to see. This is so you can easily compare your results with ours, before you need to
return to this main Lesson window (and lose sight of your results).
The Exercise window is deliberately quite small, to allow you to read it while you work in other
windows open in the main bottom left area of the screen. For this reason, you'll often need to use
the Exercise window scroll bar (that will appear on the right of it) to read all the details. Click the
button now, and follow the instructions (Exercise 1):
ex 1
C:\CSW>_
That line does what we want for our Hello World task, so let's make it into a script. It isn't a script
yet, because we haven't typed it into a file. Our file will need the right Batch file extension, too, so
let's call it HW.BAT for Hello World.
You could call it HelloWorld.BAT if you wished. However, we'll be running the Batch files we
write in this Course by typing their names at the prompt, so we'll keep names short.
A Batch script is just a simple text file, so the Windows Notepad text editor is all you need (feel
free to use your favourite text editor if you prefer, but we'll demonstrate with Notepad because it's
always part of Windows). You can start the Notepad editor with an immediate mode command
from the BatchWindow like this (click Exercise 2now):
ex 2
C:\CSW>_
What happened was that Notepad created an empty file called HW.BAT, in the folder C:\CSW.
Using the startcommand, as here, is neater than opening Notepad from the normal Programs
menu because this command line sets both the filename and folder for our script file.
The Notepad window was minimized (=just a button on the Taskbar). That's because we used
the /min (=minimized) switch of the start command. We did that so the Notepadwindow wouldn't
get in our way for the moment.
If you found that confusing, or got into a tangle with the windows, try it again. To do so properly,
you'll need to delete the HW.BAT file or you won't see the Notepad dialogue box asking if you
want the file created. If you do want to try again:
Our script consists of just one line: ECHO Hello World. It's important when typing scripts to
make sure the last line ends with a Return , otherwise Windows 95/95/ME puts a spurious blank
line on the screen when the script is run. Type the single line in Notepad, making sure you
press Return at the end, like this (Exercise 3):
ex 3
Note You must remember to click File, Save in Notepad to save any change we make. If you
prefer, you can use Alt + F , S (=hold down Alt while you press F key, release both, then
press S key). This is the keyboard alternative to the mouse method.
Unlike our BatchWindow Shortcut, Notepad doesn't store its last-used window position, so keep
it open during the Lesson, then you won't have to re-position it to read from
the Exercise window.
Don't use Notepad maximized (where its window would fill the display) or you won't be able to
read the notes in the Exercise window.
We've saved the script as HW.BAT. To run any .BAT script, we can just type its name at the
prompt in the BatchWindow . Try it now. This is what you'll see (Exercise 4):
ex 4
C:\CSW>hw
C:\CSW>
C:\CSW>_
Note We didn't add the .BAT extension, it's optional here. You would need to add the extension
if there were filesHW.COM or HW.EXE in our CSW folder, since .COM and .EXE files take
precedence with COMMAND.COM. In that case, we could specify
name and extension: hw.bat so as to ensure it was our Batch script that ran.
Our "Hello World" is in there, but amidst a lot of other clutter, too. When Windows runs our script,
it displays each command in turn, then executes it. This is very useful when we're debugging
scripts, but it makes a mess on screen. We need to turn off echoing.
Remember that you can get brief help with most Batch commands by using the help switch (/?).
Try using it withECHO in the BatchWindow now (Exercise 5):
ex 5
C:\CSW>echo /?
Displays messages, or turns command-echoing on or off.
C:\CSW>_
As well as echoing text to screen, ECHO will turn off (and on) the display of commands in a Batch
file. Windows always starts with command ECHO turned on. ECHO OFF will turn it off. In
immediate mode, ECHO OFFsuppresses the prompt that you normally see on
screen.
Try that now. In the BatchWindow , type echo off, then press Return a few times. The prompt
is no longer displayed. Then type echo on to restore normality (Exercise 6):
ex 6
C:\CSW>echo off
echo on
C:\CSW>_
ex 7
ECHO OFF
ECHO Hello World
Note The de-emphasized text such as this in the simulation marks the text already there,
so that you can see clearly exactly where your new text goes.
With the change saved, run HW.BAT in the BatchWindow once more (Exercise 8):
ex 8
C:\CSW>hw
C:\CSW>ECHO OFF
Hello World
C:\CSW>_
NT/2000/XP You may see an extra blank line displayed before the prompt returns in Exercise
8 above, andExercise 10 (and following Exercises) below.
This is better, but the ECHO OFF command itself still shows on screen. Its effect only applies to
the lines thatfollow it. You can turn off display of a single line by typing the line with an @ prefix.
So let's fix the problem in our script like this (Exercise 9):
ex 9
@ECHO OFF
ECHO Hello World
With the change saved, run HW.BAT in the BatchWindow once again (Exercise 10):
ex 10
C:\CSW>hw
Hello World
C:\CSW>_
However, while using @ to prefix each line is fine for a tiny script, we shall soon be writing longer
ones.
Most of our scripts will start with @ECHO OFF to prevent the display of each line of the script as
it runs. Of course, while you are debugging a script, it can be useful not to use @ECHO OFF.
Then, if there is a problem with the script, you will see what line is being executed when the
problem occurs.
In debugging longer scripts, you can start with @ECHO OFF, then use the command ECHO
ON later, at any point, to turn on display of subsequent lines of the script as it runs. We don't
need the @ prefix for the ECHO ON, since it affects only subsequent lines, and we would use it
only when echoing was already off.
Used on its own, the ECHO command simply reports whether echoing (displaying) of script lines
is currently on or off. Try it now, it will report that ECHO is on (Exercise 11):
ex 11
C:\CSW>echo
ECHO is on
C:\CSW>_
By the way, when you are working in immediate mode, and you want to clear previous work
cluttering the screen, use the command CLS (clear screen). You'll find that clearing the screen
from time to time makes it easier to work in a DVM window. It's probably about time you did
so (Exercise 12):
ex 12
C:\CSW>cls
C:\CSW>_
Note The simulation shows you the effect, both before and after the CLS command.
As we've seen, ECHO is used both for changing and reporting the echo state, and for displaying
text. In Windows 95/98/ME, these roles may conflict. Let's use Notepad to make a new script
called HIGHNOON.BAT and see what can happen (Exercise 13):
ex 13
@ECHO OFF
ECHO Do not forsake me, Oh my darling
ECHO On this our wedding day.
Did you remember to press Return at the end of the final line? And to make sure the new file
was saved in theC:\CSW folder?
NT/2000/XP The ECHO command doesn't suffer from the conflict Windows 95/98/ME users
will see inExercise 14 – Exercise 16 but you should work through anyway, so you will be aware of
the problem should you need to use Windows 95/98/ME systems.
Care When using Notepad, be careful about file types when you
save .BAT files. Notepad would normally add a spurious extra .TXT extension if we saved our
script as type Text Documents (the script would then fail to work until we renamed it properly).
You might have noticed that this didn't happen when we saved HIGHNOON.BAT in Exercise 13,
even though we left the Save as type : Text documents. This was because we had previously
opened Notepad with a .BAT file when we started.
Notepad remembers an extension already used in the current session (while you keep its window
open) and doesn't append a spurious .TXT to it (however, just to be sure, make certain
there isn't a spurious extra .TXT extension added to HIGHNOON.BAT)
If you're unsure when saving a file with Notepad, you can avoid a spurious .TXT extension being
added if you:
• Set the Save as type : pull-down box to All files (*.*) before saving the file (this will work
only for registered file extensions)
• Enclose the filename in "quotes" (this works for all file extensions, whether or not they're
registered in HKEY_CLASSES_ROOT in the registry)
With changes saved, try running HIGHNOON.BAT to see what happens (Exercise 14):
ex 14
C:\CSW>highnoon
Do not forsake me, Oh my darling
ON
C:\CSW>_
NT/2000/XP You won't see this conflict in Windows NT/2000/XP, both lines will display
correctly. However, it's worth being aware of the problem, in case you need to write Batch files
meant to run under Windows 95/98/ME andWindows NT/2000/XP
The initial word "On" produced a conflict
@ECHO OFF
ECHO Do not forsake me, Oh my darling
ECHO On this our wedding day
The last line produces an error because it starts with the word On, which is one of
the ECHO commands (a line of text starting with Off would also produce an error). In fact the
faulty line doesn't even turn echo on, it just writes a spurious ON. This is because any other text
following an ON or OFF instruction for ECHO produces confusion.
The standard way to separate ECHO from the following text to be displayed is with a Space . The
first Space following ECHO is always ignored (so if you need your displayed text indented by
say, five Space s, you must put six Space s in your script)
There are eleven other special characters you can use immediately after ECHO that, just like the
first Space , are not themselves echoed.
The first four work like a Space : they don't stop the action of a following ON or OFF. However,
any of the last seven stop these words being treated specially (this is exactly
what HIGHNOON.BAT needs). The usual one to use is the Period , thus ECHO.
Instead of trying to remember to use a Period whenever our ECHO text begins with an on or off,
we'll always useECHO. whenever we display text. The only time we won't use it is when we really
do want to turn echo on or off.
Now let's alter our HIGHNOON.BAT script by using ECHO. each time we merely display text.
Change it to this(Exercise 15):
ex 15
@ECHO OFF
ECHO.Do not forsake me, Oh my darling
ECHO.On this our wedding day.
ex 16
C:\CSW>highnoon
Do not forsake me, Oh my darling
On this our wedding day.
C:\CSW>_
Remember, the initial Period is not displayed, it just ensures that the rest of the line is treated as
ordinary text. You can use ECHO. on a line alone to create a blank line on screen. This is often
useful in scripts to break up text and make screen output clearer. Let's try that in
our HIGHNOON.BAT script. We'll make a blank line display both above and below the two text
lines; make the changes in Notepad (Exercise 17):
ex 17
@ECHO OFF
ECHO.
ECHO.Do not forsake me, Oh my darling
ECHO.On this our wedding day.
ECHO.
Did you remember to press Return after you added the second ECHO.? If you didn't, do so now.
It is the (new) last line of the script, and a script should always end with a properly terminated
line, one that ends with a Return . You don't need to add any further blank lines afterwards, it's
sufficient that the last line of every script is properly terminated (this prevents a spurious blank
line in the display when the script runs).
With changes saved, run the script a last time (Exercise 18):
ex 18
C:\CSW>highnoon
C:\CSW>_
That's enough ECHOing for now. When you've completed Exercise 18, use the CLS command in
the BatchWindow to clear the DVM screen.
Variables:
Stored in environment
In the second half of this Lesson, we'll learn to use Environment Variables. These are a way of
storing small pieces of text in a special area of memory called the environment. They are much
simpler than the variables in most programming languages; there are only three principal things
you can do with them:
Nevertheless, they are the basis of many powerful script techniques. Any variable you set in
a DVM normally retains its value until it's cleared, or reset, or you end your current DVM session
(close the DVM window).
Setting a variable
A variable name can contain most normal characters, including letters and digits; but you should
avoid variable names starting with a digit, they conflict with replaceable parameters (which we
shall learn about in later Lessons). To set a variable named SRC to, say C:\BKTEST (a
foldername we shall later use for testing), you useSET in the DVM window like this (Exercise 19):
ex 19
C:\CSW>set src=C:\BKTEST
C:\CSW>_
Expanding a variable
The name of the variable, src, is changed to uppercase as it's stored, so it doesn't matter
whether you use upper or lowercase in the SET command. However the case of letters in the
contents (the part on the right of the = sign) is preserved.
In our scripts, we'll always use uppercase for variable names to help them stand out:
eg SRC (this is just a convention). We don't bother when simply working at the prompt.
To make use of the current contents of a variable, that is, to expand the variable contents, you
surround the name with % characters. To expand the variable we have just set, src, you would
type %src%. When you type %src% at the prompt (or in a script), it's as if you had used the exact
text stored in the variable. Try it (Exercise 20):
ex 20
C:\CSW>_
This is useful where, say, a foldername is going to be used many times throughout a script. We
can set it in a variable once at the start, then use the variable throughout the script. If we want to
change the folder later, we need only change the initial assignment.
Storing messages
Variables are often used to store messages, for example (Exercise 21):
ex 21
C:\CSW>_
Now try using the message, by expanding the variable, like this (Exercise 22):
ex 22
C:\CSW>echo.%task% - finished
Build fresh test folder - finished
C:\CSW>_
Global variables
Environment variables can be set in the Windows startup files; then they're available whenever
you open a DVMwindow. These are called global variables (there is also a utility, WINSET.EXE,
provided on the standard Windows CD-ROM, to set global variables). Windows normally sets
some important global variables for you:
winbootdir
The path to your windows folder, set in real-mode and in the Windows GUI. Usually set
to C:\WINDOWS; this setting is taken from the file MSDOS.SYS.
COMSPEC
The path to COMMAND.COM, the command processor that runs our .BAT scripts. It's
usually set toC:\WINDOWS\COMMAND.COM in Win95/98/ME
NT/2000/XP COMSPEC usually set to C:\WINDOWS\SYSTEM32\CMD.EXE
PATH
If you ask to run a program (or a script), Windows searches certain folders for it by
default. The list of foldernames Windows searches is set in the PATH variable, with
a ; between each, usually:C:\WINDOWS;C:\WINDOWS\COMMAND
NT/2000/XP PATH will include C:\WINDOWS;C:\WINDOWS\SYSTEM32
TEMP
The path to the temporary folder. It's usually set to C:\WINDOWS\TEMP
PROMPT
This specifies how the prompt looks. Usually set to $p$g. The $p means display current
drive and path tocurrent folder, and $g means display a > symbol
windir
The path to your windows folder, set only in the Windows GUI. Usually set
to C:\WINDOWS
You'll often see another variable. Unlike the global variables above, however, it's transient, and
local to your DVM:
CMDLINE
Holds the last command line used for an external command. This may be a command
you typed in immediate mode, or one used in a script. Any internal commands you
use don't set CMDLINE, so it will probably still be set to: CMDLINE=start /min notepad
HW.BAT (start is an external command).
NT/2000/XP start is an internal command, so it won't affect CMDLINE
Note CMDLINE is allocated a separate memory region by Windows, so it doesn't take up your
precious environment space. Therefore, unlike other variables created transiently, there's no
need to clear it.
As we said, names of variables you set with the SET command are always forced to uppercase.
However, Windows sets the two variables winbootdir and windir with lowercase names. In
Windows 95/98/ME, the SET command willnot clear variables whose names contain any
lowercase letters (so they are write-protected).
You can list all the variables currently set (including the global ones) by using the SET command
on its own. Try it now (Exercise 23):
ex 23
C:\CSW>set
winbootdir=C:\WINDOWS
COMSPEC=C:\WINDOWS\COMMAND.COM
PATH=C:\WINDOWS;C:\WINDOWS\COMMAND
TEMP=C:\WINDOWS\TEMP
PROMPT=$p$g
windir=C:\WINDOWS
CMDLINE=start /min notepad HW.BAT
SRC=C:\BKTEST
TASK=Build fresh test folder
C:\CSW>_
The first six shown are the usual system variables. You may have more listed (or some set to
different values). The two we've just set are at the end of the list: SRC and TASK.
If you have a printer attached to your system, and you want to print out a complicated screenful of
text (such as the variables' listing above) from the BatchWindow , click on
the BatchWindow button on the Taskbar (so that it's the window with focus), and press the key
combination Shift + PrintScrn . This works for any DVM window.
Now try clearing one of the variables we set. You simply set it to nothing. Make sure you don't put
a space after the = sign. Clear the variable TASK like this (Exercise 24):
ex 24
C:\CSW>set task=
C:\CSW>_
ex 25
C:\CSW>set
winbootdir=C:\WINDOWS
COMSPEC=C:\WINDOWS\COMMAND.COM
PATH=C:\WINDOWS;C:\WINDOWS\COMMAND
TEMP=C:\WINDOWS\TEMP
PROMPT=$p$g
windir=C:\WINDOWS
CMDLINE=start /min notepad HW.BAT
SRC=C:\BKTEST
C:\CSW>_
If you use a variable that is clear, Windows treats it as if you typed nothing at all. Try using
our TASK message again (Exercise 26):
ex 26
C:\CSW>echo.%task% - finished
- finished
C:\CSW>_
NT/2000/XP When you expand the undefined variable in Windows NT/2000/XP, you see
literal text instead of a blank space: %task% - finished
Now clear the SRC variable in the same way (Exercise 27):
ex 27
C:\CSW>set src=
C:\CSW>_
Now list the variables that are set again, and check that SRC has been cleared from the current
list (Exercise 28):
ex 28
C:\CSW>set
winbootdir=C:\WINDOWS
COMSPEC=C:\WINDOWS\COMMAND.COM
PATH=C:\WINDOWS;C:\WINDOWS\COMMAND
TEMP=C:\WINDOWS\TEMP
PROMPT=$p$g
windir=C:\WINDOWS
CMDLINE=start /min notepad HW.BAT
C:\CSW>_
Remember, there may be other variables set on your system than the standard ones we list here,
and some of your standard variable contents may differ slightly from this list.
The point of these standard variables is that your scripts can use, say the temporary folder, by
referring to %TEMP%, without having to worry exactly what folder it is.
If you do this, your scripts will run properly on other people's machines that may have the
temporary folder in a different location. This is important, because we shall use this folder for
most of our transient working files.
Variable names (and their contents) can contain Space s, but beware of accidents! For example:
we'll set a variable called Norma Jean to the text value Marilyn Monroe. But, we'll make a
mistake (trying to be neat) and leave a Space either side of the = sign when we assign the
variable (Exercise 29):
ex 29
C:\CSW>_
The text value now includes an initial Space thus: Marilyn Monroe. That's not really a
problem, we may even want it that way. However the variable name now includes a final space,
thus Norma Jean , and it's easy to miss this detail.
If you didn't notice, or forgot, and tried to use the variable name without its accidental
trailing Space , it wouldn't work (Exercise 30):
ex 30
C:\CSW>_
NT/2000/XP When you expand the undefined variable in Windows NT/2000/XP, you see
literal text instead of a blank space: Goodbye %norma jean%
There is no variable with that name, so we draw a blank. Check the variable list with a
plain SET command(Exercise 31):
ex 31
C:\CSW>set
winbootdir=C:\WINDOWS
COMSPEC=C:\WINDOWS\COMMAND.COM
PATH=C:\WINDOWS;C:\WINDOWS\COMMAND
TEMP=C:\WINDOWS\TEMP
PROMPT=$p$g
windir=C:\WINDOWS
CMDLINE=start /min notepad HW.BAT
NORMA JEAN = Marilyn Monroe
C:\CSW>_
The SET list shows that the NORMA JEAN variable name includes a Space at the end: you
must include it in the name in order to use the variable, like this (Exercise 32):
ex 32
C:\CSW>_
Note 1 Any leading Space s typed before the variable name don't matter, since SET always
ignores them.
Note 2 Any Space s in the variable content (to the right of the = ) are part of its
content, including Space s at the end of the line.
Let's clear Ms Baker now. Don't forget the Space before the = sign (Exercise 33):
ex 33
C:\CSW>_
ex 34
C:\CSW>set
winbootdir=C:\WINDOWS
COMSPEC=C:\WINDOWS\COMMAND.COM
PATH=C:\WINDOWS;C:\WINDOWS\COMMAND
TEMP=C:\WINDOWS\TEMP
PROMPT=$p$g
windir=C:\WINDOWS
CMDLINE=start /min notepad HW.BAT
C:\CSW>_
We'll take our cue from Norma Jean, and take our leave for this Lesson, too.