Microsoft Windows Shell Script Programming For The Absolute Beginner
Microsoft Windows Shell Script Programming For The Absolute Beginner
Windows ®
Shell Script
Programming
™
This page intentionally left blank
Microsoft ®
Windows ®
Shell Script
Programming
™
04 05 06 07 08 BH 10 9 8 7 6 5 4 3 2 1
A
number of individuals deserve credit for their work on this book. I especially
want to thank Todd Jensen, who served as the book’s acquisitions editor
and who has worked with me on numerous other writing projects. I also
want to thank the book’s project editor and copy editor, Dan Foster, for his guid-
ance and suggestions. Finally, I want to acknowledge the book’s technical editor
and CD-ROM developer, Keith Davenport, as well as everyone else at Premier Press
for all their hard work.
About the Author
J
erry Lee Ford, Jr. is an author, educator, and IT professional with over 15
years of experience in information technology, including roles as an
automation analyst, technical manager, technical support analyst, auto-
mation engineer, and security analyst. Jerry is a MCSE and has earned Microsoft’s
MCP and MCP+ Internet certifications. In addition, he has a master’s degree in Busi-
ness Administration from Virginia Commonwealth University in Richmond, Virginia.
Jerry is the author of 12 other books, including Learn JavaScript in a Weekend,
Learn VBScript in a Weekend, Microsoft Windows Shell Scripting and WSH
Administrator’s Guide, VBScript Professional Projects, and Microsoft Windows XP
Professional Administrator’s Guide.
He has over 5 years of experience as an adjunct instructor teaching networking
courses in Information Technology. Jerry lives in Richmond, Virginia, with his wife,
Mary, and their children, William, Alexander, and Molly.
Contents at a
Glance
Introduction xvii
Glossary 355
Index 365
Contents
1
CHAPTER Introducing
Windows Shell Scripting
Project Preview: The Knock Knock Joke ..................................... 2
Overview of Windows Shell Scripting ........................................ 4
1
2
CHAPTER Interacting with
the Windows Shell
Project Preview: The Unpredictable Command Prompt .......... 26
Command Shell Command Syntax ........................................... 27
25
3
CHAPTER Windows Shell Scripting
Basics
Project Preview: The Fortune Teller Game ................................ 58
57
Contents
Generating Random Answers ................................................ 77
Displaying the Fortune Teller’s Prediction ............................ 78
Replaying the Game ............................................................... 79
The Final Result ....................................................................... 79
Summary ..................................................................................... 85
4
CHAPTER Storing and Retrieving
Information in Variables 87
Project Preview: The Story of Buzz the Wonder Dog ............... 88
Passing Data to Scripts at Execution Time ................................ 90
Handling Large Numbers of Arguments ............................... 92
Handling Arguments That Include Blank Spaces ................. 93
Working with Variables ............................................................... 93
Accessing Environment Variables ......................................... 94
Creating, Modifying, and Deleting Script Variables ............. 98
Back to “The Story of Buzz the Wonder Dog” ........................ 105
Designing the Game ............................................................. 105
Configuring the Windows Command Console ................... 105
Building the Welcome Screen ............................................. 106
Providing the Reader with Instructions ............................... 107
Collecting Key Story Elements from the Reader ................ 108
Using Variable Substitution to Write the Story .................. 109
The Final Result ..................................................................... 111
Summary ................................................................................... 122
5
CHAPTER Applying Conditional Logic 123
Project Preview: The Guess a Number Game ........................ 124
Applying Conditional Logic to Control Script Execution ....... 126
Working with the IF Statement ............................................ 126
Providing for an Alternative Course of Action ................... 129
Determining Whether a Variable Already Exists ................ 129
xii
Keeping an Eye Out for Errors ............................................. 130
Contents
6
CHAPTER Creating Loops to Process
Collections of Data
Project Preview: The Six-Million-Dollar Quiz .......................... 156
155
7
CHAPTER Creating Procedures
and Subroutines
Project Preview: The Rock, Paper, Scissors Game ................. 202
Reorganizing Your Windows Shell Scripts ............................. 204
201
xiii
Understanding Labels .......................................................... 204
Contents
Defining Subroutines ............................................................ 204
Improving Script Organization with Procedures .................... 208
Setting Up Internal Procedures ........................................... 208
Creating External Procedures .............................................. 212
Using Procedures to Localize Variable Access ................... 216
Tunneling Data Out of Your Procedures ............................. 217
Back to the Rock, Paper, Scissors Game ................................. 218
Using a Flowchart as a Script Development Tool .............. 218
Translating Flowchart Design
into Script Requirements ..................................................... 221
The Final Result ..................................................................... 230
Summary ................................................................................... 239
8
CHAPTER Debugging and
Error Handling
Project Preview: The Tic-Tac-Toe Game .................................. 242
Understanding Windows Shell Script Errors .......................... 244
241
A
APPENDIX Windows Shell Scripting
Administrative Scripts 297
Working with Network Drives .................................................. 298
Account Administration ............................................................ 305
Disk Defragmentation ............................................................... 312
Scheduling Script Execution .................................................... 315
The AT Command ................................................................. 315
The Scheduled Task Wizard ................................................. 320
Starting the Task Scheduler Service .................................... 321
Running the Scheduled Task Wizard ................................... 321
Creating a Chat Script ............................................................... 324
Adding a Graphical Interface ................................................... 330
Working with Third-Party Applications ................................... 334
B
APPENDIX What’s on the CD-ROM?
Windows Shell Scripting Examples ........................................ 342
341
C
What Next? 349
Contents
APPENDIX
A
t some point, you’ve probably begun to want more control of your
computer. You may want to make programs act a little bit differently
than the default behavior, automate tedious tasks, or perform certain
jobs automatically. Ultimately, such tasks come down to programming. The pro-
gramming world can be very intimidating, with all the integrated environments,
complex languages, and dizzying variety of resources. Programming looks hard,
and, frankly, it looks boring.
In this book, Jerry Lee Ford will show you how to control your computer in amaz-
ing ways. You’ll learn some relatively easy tricks that will profoundly improve the
way you work with your computer, and you’ll learn the basics of the programming
art along the way. Windows shell scripting is not the most complex programming
environment, and that’s a major part of its charm. This reasonably clean language
is ideal for beginners precisely because it is so focused.
While shell scripting is extremely useful, that doesn’t mean learning about it has
to be dry and boring. Like all the books in this series, this book teaches through
simple game programming. Nobody’s going to use Windows shell scripting to write
the next immersive 3-D action game, but games can be an interesting way to learn
about the process of writing more traditional programs. Don’t worry, there will be
lots of practical examples as you go through this book.
If you’re new to programming, you won’t find a better place to start than this
book. If you’re already an experienced programmer, you’ll be amazed at how you
can use the skills in this book to leverage your abilities. Regardless, you’ll learn a
lot and have a good time doing it.
Andy Harris
For the Absolute Beginner Series Editor
Introduction
W
indows shell scripting is a built-in scripting language found on modern
Windows operating systems. It provides the ability to create and run small
programs or Windows script files made up of Windows shell script state-
ments and Windows commands. Windows shell scripts are created as plain text
files that are saved with .bat or .cmd file extensions and run from the Windows
command prompt.
Windows shell scripts are often small files that can be created and tested within
minutes. In fact, many good Windows shell scripts are less than 10 or 15 lines long.
This makes it a perfect language for quickly automating Windows tasks. This also
makes Windows shell scripting a great first language to learn.
Unlike many modern program languages, Windows shell scripting is not object ori-
ented. In addition, it does not require you to first learn how to operate a complex
development environment. However, Windows shell scripting does have a complete
collection of statements—the elements that make up its programming language.
This allows first-time programmers to focus on learning the basics of program de-
sign without being burdened with the added requirements imposed by many other
programming languages.
Windows shell scripts also provide a way to automate complex tasks, especially those
prone to human error. Once created, Windows shell scripts can be shared with other
people, allowing you to distribute and share your work. Using Windows shell scripts,
you can access and manipulate Windows resources such as the Windows file system
and disk and printer resources, and you can even automate the execution of net-
work tasks. In addition, as this book will demonstrate, you can create Windows shell
scripts that automate and control the execution of all kinds of things. For example,
this book will show you how to create Windows shell scripts that
• Play computer games like Rock, Paper, Scissors and Tic-Tac-Toe.
• Copy and move files and folders.
• Establish connections to network resources such as network disk drives
and folders.
• Create text reports and log files.
xviii
• Execute Windows utilities such as the Windows Disk Defragmenter.
Introduction
Introduction
To use this book effectively, you will need a number of things. First, you will need
a Windows operating system that supports Windows shell scripting. These operat-
ing systems include
• Windows NT 4.0
• Windows 2000
• Windows XP
• Windows 2003
You will also need an editor that supports the creation of plain text files. As a
starter editor, you can begin working with the Windows Notepad text editor. How-
ever, over time you will probably find that Notepad is rather limited, and you
will want to use a more advanced editor that supports features like syntax color-
coding and advanced search-and-replace features. To help you out, I have included
two excellent editors on this book’s companion CD-ROM. To learn more about these
two editors, check out Appendix B, “What’s on the CD-ROM?”
Introduction
a number between 1 and 32,000 using the fewest possible guesses.
• Chapter 6—Creating Loops to Process Collections of Data. This chapter covers
the creation of loops as a means of processing large amounts of data. It will
demonstrate how to use loops to process string contents, command output,
and file and folder contents. This chapter also introduces you to the use of
pseudo code as a tool for establishing a high-level script design. This chapter
ends by teaching you how to create the Six-Million-Dollar Quiz game. In this
game, the player is presented with a series of quiz questions that, once an-
swered, are graded and used to generate a game score card report file.
• Chapter 7—Creating Procedures and Subroutines. This chapter introduces
you to the use of flowcharts as a design tool. It also shows you how to execute
one script from within another script. The chapter also covers the use of pro-
cedures and subroutines, which enable you to improve script organization
while also reducing complexity. This chapter concludes by covering the devel-
opment of the Rock, Paper, Scissors game.
• Chapter 8—Debugging and Error Handling. In this final chapter, I’ll intro-
duce you to a number of different topics. I’ll give you tips on how to develop
your script in a modular fashion and how to test your scripts one module at a
time. You’ll also learn how to test intermediate results during script develop-
ment and testing. Things constantly change on a computer system, and as a
result your scripts may break or experience problems over time. To deal with
these situations, I’ll provide you with some basic debugging techniques and
give you advice that will help you to detect and deal with script errors. This
chapter will end by stepping you through the development of one final game
project called Tic-Tac-Toe.
• Appendix A—Windows Shell Scripting Administrative Scripts. This appendix
provides you with a collection of practical examples that demonstrate the use
of Windows shell scripting in real-world situations. I included this appendix
to assist you in making a transition from the book’s game-based approach to
real-world script development.
• Appendix B—What’s on the CD-ROM? In this appendix, I’ll supply you with
information about the sample scripts that you will find on the book’s accom-
panying CD-ROM. I’ll also provide you with a freeware copy of the EditPad Lite
text editor and a shareware copy of the EditPad Pro text editor along with a
brief overview of what these two editors can do.
• Appendix C—What Next? In this appendix, I give you advice on how to continue
your Windows shell scripting education. I’ll include references to other books
that I think you will find useful, and I’ll also provide you with information about
xxii
a number of Web sites where you’ll find more information, including plenty
Introduction
HINT As you read along, I’ll offer suggestions for different or better ways of doing things
that will help make you a better and more efficient programmer.
P
TRA I’ll also point out places where it’s easy to make mistakes, and I’ll give you advice
for avoiding them.
K
TRIC Whenever possible, I’ll share shortcuts and techniques that will make things easier
for you.
ION
INIT To aid your understanding, I’ll define key terms along the way. (You can also refer to
DEF
the glossary in this book for additional information.)
I N T HE R EAL W ORLD
Throughout the book, I’ll stop along the way to point out how the knowledge and
techniques you are learning can be applied to real-world scripting projects.
EXERCISES
At the end of every chapter, I’ll include a collection of small project suggestions that
you can do to continue building on the skills you’ve learned.
Introducing
1
C H A P T E R
Windows Shell
Scripting
W
indows shell scripting is one of two scripting solutions provided by Microsoft
for developing small programs, or scripts, that automate a variety of tasks on
Windows computers. (The other scripting solution is known as the Microsoft Win-
dows Script Host, or WSH.) Scripts provide a means of developing small utility programs that
automate mundane or complex tasks with a minimal investment of time and effort.
Windows shell scripting provides a way to perform tasks on Windows computers with-
out requiring you to wade though the array of windows and dialogs boxes that make
up the Windows graphical user interface, or GUI. Scripts help to eliminate typing mis-
takes or other errors that often occur when you perform a task manually. Therefore,
scripts not only help you work faster but more accurately as well, especially when
you’re working on tasks comprised of a large number of steps. In this chapter, I’ll intro-
duce you to Windows shell scripting and provide you with the background information
you’ll need for the rest of the book. In addition, I’ll show you how to develop your first
Windows shell script game.
Specifically, you will learn
• The capabilities of Windows shell scripts
• The history of Windows shell scripting
• The differences between Windows shell scripts and the Windows Script Host
• How to configure the script development and testing environment
2
Windows Shell Script Programming for the Absolute Beginner
ION
INIT The Windows command prompt appears, by default, in the form of a drive letter
DEF
followed by a colon, the backslash character, and then the “greater than” symbol
(for example, C:\>). The command prompt accepts text input that is passed to the
operating system for processing.
Finally, the script displays the joke’s punch line as shown in Figure 1.3. If the player
makes a typo when entering one of the required responses to the joke, one of the
two messages shown in Figure 1.4 and 1.5 will be displayed.
FIGURE 1.1
FIGURE 1.3
The game
delivers the joke’s
punch line.
FIGURE 1.4
FIGURE 1.5
With incorrect
player input, the
game may
prematurely exit and
generate an error
message.
4
Don’t worry about trying to understand every line of code that you’ll type into the
Windows Shell Script Programming for the Absolute Beginner
script; you’ll learn what everything means as you read through this book. The
important thing to learn in this chapter are the steps involved in creating and
saving your first script. By completing this script, you will prepare yourself for the
more advanced programming concepts introduced in later chapters.
ION
INIT The term conditional logic refers to a script’s ability to examine data and then adjust
DEF
what it does based on the results of a conditional analysis.
ION
INIT The term iterative logic refers to a script’s ability to repeatedly execute a series of
DEF
steps over and over again.
ION
INIT A statement is a line of code. Most statements fit on a single line; however, lengthy
DEF
statements can be spread over multiple lines.
Microsoft has since added support for Windows shell scripting to all Windows
operating systems that have been built on Windows NT technology (e.g., Windows
2000, XP, and 2003).
HINT While the collection of programming statements that make up the Windows shell
script language has remained essentially the same over the years, a few of the state-
ments have been modified to extend their functionality. Rather than attempt to iden-
tify and examine differences in Windows shell scripting statements between each
of the different Windows operating systems, this book uses Windows XP as its as-
sumed development platform.
If you plan on writing scripts that will be executed by older Windows operating
systems, you should retest the scripts on each operating system to make sure that
they work as you expect them to. In addition, you can check any Windows command’s
syntax to see what syntax it supports on a given operating system by accessing the
Windows command prompt and typing the name of the command followed by a space
and the word HELP.
Windows shell scripts are saved with a .bat (“batch”) or .cmd (“command”) file
extension. This way, when the operating system is asked to run them, it will know
to execute them using the Windows shell.
ION
INIT The .cmd file extension is another file extension that Windows associates with
DEF
Windows shell scripts.
6
What Can Shell Scripts Do?
Windows Shell Script Programming for the Absolute Beginner
Windows shell scripts can accomplish any task that can be completed from the
Windows command prompt. Despite continual efforts to improve the Windows
graphical user interface and to make things easier for users by providing only a
complete point-and-click experience, Microsoft has continued to update and ex-
pand the Windows command line functionality (e.g., each new Windows operat-
ing system adds new commands and refines existing commands).
Microsoft also adds command line access to many of its utility programs, allowing
them to be accessed and controlled by scripts. For example, the Defragmenter util-
ity (which reorganizes files stored on your disk drive for more efficient storage)
can be run from the Windows graphical user interface on Windows XP by select-
ing Start, All Programs, Accessories, System Tools, and then Disk Defragmenter. Alterna-
tively, you can execute this utility program from within a Windows shell script.
For example, by typing defrag C: /f you can automate the defragmentation of your
computer’s C drive using this utility.
Windows shell scripts can be used to automate all of the following categories of tasks:
• Complicated tasks. This category of scripted tasks includes any tasks that are
highly subject to error when performed manually, such as the administration
of system resources like disk drives and printers.
• Repetitive tasks. These scripted tasks include any tasks that must be per-
formed over and over again, such as the deletion of certain file types from spe-
cific folders on a regular basis.
• Lengthy tasks. These scripted tasks include any tasks that take too long to per-
form manually, such as the creation of a few hundred new user accounts.
• Scheduled tasks. These scripted tasks include any tasks that must be run dur-
ing off hours, at times when users and administrators are not using their
computers (such as the Disk Defragmenter utility).
You can develop Windows shell scripts that perform an assortment of different
tasks on Windows computers. Once completed, these scripts will help you work
faster and be more productive. For example, using Windows shell scripts, you can
• Collect and display information about your computer
• Manage Windows services
• Manage shared folders and drives
• Automate the creation of new user accounts
• Create output files and reports
• Process data stored in input files
7
• Create and manage scheduled tasks
ION
INIT The term execution environment refers to the grouping of resources that scripts re-
DEF
quire in order to execute, such as a script interpreter that translates script state-
ments into instructions that the computer can execute.
8
WSH Advantages and Disadvantages
Windows Shell Script Programming for the Absolute Beginner
When deciding whether it is better to use Windows shell scripting or the WSH to
automate a task, there are a number of criteria to consider. WSH provides a more
comprehensive execution environment with direct access to many resources that
are not directly accessible to Windows shell scripts. For example, a WSH script can
write messages to Windows event logs or read and write to the Windows registry.
Therefore, if your scripts will need to access these resources, using the WSH may
make more sense. However, a great many tasks never require access to such re-
sources, thus negating these WSH advantages.
ION The Windows application event log is a log file maintained by the Windows NT,
INIT
DEF
2000, XP, and 2003 operating systems where application errors and messages are
recorded for later audit and review.
ION
INIT The Windows registry is a special built-in database that is a part of all Windows
DEF
operating systems, starting with Windows 95, where configuration information is
stored regarding system, application, hardware, and users settings.
To use the WSH you need to know how to write scripts using at least one scripting
language, such as VBScript or JScript. You also have to learn how to work with the
WSH execution environment.
Typically, it makes more sense to use the WSH to create scripts when
• You have expertise with another scripting language such as VBScript or
JScript and need access to a programming feature provided by these lan-
guages only
• You need to run your scripts on Windows operating systems other than Win-
dows NT, 2000, XP, and 2003
I N T HE R EAL W ORLD
If you have access to the Windows Resource Kit for the operating systems for which
you are developing scripts, you can often use command line utilities provided by the
Resource Kit to indirectly access system resources. For example, using the LOGEVENT
command line utility you can write to the Windows application event log from within
a Windows shell script. Similarly, using the REG command line utility, you can access
and change information stored in the Windows registry. To learn more about Win-
dows Resource Kits, visit www.microsoft.com/windows/reskits/default.asp.
9
• You cannot find a Windows or Resource Kit command or command line util-
WSH Complexities
In order to write scripts that work with the WSH, you must first learn how to write
scripts using a WSH supported scripting language. By default, the WSH provides
support for VBScript and JScript. VBScript is a scripting language that consists of a
subset of the Visual Basic programming language. JScript is Microsoft’s WSH-com-
patible version of Netscape’s JavaScript scripting language. In addition, you can
use third-party WSH-compatible scripting languages that allow the WSH to run
scripts written in the Perl, Python, and REXX scripting languages.
Unlike Windows shell scripts, these other scripting languages involve learning how
to use language-specific statements and commands, many of which are not very
Windows like. Therefore it takes longer to master these languages. In addition to
learning how to develop scripts using a different scripting language, you must also
learn how to work with the WSH object model in order to develop WSH scripts. The
WSH core object model provides access to Windows resources such as printers, drives,
files, and folders by representing them as objects that scripts can access and ma-
nipulate programmatically. The WSH object model is complex and requires a great
deal of time and effort to master. First-time programmers are better off learning
how to write Windows shell scripts. The Windows shell scripting language uses fa-
miliar Windows commands and does not require mastery of an object model, thus
allowing first-time programmers to focus on learning core programming concepts
10
and logic without the requirement of learning advanced concepts. In addition, Win-
Windows Shell Script Programming for the Absolute Beginner
dows shell scripting provides an excellent platform for jumping over to other more
advanced scripting and programming languages.
FIGURE 1.6
FIGURE 1.7
The Windows
console provides
access to the
Windows command
prompt.
HINT You can also start up a new Windows command console session by clicking on
Start, Run, and then typing CMD and clicking on OK.
HINT I’ll show you how to configure the Windows console in Chapter 2, “Interacting
with the Windows Shell.” If you can’t wait to see how it’s done, then jump ahead
to Chapter 2 and read “Customizing the Windows Command Console.”
12
To send a command to the Windows shell for processing, type it in at the com-
Windows Shell Script Programming for the Absolute Beginner
mand prompt and press the Enter key. For example, to display the contents of the
current working directory, type DIR and press Enter.
The Windows shell then translates the DIR command into a format that the operat-
ing system can understand. The operating system processes the command by put-
ting together a list of the contents of the current working directory, which it then
passes back to the Windows shell. The Windows shell displays the listing in the
Windows command console. It then redisplays the command prompt in order to
allow you to type additional command input as demonstrated below.
C:\Documents and Settings\Jerry Ford>dir
0 File(s) 0 bytes
ION
INIT The term current working directory refers to the Windows folder that the Windows
DEF
command console is currently focused on. By default, Windows XP sets the current
working directory to the user’s own Documents and Settings folder.
13
Assembling Your First
FIGURE 1.8
Using Notepad
to create your
first Windows
shell script.
I N T HE R EAL W ORLD
Unlike many programming languages, Windows shell scripting does not require
you to first learn how to use a complicated GUI-based development environment to
write scripts. Instead, you can create Windows shell scripts using any editor that
can save your files as plain text. However, there are advantages to using GUI-based
script editors. These advantages include
Fortunately, a number of third-party text and script editors include these advanced
features. I have provided two excellent editors on this book’s companion CD-ROM.
To learn more about them, see Appendix B, “What’s on the CD-ROM?”
14
Next click on File and then Save. The Save As dialog appears. Type Hello.bat in the File
Windows Shell Script Programming for the Absolute Beginner
name field, set the location where the file is to be saved as C:\ and click Save. You
should now have a Windows shell script stored on your computer’s hard drive. Now
let’s run the script and see what happens. First click on Start, All Programs, Accesso-
ries, and then Command Prompt. When the Windows console appears, type CD \ and
press the Enter key. This command changes your current working directory to the
same location where you saved the script. Now type the following command and
press Enter.
Hello.bat
You should see the following output displayed in the Windows console.
C:\>Echo Hello World!
Hello World!
C:\>
The first line of output shows the Windows shell script statement that is being
executed. The second line shows the results of the statement once it has been ex-
ecuted. Finally, the third line shows the Windows command prompt, indicating
that the Windows shell is ready for your next command.
If you created and ran this script for yourself and it did not run as described above,
then you probably made a typo. Reopen your script file and double-check its con-
tents. Once you have the script running as advertised, you can close the Windows
command console like any other Window by clicking on the X icon in the upper
right hand corner of the Window or by clicking on the command prompt icon
displayed in the upper left hand corner and selecting Close.
HINT
A quick way to close the Windows command prompt is to type EXIT and press Enter.
By default, Windows shell script automatically displays each statement in the script
just before executing it. The effect of this behavior is that output displayed when
the script is run may be intermingled with script statements, resulting in some
very unattractive output. You can view this behavior even when running the one-
line script above. Fortunately, you have the ability to suppress the display of Win-
dows shell script statements when your scripts execute such that only the script’s
output is displayed. To accomplish this trick, add the following statement to the
beginning of your script on a separate line, and then save and run it again.
@Echo off
15
The next effect of adding the statement as the first line in your Windows shell
Hello World!
C:\>
K
TRIC You may have noticed that I ran the hello.bat script by simply typing hello and not
hello.bat. This works because when you type in a file name without specifying its
file extension, the Windows shell automatically looks for an executable file with
that same file name and executes the first one that it finds. I’ll go over how the
Windows shell knows which files are executable in Chapter 2, “Interacting with
the Windows Shell.”
As you can see, the script displayed only its output. As your scripts grow in size, you
will appreciate the ability to prevent the display of script statements in this manner.
3. Type Command Prompt in the Type a name for this shortcut field and then click
on Finish.
You should now see a shortcut on your desktop called Command Prompt. Double-
click on it to open a new Windows console and access the Windows command
16
prompt. By default, the working directory will be the Windows folder. Type CD and
Windows Shell Script Programming for the Absolute Beginner
press Enter, and then type CD Scripts to switch over to the C:\Scripts folder. At this
point you can execute any script that you save in this folder by simply typing its
name at the command prompt.
You can make things a little easier by configuring your new shortcut to automati-
cally switch to C:\Scripts as it opens a new Windows console. The following proce-
dure outlines the steps involved in performing this task.
1. Right-click on the new shortcut you just created and select Properties. The
cmd.exe Properties dialog appears.
FIGURE 1.9
Configuring the
shortcut to make the
C:\Scripts folder the
default starting
location.
3. Click on OK.
Now when you double-click on the shortcut, the Windows console that opens will
automatically set its focus to c:\scripts (Figure 1.10).
FIGURE 1.10
At this point you should be looking at an empty Notepad file. Type in the following text.
@ECHO off
COLOR 0E
The first statement prevents the display of script statements during execution,
making the script’s output more presentable. The second statement uses the Win-
dows Title command to display the text KnockKnock.bat – The Knock Knock joke game! in
the Windows console’s title bar when the script is executed. The last statement
uses the Windows COLOR command to display all text in yellow when the script is
run. At this point, don’t worry about the specifics of any of these commands or
their syntax. I’ll go over them in detail in Chapter 2. Just accept my somewhat
high-level explanations of how things work and keep writing the script while fo-
cusing on the overall process you are going through.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
This statement uses the Windows SET command to display the Knock Knock! message
followed by the characters C:>, which are supposed to simulate the Windows prompt
and make the player feel like he is still interacting with the command prompt
when in fact he is communicating with your script. The SET command’s /p option
tells the command to assign whatever text the user types to a variable called reply.
ION
INIT A variable is a reference to a location in the computer memory where the script
DEF
stores a value. Variables provide scripts with the ability to store and retrieve data
that they collect while they execute.
ECHO "Sorry, but you are not playing the game right!"
20
GOTO :EOF )
Windows Shell Script Programming for the Absolute Beginner
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
The first statement clears the Windows console. The next three statements check
the value assigned to the reply variable to determine if the player properly typed in
“Who is there?” If the player provided an incorrect response, the script displays an
error message and terminates the script’s execution. However, if the player en-
tered the correct response, the script continues executing and writes ten blank
lines to the Windows console.
Now add the following statements to your script:
SET /p reply="Orange! C:>"
CLS
ECHO "Sorry, but you are not playing the game right!"
GOTO :EOF )
The first statement displays the message Orange! and waits for the player to type in
a response, which again is assigned to a variable called reply. The second statement
clears the Windows command console. If the player fails to enter “Orange who?”, the
third statement displays an error message and terminates the script’s execution.
Otherwise, the script keeps going.
21
Displaying the Punch Line
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO "Orange you glad you've written your first Windows shell script?"
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
The first collection of ECHO statements displays ten blank lines in the Windows
command console. Then the game’s punch line is displayed, followed by ten more
blank lines. The reason for adding the last ten blank lines was to move the display
of the Windows command prompt to the bottom of the Windows command con-
sole, so that when the script ends and the Windows shell redisplays the command
prompt, its reappearance will not interfere with the presentation of the joke’s
punch line.
22
The Final Result
Windows Shell Script Programming for the Absolute Beginner
COLOR 0E
CLS
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
CLS
ECHO "Sorry, but you are not playing the game right!"
GOTO :EOF )
ECHO.
ECHO.
ECHO.
ECHO.
23
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
CLS
ECHO "Sorry, but you are not playing the game right!"
GOTO :EOF )
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO "Orange you glad you've written your first Windows shell script?"
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
24
ECHO.
Windows Shell Script Programming for the Absolute Beginner
ECHO.
ECHO.
ECHO.
ECHO.
As you can see the script is not very complicated, and if you remove the ECHO. state-
ments, you are really only left with a handful of lines of code. Each time the script
writes something to the Windows console, it first executes the CLS command to
clear the screen and add focus to the new line of displayed text. Don’t worry about
the rest of the statements that make up this script; they will be fully covered in
Chapter 2, “Interacting with the Windows Shell.”
Once you have typed and saved this script, run it. If it does not work as expected,
reopen the script and double-check your typing. Once you have everything work-
ing, move on to the next chapter where you will learn how to configure the Win-
dows command console.
Summary
You have covered a lot of ground in this chapter. You learned what the Windows shell
is and how it provides you with a text-based interface to the Windows operating sys-
tem. You also learned about other scripting options available for Windows operating
systems. You created, saved, and ran your first Windows shell script. Finally, you cre-
ated your first Windows shell script computer game, the Knock Knock joke.
EXERCISES
1. As computer games go, the Knock Knock game is very simple. Its main purpose
was to introduce you to the mechanics of script creation and execution. Try
enhancing the scripts by adding additional Knock Knock jokes.
2. Experiment with the TITLE statement by changing the message the script dis-
plays in the Windows command console’s title bar.
3. Modify the text that is displayed when the player fails to respond correctly to
the joke’s prompts. Try to make the message more clear and understandable.
Interacting with
2
C H A P T E R
I
n this chapter, you will learn how to work with and control the Windows
shell environment. In doing so you will also learn how to configure the
appearance and behavior of the Windows command console and the Win-
dows command prompt. You will also learn about the commands internally defined by
the Windows shell. These commands include all of the programming statements that
make up the Windows shell scripting language.
This chapter will also explain how the Windows shell works with external commands
and utility programs, including how it locates and executes these commands and utili-
ties. The chapter will conclude by demonstrating how to develop the Unpredictable
Command Prompt script. This script provides a fun demonstration of how to automate
the configuration of the Windows shell environment.
Specifically, you will learn
• The basics of Windows command syntax
• Different ways of starting Windows command consoles and configuring the Win-
dows shell environment
• The differences between internal Windows shell script commands and external
Windows commands and utilities
• How to manually customize the Windows command console from the
Windows desktop
26
Windows Shell Script Programming for the Absolute Beginner
Project Preview:
The Unpredictable Command Prompt
This chapter’s main project is called the Unpredictable Command Prompt. It demon-
strates how to randomly alter the appearance of the Windows command console.
Among the Windows command console features customized by the script are the fore-
ground and background colors of the Windows command console, the text displayed
in the title bar, the format of the Windows command prompt, and the message that
is initially displayed when the Windows command console first appears.
The Unpredictable Command Prompt script randomly configures one of three dif-
ferent sets of configuration settings each time it is executed. For example, as Fig-
ure 2.1 shows, in one scenario the user may be greeted by name and told to Code
well and Prosper. The text displayed in the Windows command console appears in
green on a black background.
FIGURE 2.1
The Windows
command console
displays the first of
three different
greeting messages.
Figure 2.2 shows a second view that the user may see. In this case, the user is
greeted by the message, “Hello. It is good to be working with you today!” In addition,
the color of the foreground text is changed to yellow and the Windows command
prompt now displays both the day of the week and the date.
Figure 2.3 shows the final view the user will see. In this case, the text message,
“Boo! Did I scare you?” is displayed and the text appears as black characters on a
yellow background.
This script also gives you a sneak peak of several other important Windows shell
scripting techniques, which are explored further later in the book. These tech-
niques include the storage of data in variables, the use of conditional logic to con-
trol script execution, and the ability to perform numeric comparisons.
27
The Windows
command console’s
title bar message is
also changed.
FIGURE 2.3
Foreground and
background colors
are changed
as well.
Command Arguments
the name of the command followed by one or more optional arguments that tell
the command what you want it to do. Command arguments can consist of several
different elements, including
• Switches. Modify the way in which a command is processed. Switches consist
of a forward slash followed by one or more characters. Each Windows com-
mand has its own unique set of switches.
• Modifiers. Change the behavior of a switch. Modifiers consist of a colon fol-
lowed by one or more characters. Each Windows command has its own set of
modifiers.
• Parameters. Arguments passed to commands for processing.
HINT If you are uncertain of a command’s syntax, you can view it from the Windows com-
mand console by typing Help followed by the name of the command. For example, if
you type HELP DATE and press Enter, you will see the following:
C:\>HELP DATE
Type DATE without parameters to display the current date setting and a prompt
If Command Extensions are enabled the DATE command supports the /T switch
which tells the command to just output the current date, without prompting
C:\>
ION
INIT When referring to Windows commands, the term mutually exclusive means that only
DEF
one of a collection of options can be selected. For example, when executing the CMD
command you have the option of specifying the E:/ON or E:/OFF, but you cannot
specify both options at the same time.
In this book I have chosen to display Windows commands in upper case. However,
Windows commands are not case-sensitive, which means that you can type them
using upper case, lower case, or a combination of upper and lower case and achieve
the same results. For example, as far as the Windows shell is concerned, all of the
following commands are equivalent:
• ECHO Greetings
• echo Greetings
• Echo Greetings
• EcHo Greetings
mand opens a new Windows shell session within the current console. In contrast,
the START command (which works only from within an already open Windows com-
mand console) starts a new Windows shell session by opening a new Windows
command console each time.
Switch Function
/C Executes the command and closes the Windows shell
/K Executes the command but does not close the Windows shell
/S Changes the handling of the string after the /C or /K switch
/Q Disables echo
/D Prevents the execution of AutoRun commands specified in the registry
/A Formats command output in ANSI format
/U Formats command output in Unicode format
/T:FG Sets the Windows command console’s foreground and background colors
/E:ON Enables extensions to the Windows shell required by certain commands
/E:OFF Disables extensions to the Windows shell (required by certain commands)
/F:ON Enables file and folder name completion
/F:OFF Disables file and folder name completion
/V:ON Allows for the delayed expansion of environment variables
/V:OFF Prevents the delayed expansion of environment variables
31
P
TRA Command line extensions are improvements made to Windows commands in later
Let’s look at a few examples of how to work with CMD. First, click on Start, Run, and
then type CMD and click on OK to start a new Windows shell session. This opens a
new Windows command console with which you can begin working with the Win-
dows command prompt.
If you want, you can start a new Windows shell session and pass it a command to
execute at the same time by clicking on Start, Run, and then typing CMD followed by
a command as shown below.
CMD /K TITLE Welcome
In this example, a new Windows command console will open and display the text
message of Welcome in its title bar. Sometimes you may want to simply start a new
Windows shell session, pass it a command, have the command execute, and then
automatically close the Windows command console. You can do this as follows.
CMD /C DEL C:\Temp\*.txt
The CMD command’s /K and /C switches are examples of mutually exclusive param-
eters. /K specifies that the Windows command console should remain open after
executing the command whereas /C specifies that the Windows command console
should close after the command completes processing.
The next example demonstrates how to use a modifier to control the execution of
the CMD command. In this example, the /T switch, which sets foreground and back-
ground colors, is used to invert the Windows color scheme from white on black to
black on white.
CMD /T:F0
In this example, the switch is /T. It has a modifier, which is preceded by the colon
character. The first character in the modifier sets the Windows command console’s
foreground color (e.g., the color of text) and the second character of the modifier
sets the background color. You can specify a range of different foreground and
background colors in the Windows command console, as shown in Table 2.2.
32
TABLE 2.2 COLORS FOR THE WINDOWS
Windows Shell Script Programming for the Absolute Beginner
COMMAND CONSOLE
Color Value
Black 0
Blue 1
Green 2
Aqua 3
Red 4
Purple 5
Greenish Yellow 6
Light Gray 7
Gray 8
Light Blue 9
Light Green A
Light Aqua B
Light Red C
Light Purple D
Light Yellow E
Bright White F
To test this command, open a Windows command console, type in the command
at the command prompt, and press the Enter key.
Parameter Description
"title" Text to be displayed in the Windows command console’s title bar
/d Path Specifies the startup folder
B Starts a script without opening a new Windows command console
I Resets the execution environment to the original state of the
parent environment
MIN Opens a new Windows command console in a minimized state
MAX Opens a new Windows command console in a maximized state
SEPARATE Starts a 16-bit program in its own memory space
SHARED Starts a 16-bit program in a shared memory space
LOW Starts an application using the low priority
NORMAL Starts an application using the normal priority
HIGH Starts an application using the high priority
REALTIME Starts an application using the real-time priority
ABOVENORMAL Starts an application using the above normal priority
BELOWNORMAL Starts an application using the below normal priority
WAIT Starts an application and waits for it to end
Program/Command An optional program or command to be processed by the
Windows shell
Parameters One or more arguments to be passed to the program or command
34
Internal vs. External Commands
Windows Shell Script Programming for the Absolute Beginner
The Windows shell works with two different types of commands: internal and
external. Internal commands are built into the Windows shell, whereas external
commands exist as separate executable files stored on the computer’s hard drive.
Most Windows commands are found in \Winnt\System32. Both internal and external
commands follow the same basic syntax rules. Table 2.4 provides a listing of the
Windows shell’s internal commands.
Command Overview
ASSOC Displays or modifies file name extension associations
CALL Calls one script from another without stopping the calling or parent
script. Also provides the ability to switch processing control to labels
specified within a script
CD (CHDIR) Changes the current directory
CLS Clears the Windows command console screen
COLOR Sets Windows command console foreground and background colors
COPY Copies one or more files from one location to another
DATE Displays or modifies the system date
DEL Removes one or more files
DIR Displays a list of files and folders located in the specified directory
ECHO Displays text messages in the Windows command console
ENDLOCAL Terminates variable localization by restoring variables to their values as
they existed before the preceding SETLOCAL command was executed
ERASE Removes one or more files
EXIT Closes the Windows command console and ends a command shell
session
FOR Executes a command for each file in a collection of files
FTYPE Displays and modifies file types that are associated with file name
extensions
GOTO Alters processing flow in a script by transferring it to a line containing a
specified label
IF Performs conditional processing and alters the execution flow within the
script based on tested results
35
TABLE 2.4 BUILT-IN WINDOWS SHELL COMMANDS (CONTINUED)
The number of external commands and command line utilities are too numerous and
varied to attempt to cover here. You learn more about them as you work your way
through this book. These commands consist of any executable file provided by the
operating system and any applications that you may have installed on your computer.
To view the list of folders stored in the path variable, open the Windows command
prompt and type PATH. The output displayed by the command will resemble the
following output.
C:\>path
PATH=C:\WINNT\system32;C:\WINNT;C:\WINNT\system32\WBEM
C:\>
The output displayed in this example shows that the Windows shell will search
three folders when looking for a command to execute. The folders are searched in
the order presented, from left to right. Therefore C:\Winnnt\system32 will be searched
first and if the command is not found, C:\Winnt will be searched second followed by
C:\Winnt\system32\wbem.
37
If you want, you can add additional folders to the search list stored in the path
As you can see, the structure of this command is PATH followed by the name and
path of the folder to be added, a semicolon character, and then %path%.
K
TRIC Placing a folder at the beginning of the path variable’s search list ensures that it
will be the first folder checked. This way, if you give a script a name that happens to
match a Windows command, your script will be executed in place of the Windows
command. Remember, the Windows shell stops looking for commands as soon as it
finds the first match.
P
TRA I have not yet covered the use of variables in this book, but they are such a funda-
mental part of scripting that it’s almost impossible to do anything without using them.
For now, just note that to reference them from within a script you must enclose the
variable’s name inside a pair of percentage characters. Keep reading along and I
will explain how to work with variables in detail in Chapter 4, “Storing and Retriev-
ing Information in Variables.”
You can just as easily add a folder to the end of the search list, as shown below.
PATH C:\scripts;%path%
P
TRA Don’t forget to always add the %path% variable to either the beginning or the end of
the PATH command when modifying the command’s search path. Otherwise, the list
of folders that made up the original search path will be deleted and replaced by
your new addition, which is not what you’ll want to do.
Any changes that you make to the path variable by modifying it from a Windows shell
script are just temporary. In other words, the changes you make are lost when you
close the Windows command console and terminate your Windows shell session.
38
PATHEXT
Windows Shell Script Programming for the Absolute Beginner
When you type an external command, you must specify its name. Optionally, you
can specify an external command’s file extension. Normally, all that you’ll need is
the name of the command itself. When you type in a command’s name without its
file extension, the Windows shell uses the list of file extensions stored in the pathext
variable to search for a matching command. The pathext variable lists all of the file
extensions that Windows associates as being executable files.
When you type a command without its file extension, the Windows shell uses the
collection of file extensions stored in pathext to search for a matching file. It does
this by substituting each file extension listed in pathext as the command’s file ex-
tension until it finds a match. The first match that is found ends the search. The
Windows shell then executes this command.
By default, the pathext variable lists the following file extensions in the follow-
ing order.
• .COM
• .EXE
• .BAT
• .CMD
You can display the contents of the pathext variable by typing the following com-
mand at the Windows command prompt.
ECHO %pathext%
The output you get back should look something like this:
C:\>ECHO %pathext%
.COM;.EXE;.BAT;.CMD
However, you may see additional file extensions listed depending on what soft-
ware you have installed on your computer. If you wish, you can add a new file
extension to pathext as demonstrated below.
SET pathext=%pathext%;.shl
In this example, the file extension .SHL is added to the end of the pathext variable
using the SET command. You’ll find yourself using the SET command a lot when
working with variables. I will explain the command in detail in Chapter 4, “Stor-
ing and Retrieving Information in Variables.”
39
Other Useful Windows Commands
• PROMPT
• COLOR
• CLS
• ECHO
You’ll need to know how to work with these commands to complete this chapter’s
scripting project, so I’ll go over them in the sections that follow.
To see how the TITLE command works, create a new Widows shell script made up of
the following statement.
TITLE Greetings!
When you run your script, you’ll see the message Greetings! in the title bar area, as
shown in Figure 2.5.
FIGURE 2.5
Posting a message
in the Windows
command console’s
title bar.
40
Working with the PROMPT Command
Windows Shell Script Programming for the Absolute Beginner
The PROMPT command is used to modify the display of the Windows command
prompt. By default, the Windows command prompt shows the currently selected
disk drive and folder in the form of the drive letter followed by a colon, a backward
slash, and the “greater than” character as shown below.
C:\>
However, using the PROMPT command you can display any of the information listed
in Table 2.5.
Argument Displays
$A & - Ampersand character
$B | - Pipe character
$C ( - Left parenthesis character
$D The current date
$E ANSI escape code 27
$F ) - Right parenthesis character
$G > - Greater-than character (greater-than sign)
$H Backspace character
$L < - Less-than character (less-than sign)
$N The current drive name
$P The current drive and path names
$Q = - Equal character (equal sign)
$S A blank space
$T Current system time
$V The Windows version number
$_ Performs a carriage return and linefeed
$$ $ - Dollar character (dollar sign)
$+ A + sign representing the depth of the pushd stack.
41
The syntax of the PROMPT command is shown below.
The value of text represents a combination of one or more of the arguments listed
in Table 2.5. For example, to replace the current drive letter with the current time
you would type the following:
PROMPT $D
When executed, the previous command would modify the command prompt as
shown below.
C:\>PROMPT $D
Wed 06/18/2003
If you prefer a shorter, less intrusive command prompt, then try the following
command:
PROMPT $G
This command turns the command prompt into the > character. If desired, you can
combine multiple arguments when modifying the command prompt, as demon-
strated below.
C:\>PROMPT $D$G
Wed 06/18/2003>
As you can see, the command prompt now display the date followed by the “greater
than” character. You can also insert any free-form text that you want as the com-
mand prompt, as shown below.
C:\>PROMPT Welcome to my PC$G
Welcome to my PC>
Here I changed the command prompt to display a greeting message followed by the
“greater than” character. Finally, if you decide that you want to restore the command
prompt to its default format, just type PROMPT and hit the Enter key as shown below.
Welcome to my PC>PROMPT
C:\>
42
Changing Colors
Windows Shell Script Programming for the Absolute Beginner
By using the COLOR command, you can take control of the foreground and back-
ground colors displayed in the Windows command console. The syntax of the COLOR
command is outlined below.
COLOR BF
The COLOR command requires two arguments. B represents a numeric value that
specifies the background color to be used, and F represents the foreground color
(e.g., the color of displayed text). The COLOR command supports the same colors as
the CMD command, which were listed earlier in this chapter in Table 2.2.
By default, the Windows command console displays text in white on a black
background. Using the COLOR command, you can change these settings as dem-
onstrated below.
COLOR E4
This command modifies the Windows command console so that it displays all text
in red on a yellow background. To restore the Windows command console color
settings to their default setting, you can type COLOR 0F, or, as a shortcut, just type
COLOR and the Windows command console default white-on-black color scheme will
be restored.
CLS
The Windows command console automatically scrolls text off of the display as its fills
up. However, this can make the console look cluttered and difficult to read. If you
prefer, you can use the CLS command to clear out all currently displayed text, leaving
only the command prompt visible. The CLS command’s syntax is outlined below.
CLS
As you can see, the CLS command does not accept any arguments, making it ex-
tremely easy to use.
ECHO
The ECHO command gives you the ability to display text messages in the Windows
command console. Using the ECHO command you can create scripts that keep the
user informed about their execution status and display their results. The syntax of
the ECHO command is outlined below.
ECHO [ON | OFF] [message]
43
As you have already seen, the ECHO command’s use is very straightforward. For ex-
C:\>
As you can see, the original ECHO command and its resulting output are both displayed.
To clean up the display, it is generally a good idea to prevent the display of the original
command and leave only its output visible. You can accomplish this by adding the @
character to the beginning of the ECHO command, as demonstrated below.
@ECHO This is an example of how to use the ECHO command
If you make this change to your script and run it again, you’ll get the following output.
This is an example of how to use the ECHO command
C:\>
As you can see, this time only the text message is displayed, followed by the Win-
dows command prompt. Using this same technique, you can suppress the display
of any number of ECHO commands, as demonstrated below.
@ECHO Once upon a time there was a little boy
Since displaying output is a very common task in Windows shell scripts, a short-
cut has been provided to simplify your scripts. To use this shortcut, just type the
following statement at the beginning of your Windows shell scripts:
@ECHO Off
For example, the following statements demonstrate how to rewrite the previous
example using the @ECHO Off statement.
44
@ECHO Off
Windows Shell Script Programming for the Absolute Beginner
Customization Options
Windows command console customization is performed from the Command
Prompt Properties dialog. You can open this dialog by opening the Windows com-
mand console and right-clicking on the Command Prompt icon in the upper-left
corner of the console and selecting Properties. This dialog is organized into four
property sheets as listed below.
• Options
• Font
• Layout
• Colors
Each of these property sheets configures a different set of properties for the Win-
dows command console as explained in the sections that follow.
FIGURE 2.7
Configuring font
type and size for
the Windows
command console.
ION
INIT The term pixel is short for picture element and represents the smallest area that a
DEF
computer can display or print.
47
K
TRIC Set the Screen Buffer Size Height setting to three or four times larger than the height
FIGURE 2.8
Configuring screen
size and the
Windows position of
the Windows
command console
FIGURE 2.9
Configuring the
Windows command
console’s
foreground and
background colors.
I N T HE R EAL W ORLD
Any true Windows power user or system administrator is, by definition, good at
working with the Windows shell. Often working with the Windows shell means
typing in the same sets of commands repeatedly. To speed things up and increase
their efficiency, power users and administrators learn all kinds of tricks to help them
work faster. One technique that many people use is to access command history,
which provides a list of previously executed commands that you can quickly access
and run again. To access the Windows shell’s command history, press the F7 key.
Then use the up and down arrows to select a previously executed command and
press the Enter key.
SET TestVariable=%random%
The first statement prevents the Windows shell from displaying script statements
as it processes them. This will make the script’s output less cluttered and present
a cleaner and more polished looking output. The second statement uses the SET
command to assign a random number to a variable called TestVariable. The random
variable is generated automatically by the operating system on Windows 2000, XP,
and 2003 computers. Whenever it is referenced, it returns a random number be-
tween 1 and 32,767.
The script will reference the random value assigned to this variable to determine
which of three possible actions to take. Specifically, it will take one set of actions if
50
the value assigned to the variable is greater than 22,000. It will take a different set of
Windows Shell Script Programming for the Absolute Beginner
actions if the value is greater than 11,000 but less than 22,000. Finally, a third set of
actions is taken if the variable’s value is less than 11,000 but greater than zero.
The rest of the script consists of three major sections. The statements that make up
each section are very similar, so I’ll explain the statements that comprise the first
section in detail and then provide a high-level overview of the remaining sections.
CLS
The first line can be translated like this: “If the value assigned to TestVariable is
greater than 22,000, then perform the following action.” The action to be performed
is enclosed within parentheses (a pair of () characters). Actually, the opening (
character is shown at the end of the first line and the closing ) character is on the
third line. Nonetheless, the CLS command is still considered enclosed within them.
This command clears the Windows command console, giving the script a clear
screen onto which to write additional text.
Cls
)
51
Changing Background and Foreground Colors
Cls
COLOR 02
Cls
COLOR 02
Echo.
Cls
COLOR 02
52
Echo Greetings %username%. Code well and Prosper.
Windows Shell Script Programming for the Absolute Beginner
Echo.
PROMPT
Cls
COLOR 02
Echo.
PROMPT
GOTO :EOF
If you were to forget and leave out the GOTO :EOF statement from this section of the
script, then any changes made by this portion of the script would always be overrid-
den by changes made in the two sections that follow. This will happen because the
script would keep on processing the statements that follow. For example, the third
section of this script is set up to process whenever the value assigned to TestVariable
is greater than zero. Therefore, if the value assigned to TestVariable happens to be
26,000, then any changes made by this first section of the script will be undone later
in the script. By adding the GOTO statement, you prevent this from occurring.
CLS
COLOR 0E
ECHO.
PROMPT $d$g
GOTO :EOF
CLS
COLOR E0
ECHO.
PROMPT $p
GOTO :EOF
SET TestVariable=%random%
Cls
COLOR 02
Echo.
PROMPT
GOTO :EOF
CLS
COLOR 0E
ECHO.
PROMPT $d$g
GOTO :EOF
If %TestVariable% GTR 0 (
CLS
COLOR E0
ECHO.
PROMPT $p
GOTO :EOF
)
55
Summary
EXERCISES
1. Create a new Windows shell initialization script that automatically adds to the
path variable the name and path of the folder where you plan to store your
Windows shell scripts.
Scripting Basics
I
n this chapter, I’ll explain the importance of adding comments to your Windows
shell scripting to make your code self-documenting. I’ll also provide you with
a Windows shell script template that you can use as the basis for organizing
and documenting your scripts. You will learn about a programming technique called
redirection, and you’ll learn how to use it to control script input and output.
This chapter also shows you how to group commands and make the execution of one
command dependent on the outcome of another command. Finally, you will learn how to
create the Fortune Teller game. This game builds on the programming techniques that
have been used in previous games and also demonstrates how to create a script that
continues to execute indefinitely by looping back and re-executing previous statements.
Specifically, you will learn
• How to add comments to your Windows shell scripts
• How to place two or more statements on the same line
• How to set up conditional command execution
• How to make the output of one command the input for another command
• How to create report and log files and append data to existing report and log files
58
Windows Shell Script Programming for the Absolute Beginner
FIGURE 3.1
The player must press a key for the game to continue, at which point the next
screen continues to build upon the game’s story line, as shown in Figure 3.2.
FIGURE 3.2
Next, the fortune teller invites the player to ask a question and promises to try and
provide an answer, as shown in Figure 3.3.
59
The game then describes the process that the fortune teller goes through as she uses
her psychic powers to come up with an answer. As shown in Figure 3.4, the fortune
teller is not always able to provide the player with a conclusive Yes or No response.
FIGURE 3.4
With as much
drama as she can
create, the fortune
teller answers the
player’s question.
After answering the player’s first question, the fortune teller continues to allow
additional questions to be asked, as shown in Figure 3.5. The game continues until
the player closes the Windows command console or types the lower case letter e to
end, or exit, the game.
FIGURE 3.5
Players may
continue to ask as
many questions as
they wish.
addition, I’ll discuss the importance of using comments to create a Windows shell
script documentation template that you can use to improve the overall organiza-
tion and manageability of your scripts.
Comment is a text string representing the documentation that you wish to embed
in the script. REM statements have no impact on the execution of your script. The
Windows shell ignores them during script execution. You can use the REM state-
ment in either of two ways. One way to use the REM statement is to include it on a
line by itself to describe or document the action of one or more statements that
follow, as demonstrated below.
@ECHO off
ECHO.
ECHO.
ECHO W E L C O M E T O T H E
ECHO.
ECHO F O R T U N E T E L L E R G A M E !
ECHO.
ECHO.
ECHO.
REM Make the player hit a key in order for the game to continue
PAUSE
61
A second way to use the REM statement is to place it at the end of another state-
P
TRA Always begin with the @ECHO off statement as the first script statement. If you
forget and leave this statement out of your script, all your script statements (includ-
ing your comments) will be displayed as the script executes, thus defeating much of
the benefit for adding comments to your scripts.
REM ***************************************************************************
REM
REM
REM
REM ***************************************************************************
the REM statement to format a script header in which you can document informa-
tion about the script, including its name, author, creation date, and a description.
Three additional statements have been added to the bottom of the template and
can be used to organize your scripts into three major sections. In the Initialization
section, you would add statements that perform functions such as setting fore-
ground and background colors or posting the name of the script in the Windows
command console’s title bar.
The Main Processing section is where you would type the core logical portions of
your script. Later, in Chapter 7, “Creating Procedures and Subroutines,” I’ll go over
how to isolate portions of your code into discreet subroutines and procedures,
which you would then locate in the third section of the template.
By using the template I have provided or by creating one of your own, you lay down
a foundation for all future script development with a consistent organizational
structure that will be easy to follow and update. For example, the following script
demonstrates how to use the template in the creation of a new script.
@ECHO off
REM ***************************************************************************
REM
REM
REM
REM ***************************************************************************
PATH %path%;C:\Scripts
REM Modify the command prompt to display the greater than sign
PROMPT $g
CLS
As you can see, anyone who views the script can quickly identify the script’s pur-
pose and its author. By looking for the three main script comments, you can also
easily locate different sections of the script. By adding additional comments, you
can create self-documenting scripts. Note that while this particular example does
not have any subroutines or procedures, you might still want to include that sec-
tion comment in the script as a placeholder for possible future development.
such as
• The Windows command console display
• A file
• A printer
K
TRIC In addition to redirecting output to files, you can also send it to a printer by specify-
ing the appropriate port number, such as LPT1.
I’ll demonstrate how to work with these redirection operators in the sections
that follow.
65
TABLE 3.1 REDIRECTION OPERATORS
Apple
Grape
Blue Berry
Orange
One way to view the contents of this file from the Windows command console
would be with the TYPE command, as demonstrated below.
c:\scripts>TYPE TestFile.txt
Strawberry
Apple
Grape
Blue Berry
Orange
ION
INIT The TYPE command displays the contents of files by sending its output to standard
DEF
output. By default, this is the Windows command console.
66
As you can see, the TYPE command displays the contents of the TestFile.txt file ex-
Windows Shell Script Programming for the Absolute Beginner
actly as they are stored. However, suppose that you wanted to sort the entries in the
file before displaying them. One way to accomplish this is to redirect the output of
the TYPE command and use it as input for the SORT command, as demonstrated below.
c:\scripts>TYPE TestFile.txt | SORT
Apple
Blue Berry
Grape
Orange
Strawberry
ION
INIT The SORT command sorts data as input and sends the result to standard output.
DEF
Generating Reports
The > redirection operator enables you to send command output to a destination
other than standard output. It provides an easy way to generate report and log files.
In addition, the >> operators provide the ability to append data to the end of existing
report and log files. Look at an example of these two redirection operators in action.
@ECHO off
REM ***************************************************************************
REM
REM
REM
REM ***************************************************************************
ION
INIT The DIR command provides a list of all files and folders stored in the specified folder
DEF
or directory.
In this example, a variable called dest is established using the SET command. It is
assigned the name and path of a report that the script will create. The report is
actually created when the first ECHO statement is executed and has its output redi-
rected to the folder specified by the dest variable. Once the file is created, the script
continues to write to the file by redirecting the output of ECHO statements using
the >> (append) operator.
P
TRA This script will fail unless the complete path to the target folder already exists.
Before you run this script, make sure that you create a subfolder called LogFiles
within your C:\Script folder.
68
P
TRA Be sure you remember to switch from the > operator to the >> operator after the first
Windows Shell Script Programming for the Absolute Beginner
FIGURE 3.6
Examining the
report created by a
Windows shell
script using output
redirection.
In this example, the TYPE command is used to display the contents of a file called
Report.txt located in C:\Reports. If Report.txt exists, then its contents are displayed.
If the Report.txt file does not exist, the following error will occur and be written to
the C:\Scripts\Errors.log file.
The system cannot find the file specified.
In addition, since the error shown above was redirected to the log file, it would not
have been displayed in the Windows command console when the script executed.
69
Conditional Command Execution
This compound command begins by executing the MKDIR command, which cre-
ates a new directory or subfolder called Reports in the C:\Scripts folder. Once
this command completes execution, the second command in the compound com-
mand executes. In this example, the COPY command copies all files ending with a
.txt extension in the current working directory to C:\Scripts\Reports.
The || compound command operator is the exact opposite of the && operator, per-
forming the second command only in the event that the first command fails. For
example, the following compound command begins by displaying all .log files in
the current working directory. If no .log files are found, then the text of the ECHO
statement is redirected to C:\Scripts\Debug.log.
DIR *.log || ECHO No .log files were found >> C:\Scripts\Debug.log
The Windows shell allows you to chain together more than two commands at a time
if needed. For example, the following statement chains together three commands:
DIR *.log & COPY *.log C:\Tmp & ECHO .LOG files have been copied.
Grouping Commands
The Windows shell also enables you to explicitly group commands together to dic-
tate the order in which they are executed. This is accomplished using the () opera-
tors. For example, the following statement consists of five different commands:
CD C:\Scripts\Reports && (COPY *.txt A:\ & COPY *.bak A:\) && (DEL *.txt & DEL *.bak)
REM ***************************************************************************
REM
72
REM Script Name: Fortune.bat
Windows Shell Script Programming for the Absolute Beginner
REM
REM Description: This Windows shell script game provides random answers to
REM
REM ***************************************************************************
COLOR 5e
CLS
The first statement presents the display of script statements during execution.
The next 10 statements provide a place to document the script’s name, author,
and creation date as well as to provide a brief description. The COLOR statement sets
the Windows command console’s color scheme to yellow text on a purple back-
ground. The TITLE statement then posts the name of the game in the Windows
command console’s title bar. Finally, the CLS statement clears the display and pre-
pares it for the game’s first screen.
ECHO.
ECHO.
ECHO ^|
ECHO.
ECHO W E L C O M E T O \ /
ECHO ***
ECHO T H E F O R T U N E * *
ECHO __ * * __
ECHO T E L L E R ' S M A G I C * *
73
ECHO * *
ECHO / \
ECHO -----
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO Prepare to be mystified by the great psychic power of the Fortune Teller.
ECHO She knows all, she sees all and she tells all!
ECHO.
ECHO.
Pause
To prevent the above screen from scrolling off of the display as the game executes,
thus giving the player a chance to read it, the PAUSE command has been added.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO The door opens and a small woman with a cane and a limp slowly
ECHO.
74
ECHO enters into the room.
Windows Shell Script Programming for the Absolute Beginner
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
PAUSE
As you can see, the PAUSE command is again used to ensure that the player has an
opportunity to view the information on this screen.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO "I shall reveal the answer that you so desperately need to know."
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
:QUESTION
ECHO.
SET trigger=%reply:~0,1%
Near the end of this section of code, you see a statement that looks like this:
:QUESTION
ION
INIT A loop is a collection of statements that are executed repeatedly.
DEF
The next statement prompts the player to enter a question for the fortune teller to
answer. By placing the :QUESTION label just before the SET statement, I have provided
the ability to loop back to this portion of the script and replay the game starting at
the point where the fortune teller instructs the player to ask a question.
76
Next, another SET statement is executed. This statement extracts the first charac-
Windows Shell Script Programming for the Absolute Beginner
ter from the text string entered by the player to see if it is equal to the letter e. If
is does equal the letter e, the script assumes that the player is done and wants to
end the game.
P
TRA Even though I have not yet covered it in this book, I wanted to use the substring
operation presented here to introduce you to a different method of control script
termination. Unfortunately, whether it be substring operations, conditional logic, or
loops, for your best learning experience I will only formally introduce and explain a
limited number of programming concepts at a time. My goal in this book is to intro-
duce and explain basic programming concepts and to continue to build upon them
as I go along. However, it’s almost impossible to write Windows shell script games
without using some advanced scripting techniques. Without some advanced tech-
niques, the game projects in the first two-thirds of this book would have remained
very simple while I covered all the concepts that you’ll need to write more advanced
scripts. But this approach takes away most of the fun and I wanted to present you
with game scripts that become increasingly interesting (and therefore difficult) as
the book progresses. Whenever I need to use a programming technique that I have
not yet formally introduced to you, I’ll try to provide a brief explanation of what’s
going on. I’ll then provide a reference to the chapter where the programming tech-
nique is more fully explored, and then I’ll keep moving on with the script project.
K
TRIC I used a substring operation above to provide a quick way for the script to end.
When coded in this way, the player could end the game by typing end, exit, or e.
P
TRA Be careful when using a substring operation as shown above because if the player
somehow formulates a question using a word that begins with the letter e, the game
would end instead of providing the player with an answer. In a game like this one,
it’s a fairly safe bet that most questions will begin with phrases such as “Will I” and
“Should I,” so using the letter e is probably safe enough.
GOTO :EOF
ECHO.
ECHO.
ECHO.
ECHO The old fortune teller closes her eyes and slowly leans her head back.
ECHO.
ECHO She begins to mumble aloud in an ancient dialect sending chills up your back.
ECHO.
ECHO Suddenly she sits upright and stares you in your eyes!
ECHO.
ECHO.
ECHO.
ECHO.
SET z=%random%
SET answer=NO!
GOTO :Continue
GOTO :Continue
If %z% GTR 0 (
GOTO :Continue
After describing the actions of the fortune teller, a SET statement is used to assign
a random number to a variable called z. As in previous script examples, a series of
IF statements are then used to assign a value to a variable called answer based on
the value of the randomly selected variable. Specifically, if the randomly selected
variable is greater than 22,000 the answer returned by the fortune will be NO! and
the GOTO statement causes the script to jump down to the label called :Control and
continue executing from that point in the script, thus bypassing any remaining
validation of the randomly selected value. If the value of the variable is less than
22,000 and greater than 11,000, the answer returned will be YES! Otherwise, the
answer will be set to Uncertain. Only time will tell.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
79
ECHO.
PAUSE
GOTO :QUESTION
REM ***************************************************************************
REM
REM
REM Description: This Windows shell script game provides random answers to
REM
REM ***************************************************************************
REM Post the name of the game in the Windows command console title bar
COLOR 5e
ECHO.
ECHO.
ECHO.
ECHO ^|
ECHO.
ECHO W E L C O M E T O \ /
ECHO ***
ECHO T H E F O R T U M E * *
ECHO __ * * __
ECHO T E L L E R ' S M A G I C * *
ECHO * *
ECHO C R Y S T A L B A L L ! ***
ECHO / \
ECHO -----
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO Prepare to be mystified by the great psychic power of the Fortune Teller.
ECHO She knows all, she sees all and she tells all!
ECHO.
ECHO.
CLS
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO The door opens and a small woman with a cane and a limp slowly
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
CLS
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO "I shall reveal the answer that you so desperately need to know."
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
SET trigger=%reply:~0,1%
REM If the player typed the letter "e" then it's time to end the game
IF %trigger%==e (
GOTO :EOF
CLS
REM Display the text that precedes the fortune teller's answer
ECHO.
ECHO.
ECHO.
ECHO.
ECHO The old fortune teller closes her eyes and slowly leans her head back.
ECHO.
ECHO.
ECHO your back. Suddenly she sits upright and stares you in your eyes!
ECHO.
ECHO.
ECHO.
84
ECHO.
Windows Shell Script Programming for the Absolute Beginner
SET z=%random%
REM If the random number is greater than 22,000 the answer is NO!
SET answer=NO!
GOTO :Continue
REM If the random number is greater than 11,000 the answer is YES!
SET answer=YES!
GOTO :Continue
REM If the random number is greater than zero the answer is uncertain.
If %z% GTR 0 (
GOTO :Continue
:Continue
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
85
ECHO.
ECHO.
ECHO.
PAUSE
CLS
REM Loop back and let the player ask the fortune teller another question
GOTO :QUESTION
Summary
In this chapter, you learned how to add comments to your Windows shell scripts in
order to document your scripting logic and to create a documentation template. You
also learned how to take control of input and output. This included setting up the
output of one command to provide another command’s input. This also included
learning how to create reports and error log files. This chapter also showed you how
to combine more than one command to create a compound command as well as
how to make the execution of one command conditional on the success of another
command. Finally, you had some fun by creating the Fortune Teller game.
EXERCISES
1. The Fortune Teller game’s story line is very basic. Add additional story text that
helps to better describe what is occurring as the game plays out.
2. The Fortune Teller game currently makes a random selection from one of only three
possible answers. Expand the range of available answers to six and then to nine.
3. Currently, the Fortune Teller game ends when the player types the letter e instead
of a question. Add instructions to the game that explicitly inform the player of
this capability. In addition, experiment with other possible ways to end the game
such as requiring that the player enter the word Bye, at which time the Fortune
Teller could invite the player to return again later to ask more questions.
This page intentionally left blank
Storing and
4
C H A P T E R
Retrieving
Information in
Variables
T
his chapter begins by showing you how to pass data to scripts at execution
time and how to write scripts that can accept and process this data. In addition,
you will get a formal education on the use of variables within Windows shell
scripts. You will learn about environment variables that are created and maintained by
the operating system as well as how to create and modify your own script variables.
You will also learn how to replace portions of the contents of string variables and to
perform mathematical operations on variables containing numeric data. The chapter
will then conclude by showing you how to build a Mad lib-style story called “Buzz the
Wonder Dog,” in which the reader helps to write the story by supplying key story ele-
ments collected from questions presented at the beginning of the script’s execution.
Specifically, you will learn
• How to pass data to scripts in the form of arguments
• How to access system information using system environment variables
• How to access user information using user environment variables
• How to create, modify, and delete script variables
• How to limit access to variables within scripts
88
Windows Shell Script Programming for the Absolute Beginner
Project Preview:
“The Story of Buzz the Wonder Dog”
This chapter’s main project is “The Story of Buzz the Wonder Dog.” This Mad lib-style
story collects input from the reader, stores it in variables, and then uses variable sub-
stitution to tell a story using the reader’s input. The story will begin by displaying an
initial welcome screen that introduces the story, as shown in Figure 4.1.
FIGURE 4.1
The reader is then informed that in order for the story to be told, he will need to
participate, as shown in Figure 4.2.
FIGURE 4.2
The reader is
informed that his
help is needed to
write the story.
The reader will be asked a series of five questions, as shown in Figure 4.3. These
questions will be asked without providing any context as to their ultimate use.
This will help to ensure that the story is both unpredictable and humorous.
89
The answers
collected from five
questions are
substituted into
the story.
Once the reader’s input has been collected and assigned to variables within the
Windows shell script, the story is told, as shown in Figure 4.4. As the story unfolds,
the input collected from the reader is woven into the story line.
FIGURE 4.4
After the entire story has been presented, the script will end and the Windows
command prompt will be displayed, as shown in Figure 4.5.
FIGURE 4.5
variables within Windows shell scripts and lay some foundation for developing
more advanced scripts.
ION
INIT An argument is a piece of data passed to a command or script when it executes.
DEF
ION
INIT A delimiter is a marker that identifies the boundaries of individual pieces of data
DEF
passed to a script or command.
K
TRIC Don’t be fooled if you see that someone else has used commas, tabs, equal signs, or
semicolons as delimiters within Windows shell scripts. While most programmers
use blank spaces to separate arguments, the Windows shell will allow any of these
characters to serve as delimiters.
I N T HE R EAL W ORLD
As you continue to create Windows shell scripts, you may find that you sometimes
need to create more than one script to tackle certain tasks. In these situations, you’ll
probably want to start one script and then have it trigger the execution of the next
script. In this scenario, you’ll probably need to have the first script pass arguments
to the second script in order for the second script to know what to do.
91
A Windows shell script processes arguments by assigning them to parameters. The
Parameter Description
%* Lists all the arguments that have been passed to the script
%0 Stores the name of the script
%1 Stores the first argument passed to the script
%2 Stores the second argument passed to the script
%3 Stores the third argument passed to the script
%4 Stores the fourth argument passed to the script
%5 Stores the fifth argument passed to the script
%6 Stores the sixth argument passed to the script
%7 Stores the seventh argument passed to the script
%8 Stores the eighth argument passed to the script
%9 Stores the ninth argument passed to the script
Look at an example of how to write a Windows shell script that processes a pair of
arguments passed to it at execution time.
@ECHO off
ECHO %1
ECHO %2
This script should be easy to understand. It simply displays the arguments that
have been passed to it. Go ahead and create and save this script as Test.bat. Then
run it by typing its name followed by two arguments, as demonstrated below.
Test.bat C:\Temp C:\Scripts
Once executed, you should see the following results displayed in the Windows
command console:
C:\Temp
C:\Scripts
92
Handling Large Numbers of Arguments
Windows Shell Script Programming for the Absolute Beginner
Using the information just presented, you should be able to create Windows shell
scripts that can accept and process up to nine arguments at execution time. While
this will certainly accommodate most situations, at some time you may find a need to
create a script that can accept and process more than nine arguments at run time.
When you think of script parameters, think of them as being lined up in a row
with the first argument passed to the script lined up on the far left and the last
argument passed to the script lined up on the far right. At most, the Windows
shell allows you to access nine parameters at a time, as shown below.
%1 %2 %3 %4 %5 %6 %7 %8 %9
However, the Windows shell allows you to pass as many arguments as you want to
your scripts. For example, the following list defines a collection of 12 arguments
that you might want to pass to a script.
arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10 arg11 arg12
The Windows shell automatically associates each argument with its correspond-
ing parameter. For example, the first argument passed to the script would repre-
sent the script’s first parameter, as represented by %1.
While the Windows shell won’t let you directly access more than nine arguments
at a time, it does allow you to pass as many arguments as you need. To access any
arguments passed to the script beyond the ninth one, you must learn how to use
the SHIFT command. This command allows you to move to the left by one all param-
eters representing arguments passed to your script. For example, the following
command moves all of the parameters to the left by one.
SHIFT
The net effect of the previous command is that the value stored in %2 becomes %1
and the value stored in %3 becomes %2, and so on. As a result, the script’s ninth
parameter (e.g., %9) frees up and is then automatically assigned the value passed to
the script by the tenth argument. Therefore, by executing the SHIFT command re-
peatedly, you can create a script that can access every argument passed to it.
K
TRIC If you wish, you can specify the parameter position at which you begin shifting argu-
ments. For example, typing SHIFT /3 leaves the contents stored in %1 and %2 unal-
tered but shifts the values stored in the rest of the script’s input parameters. Thus the
values of the arguments stored in %3 – %9 would all be shifted to the left by one.
93
Handling Arguments That Include Blank Spaces
C:\Temp\Sample Report.doc
Since both of these files have file names that include blank spaces, you would
need to surround both file names with double quotes before passing them to your
script, as demonstrated below.
Test.bat "C:\Temp\Rough Outline.txt" "C:\Temp\Sample Report.doc"
The script, Test.bat, would then be able to reference these two file names at %1 and
%2, respectively.
SET /A Expression
SET /P Variable=[MessagePrompt]
94
When used in its first form, the SET command displays, creates, modifies, and de-
Windows Shell Script Programming for the Absolute Beginner
letes variables. Variable specifies the name of the variable to be displayed, created,
modified, or deleted. Value specifies an optional data assignment.
The second form of the SET command defines numeric variables. /A designates that
the value stored in the variable is to be treated as a number and Expression specifies
the value assigned to the variable.
The final format of the SET command allows you to interactively prompt the user
to type input, which is then assigned to a variable. /P specifies that the SET com-
mand should prompt for user input. Variable defines the name of the variable to
which the user’s input is assigned, and MessagePrompt is an optional text string that
you can use to present the user with instructions on what you want him to enter.
1. Click on Start, right-click on My Computer, and select Properties from the menu
that appears. The System Properties dialog appears.
2. Select the Advanced property sheet.
3. Click on the Environment Variables button located at the bottom on the dialog.
The Environment Variables dialog appears, as shown in Figure 4.6.
User variables associated with the currently logged-on user are displayed at the
top of the dialog. In this example, two user environment variables are shown, both
of which specify the location of different temporary folders.
95
On Windows XP,
both user and
system environment
variables can be
viewed and
modified from the
Environment
Variables dialog.
System environment variables are displayed at the bottom of the dialog. You’ll usu-
ally find a number of different system environment variables listed here, including
• COMSPEC. Specifies the location of the Windows shell (e.g., CMD.EXE).
• OS. Identifies the currently running Windows operating system.
• PATH. Specifies the default search path.
• PATHEXT. Lists file extensions that represent executable programs.
• Prompt. Specifies the default command prompt format.
• TEMP. Specifies the location of a folder where the system may store
temporary files.
• WINDIR. Identifies the folder where system files are located.
Defining a new
system environment
variable.
K
TRIC For any changes you make to user environment variables to take effect, you must log
off the computer and log back in again. For any changes you make to system vari-
ables to take effect, you must restart the computer.
Some environment variables cannot be viewed from the Environment Variables dia-
log. However, the Windows shell will let you view and reference them using the SET
command. For example, to view a list of all environment variables accessible by
your scripts, type SET at the Windows command prompt and hit the Enter key. You
should see output displayed similar to the following:
C:\>SET
COMPUTERNAME=WRKSTN0001
ComSpec=C:\WINDOWS\system32\cmd.exe
HOMEDRIVE=C:
LOGONSERVER=\\WRKSTN0001
NUMBER_OF_PROCESSORS=1
OS=Windows_NT
Path=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\COMMAND;C:\DOS;C:\WINDOWS\system3
2\WBEM
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH
PROCESSOR_ARCHITECTURE=x86
PROCESSOR_LEVEL=6
PROCESSOR_REVISION=0600
ProgramFiles=C:\Program Files
97
PROMPT=$p$g
SystemDrive=C:
SystemRoot=C:\WINDOWS
TEMP=C:\DOCUME~1\JERRYF~1\LOCALS~1\Temp
TMP=C:\DOCUME~1\JERRYF~1\LOCALS~1\Temp
USERDOMAIN=WRKSTN0001
USERNAME=Jerry Ford
windir=C:\WINDOWS
C:\>
K
TRIC While you cannot make permanent changes to environment variables from within
your Windows shell scripts, you can create variables that have the same name as
environment variables and modify their values. These variables will then tempo-
rarily override the values of the environment variables for your script.
Although you cannot see them using any of the previously mentioned procedures,
Windows 2000 and XP also provide access to a small collection of dynamically
created environment variables. These variables are listed in Table 4.2.
Variable Description
CD Stores a string representing the current working directory
DATE Stores a string representing the current system date
Time Stores a string representing the current system time
RANDOM Retrieves a random number between 0 and 32,767
ERRORLEVEL Retrieves the exit code of the previously executed command
CMDEXTVERSION Stores a string identifying the Windows shell version number
CMDCMDLINE Stores a string showing the command that was used to start the
current Windows shell session
98
Creating, Modifying, and Deleting Script Variables
Windows Shell Script Programming for the Absolute Beginner
While you are limited as to what you can do within a script with environment
variables, you have complete control over your script variables. For example, to
create a script variable called gamename and assign it a value of WonderDog, you would
use the SET command to define the variable, as shown below.
SET gamename=Wonderdog
Note that there are no blank spaces between either the variable name and the
equals sign or between the equals sign and the assigned value. If a blank space
were added before the equals sign, the Windows shell would interpret that to mean
that the blank space was part of the variable’s name. If a blank space were inserted
between the equals sign and the assigned value, the Windows shell would inter-
pret the blank space as part of the assigned text.
To change the value assigned to the variable, you would again use the SET com-
mand, as demonstrated below.
SET gamename=BuzzTheWonderDog
When used this way, the SET command simply replaces the value assigned to the
specified variable. You can also use the SET command to delete a variable by setting
the variable equal to nothing, as demonstrated below.
SET gamename=
Naming Variables
While the Windows shell is very flexible when it comes to working with variables,
there are still a few rules that you must follow to avoid errors. These rules are
outlined below.
• If you include quotation marks as part of the variable’s assigned value, the
Windows shell will treat the quotation marks as part of the value assignment.
• You may not include reserved characters in a variable’s value assignment un-
less you enclose them within double quotation marks.
• Blank spaces included before the equals sign are considered part of the
variable’s name.
• Blank spaces included after the equals sign are considered part of the
variable’s assigned value.
99
In addition to these rules, I have some additional friendly advice that you should
You use the SETLOCAL and ENDLOCAL commands together to define a starting and end-
ing location within a script where a variable and its value can be referenced. For
example, consider the following script:
@ECHO off
SETLOCAL
SET x=true
ECHO x = %x%
ENDLOCAL
ECHO x = %x%
This script begins by using the SETLOCAL command to localize the value of a variable
called x. It then assigns a value of true to x and displays its value. The ENDLOCAL command
is then used to terminate the scope of the x variable, effectively deleting it. Therefore,
when the script attempts to reference it a second time, no value is displayed. The
following output shows what you will see if you create and run this script.
x = true
x =
100
The SETLOCAL and ENDLOCAL commands can also be used to localize changes made to
Windows Shell Script Programming for the Absolute Beginner
an existing variable, with the result that any changes made to the variable within
the localized scope are discarded when the scope terminates. For example, con-
sider the following example.
@ECHO off
SET x=true
ECHO x = %x%
SETLOCAL
SET x=false
ECHO x = %x%
ENDLOCAL
ECHO = %x%
In this example, the script begins by defining a variable called x and assigning it a
value of true. It then displays this value. Next, the SETLOCAL and ENDLOCAL commands
set up a temporary localized scope in which the value of x is changed to false and
then displayed. However, as soon as the localized scope terminates, the previous
value assigned to x is restored. Thus when the value of x is displayed again, its
value is equal to true again, as shown below.
x = true
x = false
x = true
K
TRIC The SETLOCAL and ENDLOCAL commands are often used in combination with subrou-
tines and procedures, which are covered later in Chapter 7, “Creating Procedures
and Subroutines.”
In this example, x has been set to equal 1. You can also use mathematical expres-
sions to assign a numeric value to a variable, as demonstrated below.
SET /A x = 1 + 2
In addition, you can use values stored in other numeric variables in building ex-
pressions, as demonstrated below.
SET /A x = 1
SET /A y = 2
SET /A z = x + y + 3
ECHO z
If you ran this example, you would see that the value of z is 6. In each of these
examples, the = (equals sign) is used to assign numeric values to variables. The
Windows shell also provides a number of other arithmetic operators, as listed in
Table 4.3, that you can use to assign values to numeric variables.
Operator Purpose
+= Adds two values together and assigns the result
-= Subtracts one value from another and assigns the result
*= Multiplies two values and assigns the result
/= Divides one value into another and assigns the result
%= Assigns the remaining portion of a division operation (e.g., the modulus)
For example, the following statement sets the value of x equal to the current value
of x plus 1.
SET /A x += 1
102
Likewise, the following example sets x equal to x plus 5.
Windows Shell Script Programming for the Absolute Beginner
SET /A x += 5
In addition to the assignment operators listed in Table 4.3, you may use any of the
arithmetic operators shown in Table 4.4 when manipulating the contents of nu-
meric variables.
Operator Purpose
+ Adds numeric values together
- Subtracts one value from another
* Multiples two values together
/ Divides one value into another
% Determines the quotient when dividing two numbers (also referred to
as the modulus)
For example, the following statements define a variable called x, assign it an ini-
tial value of 2 and then multiplies the result by 5 before subtracting 3.
SET /A x = 2
SET /A x = x * 5 - 3
K
TRIC I don’t know if you have noticed yet or not, but when you use the /A switch with the
SET command, you can add blank spaces before and after the arithmetic operator
and the Window shell automatically ignores them. This allows you to make your
scripts more readable.
P
TRA The Windows shell follows a strict set of rules whenever it performs a mathemati-
cal operation. First, it resolves quotient values (i.e., the modulus). Then it performs
multiplication and division from left to right. Finally, it does any remaining addition
and subtraction, again working from left to right.
103
Variable String Manipulation
%VariableNameis the name of a variable to which you want to assign the result of the
substring operation. It is immediately followed by the colon character. ReplacementString
is a placeholder representing the string to be substituted (e.g., the Y string in the
previous example) and OriginalString is a placeholder representing the string in which
the replacement is to occur (e.g., the Yes string in the previous example).
Below is an example of string substitution in action. In this example, a variable
called x is set equal to a small text phrase. Then, using string substitution, a sec-
ond variable called z is set equal to the value of x, but only after a substring opera-
tion has been completed. In the substring operation, the word blue is substituted
for the word gray.
@ECHO off
SET z=%x:gray=blue%
ECHO %z%
104
If you save and run this script, you’ll see the output shown below.
Windows Shell Script Programming for the Absolute Beginner
K
TRIC You may also use string substitution to delete portions of text from a text string. To
accomplish this trick, leave the replacement string blank. For example, to remove
the word gray from the string in the previous example, you would set the value of z
as shown below.
SET z=%x:gray=%
First you specify the variable name. Then you add the colon and the tilde character (~)
exactly as shown above. Next the StartPosition placeholder is used to specify the posi-
tion of the first character in the substring. Length is optional. If Length is omitted, the
substring will consist of all characters starting at StartPosition all the way to the end of
the string. When Length is specified, the substring will consist of all the characters
beginning at StartPosition plus the number of specified characters to the right of the
starting position. To see how substring operations work, look at the following example:
@ECHO off
SET z=%x:~0,7%
ECHO %z%
In this example, the second SET statement extracts a substring from a text string
stored in the x variable. It then assigns the substring text to a variable called z.
105
The substring operation begins at character position zero (e.g., the first letter of the
COLOR EC
CLS
The initial screen welcomes the reader to the story. It consists of a series of ECHO
statements as shown below.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO W E L C O M E T O T H E ...........
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO S T O R Y O F B U Z Z T H E W O N D E R D O G !
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
PAUSE
The last statement in this section uses the PAUSE command to ensure that the reader
has the chance to read and ponder the story that is about to be told.
107
Providing the Reader with Instructions
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO Your help is needed to tell this story. All that you have to do is
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
PAUSE
This section, like all sections that follow, begins by clearing the screen before dis-
playing any text and ends by executing the PAUSE command.
108
Collecting Key Story Elements from the Reader
Windows Shell Script Programming for the Absolute Beginner
To tell the story, the script needs to collect information from the reader that will
then be assigned to the following script variables:
• player.The name of the person reading the story (a.k.a. the name of Buzz’s fic-
tional owner)
• clothes. The piece of clothing that Buzz grabs onto when saving his owner for
the first time.
• vehicle.
The type of motor vehicle that almost runs over Buzz’s owner at the
beginning of the story.
• bodypart.
The part of his owner’s body that Buzz grabs onto when saving his
owner for the second time.
• animal.The type of animal that almost runs over Buzz’s owner at the end of
the story.
These pieces of information are collected and assigned to variables using the SET
command with the /P switch, as shown below.
CLS
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO These look like really good answers. Now, let's get on with the story.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
PAUSE
Buzz's best friend was his owner, %player%. Buzz and %player% went everywhere
that day they would play in the water down by Old Man's Grove.
On one particularly hot summer Sunday, Buzz and %player% were walking down
the side of an old dirt road on their way to Old Man's Grove when
dragging %player% off the road down into the ditch. A split second later,
110
a big red %vehicle% came tearing by out of control, running right over the
Windows Shell Script Programming for the Absolute Beginner
stretch of the road where Buzz and %player% had been walking.
"Good boy," said %player%. "You really saved me that time Buzz. But what
about the man in that %vehicle%? If he doesn't slow down quickly, he'll never
make the turn at Old Man's Grove!" %player% stared as the %vehicle% barreled
down the road. When %player% looked back to see Buzz, the four-legged friend
was gone.
Moments later, as the %vehicle% was about to crash into the grove, Buzz
leaped off of the top of a large bolder and onto the top of the
%vehicle%. He then squeezed his way through an opening in the back of the
Thinking quickly, Buzz pulled the driver out of the way and took over
at the wheel, quickly applying the brakes and stopping the %vehicle%
just inches before it reached the edge of the grove. The quick-
thinking Buzz saw that the man was not breathing and began pulling
By the time %player% arrived a few minutes later, the man had
revived and was sitting upright on the ground, petting Buzz as the
dog licked his face. "This here your dog?" the driver asked. "Yes sir,"
said %player% with a great big smile. "Well, it looks like I owe you a lot.
Your dog just saved my life. Had he not given me CPR, I think I'd have
"Wow!" said %player%, running over to hug his four-legged friend. Just then
Buzz unexpectedly leaped up, grabbing %player% by the %bodypart%, tossing %player%
clear of the dirt path that %player% had been running on. Moments later, a
big white %animal% came scurrying down that very path, and Buzz the Wonder
Dog ran off after it. "I hope that %animal% will be OK" said the driver.
The End
111
I suggest that you attempt to complete the development of this story before I show
REM ***************************************************************************
REM
REM
REM Description: This Windows shell script tells the story of "Buzz the Wonder
REM
REM ***************************************************************************
COLOR 0E
CLS
REM Write the name of the story to the Windows command console's title bar
ECHO.
ECHO.
112
ECHO.
Windows Shell Script Programming for the Absolute Beginner
ECHO.
ECHO.
ECHO.
ECHO W E L C O M E T O T H E ...........
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO S T O R Y O F B U Z Z T H E W O N D E R D O G !
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
PAUSE
CLS
REM Let readers know that their help is required to write the story
ECHO.
ECHO.
ECHO.
113
ECHO.
ECHO.
ECHO Your help is needed to tell this story. All that you have to do is
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
PAUSE
CLS
ECHO.
ECHO.
ECHO.
ECHO.
114
ECHO.
Windows Shell Script Programming for the Absolute Beginner
ECHO.
ECHO.
REM Determine the piece of clothing that Buzz grabs onto when saving
ECHO.
REM Determine what type of vehicle almost runs over Buzz and his owner
ECHO.
REM Determine the body part Buzz grabs onto when saving his owner for
ECHO.
REM Determine what type of animal almost runs over Buzz's owner the
ECHO.
ECHO.
ECHO These look like really good answers. Now, let's get on with the story.
115
ECHO.
ECHO.
ECHO.
ECHO.
Pause
CLS
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO Once upon a time there lived a very special little dog called Buzz.
ECHO.
ECHO Buzz's best friend was his owner, %player%. Buzz and %player% went everywhere
ECHO.
ECHO together. Sunday was their favorite day to spend together because on
ECHO.
ECHO that day they would play in the water down by Old Man's Grove.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
116
ECHO.
Windows Shell Script Programming for the Absolute Beginner
ECHO.
ECHO.
ECHO.
PAUSE
CLS
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO On one particularly hot summer Sunday, Buzz and %player% were walking down
ECHO.
ECHO the side of an old dirt road on their way to Old Man's Grove when
ECHO.
ECHO suddenly Buzz stopped and spun around, grabbing %player%'s %clothes%,
ECHO.
ECHO dragging %player% off the road down into the ditch. A split second later
ECHO.
ECHO a big red %vehicle% came tearing by out of control, running right over the
ECHO.
ECHO stretch of road where Buzz and %player% had been walking.
ECHO.
ECHO.
ECHO.
117
ECHO.
ECHO.
PAUSE
CLS
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO "Good boy," said %player%. "You really saved me that time Buzz. But what
ECHO.
ECHO about the man in that %vehicle%? If he doesn't slow down fast he'll never
ECHO.
ECHO make the turn at Old Man's Grove!" %player% stared as the %vehicle%
ECHO.
ECHO barreled down the road. When he looked back to see Buzz, his four-legged
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
118
ECHO.
Windows Shell Script Programming for the Absolute Beginner
ECHO.
PAUSE
CLS
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO Moments later, as the %vehicle% was about to crash into the grove, Buzz
ECHO.
ECHO leaped off of the top of a large bolder onto the top of the
ECHO.
ECHO %vehicle%. He then squeezed his way through an opening in the back of the
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
119
ECHO.
PAUSE
CLS
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO Thinking quickly, Buzz pulled the driver out of the way and took over
ECHO.
ECHO at the wheel, quickly applying the brakes and stopping the %vehicle%
ECHO.
ECHO just inches before it reached the edge of the grove. The quick-
ECHO.
ECHO thinking Buzz saw that the man was not breathing and began pulling
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
120
ECHO.
Windows Shell Script Programming for the Absolute Beginner
ECHO.
PAUSE
CLS
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO By the time %player% arrived a few minutes later, the man had
ECHO.
ECHO revived and was sitting upright on the ground, petting Buzz as the
ECHO.
ECHO dog licked his face. "This here your dog?" the driver asked "Yes sir,"
ECHO.
ECHO said %player% with a great big smile. "Well, it looks like I owe you a lot.
ECHO.
ECHO Your dog just saved my life. Had he not given me CPR, I think I'd have
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
121
ECHO.
PAUSE
CLS
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO "Wow!" said %player%, running over to hug his four-legged friend. Just then
ECHO.
ECHO Buzz unexpectedly leaped up, grabbing %player% by the %bodypart%, tossing
ECHO.
ECHO %player% clear of the dirt path that %player% had been running on. Moments later, a
ECHO.
ECHO big white %animal% came scurrying down that very path, and Buzz the Wonder
ECHO.
ECHO Dog ran off after it. "I hope that %animal% will be OK" said the driver.
ECHO.
ECHO.
ECHO.
Now that the script is complete, run it a number of different times, making sure to
feed it different input each time. If any errors occur, go back and check your typing
to make sure that you did not mistype any of the script’s statements. Once you have
everything working properly, pass your game on to a friend, and see what they think.
122
Summary
Windows Shell Script Programming for the Absolute Beginner
In this chapter, you learned how to write scripts that could accept and process input
passed to them at execution time. You also learned the ins and outs of working with
environment and script variables. This included how to create, modify, and delete
variables from within your Windows shell scripts, as well as how to access and per-
manently modify environment variables. In addition, you learned how to manipu-
late and extract portions of variables that contained text strings and how to perform
mathematical operations on variables containing numeric data.
EXERCISES
1. Further expand on “The Story of Buzz the Wonder Dog” by adding a few more
paragraphs of story line.
2. Try removing the CLS statements from the story portion of the script. This will result
in a scrolling effect each time the reader presses a key to un-pause the story.
Hint: You will have to adjust the number of ECHO. statements to make the effect
look right.
3. Make the story’s outcome even more unpredictable by reviewing the story and
looking for keywords that you can replace with variables and then prompt the
reader to supply input for these new variables.
Applying
5
C H A P T E R
Conditional Logic
Y
ou’ve already seen examples of conditional logic presented in many of the
chapter projects presented earlier in this book. That’s because conditional
logic is such a core programming concept that it is all but impossible to write
a useful script of any complexity without using some form of conditional logic.
In Chapter 3, “Windows Shell Scripting Basics,” you learned how to perform condi-
tional logic using compound commands in which the execution of one command was
made dependent on the success or failure of another command. In this chapter, you
will learn how to use the IF statement to implement conditional logic that goes far
beyond the capabilities of simple compound commands. You’ll also learn how to cre-
ate multi-line IF statements that allow you to execute numerous commands based on
the results of a single conditional test. In addition, you’ll learn how to nest, or embed,
one IF statement within another to produce powerfully intricate logic.
Specifically, you will learn
• To work with each of the various forms of the IF statement
• How to determine whether variables have been defined
• How to determine whether errors have occurred when executing commands
• How to determine what version of the Windows shell is being used to run your scripts
• How to determine whether files or folders exist before you attempt to access them
124
Windows Shell Script Programming for the Absolute Beginner
Project Preview:
The Guess a Number Game
This chapter’s main programming project is called the Guess a Number game. It is
designed to give you further experience in working with conditional logic. To com-
plete the game, you will create a Windows shell script that prompts the player for
a number and then compares that number to a randomly generated number to see
if it is less than, equal to, or higher than the player’s chosen number. The game
will give the player hints that identify whether the player’s guess is high or low
and will keep a count of the number of guesses that the player ultimately makes
before correctly guessing the randomly selected mystery number.
Figure 5.1 shows the game’s opening screen, which greets the player, displays the
name of the game, and waits for the player to press a key before continuing.
FIGURE 5.1
Figure 5.2 shows the game prompting the player to make their first guess. As you
can see, the player types in a guess on the same line as the prompt and presses the
Enter key to submit it.
Figure 5.3 shows the kind of feedback that players receive when their guess is too
low. The game will continue to prompt the player to enter guesses until the player
correctly guesses the mystery number.
Likewise, Figure 5.4 shows the message that the game displays when the player’s
guess is too high.
When the player finally guesses the mystery number, the screen shown in Figure
5.5 is displayed, informing the player that the number has been guessed correctly.
In addition, the total number of guesses made by the player is also displayed.
125
The player is
prompted to enter
a guess.
FIGURE 5.3
FIGURE 5.4
FIGURE 5.5
Type Function
IF Performs a true/false test to determine whether one or more
commands should be executed
IF...ELSE Executes either of two sets of commands based on the outcome
of a conditional test
IF DEFINED Determines whether a variable already exists
IF ERRORLEVEL Checks the exit code of the previously executed command
IF CMDEXTVERSION Retrieves a numeric value indicating the current version of the
Windows shell
IF EXIST Determines whether a file or folder exists
IF NOT Performs a conditional test and takes an action based on a
negative result
Loosely translated, the above statement reads like this: “If the first specified condi-
tion equals the second specified condition, then the specified command will be
executed.” Otherwise it won’t be executed. Look at the following example:
IF %OS% == Windows_NT ECHO The script is running on a supported operating system
127
In this example, the value assigned to an environment variable called OS is com-
K
TRIC The %OS% variable identifies the type of operating system currently running. This
variable will be set equal to Windows_NT on any computer running a Windows NT,
2000, XP, or 2003 operating system.
Note that in the previous example blank spaces were included both before and
after the double equals sign. Although not required, adding blank spaces in this
manner helps make things easier to read. Now look at another example. In this
example, the statement is set up to compare the value stored in the first argument
passed to the script against a text string of PLAY. If the results of the test are true,
then the ECHO command that follows will be executed.
@ECHO off
Save this example as a script and run it by entering the name of the script followed
by a blank space and then the word Play. You should see the following output dis-
played:
Ready to begin play.....
Now, run the script again and either pass it an argument other than the word Play
or just don’t enter anything at all. As you’ll see, the following error will appear:
ECHO was unexpected at this time.
This error occurred because the value of %1% was not set and the Windows shell
ended up with a logical statement that looked like the one shown below. Since this
statement is syntactically incorrect, the error occurred.
IF == Play ECHO Ready to begin play.....
There may be times when you want your scripts to keep on running even when
they are started without any arguments. For example, you could perform a test to
see if an argument was supplied, and if it wasn’t, you could instead use a default
value that you hard coded into your script. To prevent the above error from appear-
ing, you should enclose both of the conditionals tested by the IF statement within
a pair of matching double quotation marks, as shown below.
IF "%1%" == "Play" ECHO Ready to begin play.....
128
Using double quotation marks in this manner does not affect the results of the test
Windows Shell Script Programming for the Absolute Beginner
when both conditions are equal. They still remain equal even with the addition of
the double quotation marks. However, in the case where the argument is missing,
formatting your IF statement in this manner prevents an error because the Win-
dows shell would interpret the command as shown below. Syntactically, this passes
the muster and allows the script to continue executing without an error.
IF "" == "Play" ECHO Ready to begin play.....
There are other times when you will want to enclose your variables within double
quotation marks. For example, there may be a time when you write a script that
prompts the user for input. However, you may have no way of knowing in advance
whether users will include one or more blank spaces in their response. To ensure
that the blank spaces are properly interpreted, you should enclose the variable
within double quotes. You may remember from Chapter 1, “Introducing Windows
Shell Scripting,” that when you created the Knock Knock joke game you had to
make the player responsible for enclosing his response inside double quotation
marks. Using this new technique, you can rewrite the script and unburden the
player from that responsibility.
In the previous example, you compared a variable’s value against a hard-coded
text string. However, you can just as easily compare the values stored in two vari-
ables, as demonstrated below.
SET hisname=Alexander
SET hername=Molly
When comparing text string values against one another, the Windows shell exam-
ines not only the text of both strings but also their case. Therefore, for example, it
would interpret X and x as not being equal. However, if you wish, you can override
this case-sensitivity requirement and perform a case-insensitive comparison by
using the /I switch, as demonstrated below.
SET hisname=CHRIS
SET hername=Chris
IF /I %hisname% == %hername% ECHO We have two people named Chris with us today.
In addition to determining whether two strings are equal, the IF statement pro-
vides the ability to perform a host of mathematical comparisons. For example,
the following statements demonstrate how to compare the values stored in two
numeric variables.
129
SET /A totalcount = 10
If both conditions are equal, then command1 is executed; otherwise, command2 is ex-
ecuted. You must place both commands inside parentheses for the Windows shell
to recognize the ELSE portion of the statement. The following statement demon-
strates one particularly good use of the IF...Else statement:
IF "%OS%" == "Windows_NT" (ECHO Script now executing) ELSE (GOTO :EOF)
In this example, the IF statement begins by checking to see if the script is executing on
a computer running Windows NT, 2000, XP, or 2003. If the result of the comparison is
true, then a message announces that the script will now begin executing. Otherwise, if
the comparison results in a value of false, the ELSE portion of the statement executes,
in which case a GOTO :EOF causes the script to terminate its own execution.
K
TRIC By including a check of the OS variables at the beginning of your Windows shell
scripts, you can prevent their accidental execution on unsupported operating sys-
tems such as Windows 95, 98, or Me. These operating systems lack a robust script-
ing environment, and while your scripts will try to run on them, they probably won’t
run for long before an error occurs.
of the environment variable on the other computer, your script would probably
fail when it tried to reference a variable that was not defined. This is because the
Windows shell returns an empty value any time it is unable to locate a variable.
Depending on how you wrote your script, what it was designed to do, and at what
point in the script the variable reference occurred, the results could be unpredict-
able. As a result, your script may have done nothing, or it may have had the oppor-
tunity to complete a portion of its task, leaving you to manually figure out what
was and was not done and potentially having a mess to clean up.
However, you could avoid this problem by adding code to the beginning of your
script that would prevent it from running in the event that it could not find your
custom environment variable. This is accomplished using the IF DEFINED statement,
which has the following syntax:
IF DEFINED variable command
P
TRA Even the best programmers run into syntax and logical errors, so don’t be shocked when
they happen to you. To help you work your way through these types of situations, I’ll give
you some basic debugging tips in Chapter 8, “Debugging and Error Handling.”
One way to deal with run-time errors is to try to anticipate places within your
scripts where errors are likely to occur, and then test to see if they occurred. You
can do this using the IF ERRORLEVEL statement, which checks the exit code of the
previously issued command.
ION
INIT An exit code (or return code) is a numeric value returned by commands that indi-
DEF
cates whether they ran successfully or experienced an error.
You can use either of two versions of the IF ERRORLEVEL statement when developing
your Windows shell scripts. The syntax for the first version of the IF ERRORLEVEL
statement is outlined below.
IF ERRORLEVEL exitcode command
132
exitcode is a placeholder representing a numeric value that specifies the minimum
Windows Shell Script Programming for the Absolute Beginner
error level that you are looking for. If the exit code returned by the previously
executed command is equal to or greater than the value specified by exitcode, then
the specified command is executed. Otherwise the command is not executed and
the script continues processing. For example, look at the following statements:
COPY c:\Script\TestScript.bat C:\Temp
IF ERRORLEVEL 1 ECHO Copy operation terminated. The specified file was not found.
The first statement attempts to copy a file to the C:\Temp folder. The second state-
ment checks to see if an error occurred when the first statement executed and
displays an error message if an error did occur.
The syntax for the second version of the IF ERRORLEVEL statement is outlined below.
IF ERRORLEVEL == exitcode
This time exitcode specifies a specific error code that must be exactly matched in
order to trigger the execution of the specified command. In other words, if you set
exitcode equal to 2, as demonstrated below, and an exitcode of 1 is returned, the
execution of the specified command is skipped.
IF "%ERRORLEVEL%" == "2" ECHO Fatal error occurred & GOTO :EOF
In the above example, the IF ERRORLEVEL statement checks to see if the previous
command returned an exit code of 2, and if it did, an error message is displayed
and the script’s execution terminates.
By using the IF CMDEXTVERSION statement to check the value of the CMDEXTVERSION vari-
able, you can enable your scripts to detect which version of the Windows shell is
being used to execute them and then to react accordingly. For example, if your
scripts make use of command extensions, you might halt script execution, or you
might use conditional logic to have your scripts skip certain steps.
The syntax you must follow to use the IF CMDEXTVERION statement is outlined below.
IF CMDEXTVERSION VersionNo Command
VersionNo is a placeholder that represents the Windows shell version number that
you want to test for, and Command is a Windows command that will be executed if the
value of CMDEXTVERSION is equal to or less than the value specified by VersionNo. For
example, the following script checks to see whether the script is being executed on
a computer running Windows NT, 2000, XP, or 2003, and if it isn’t, the script termi-
nates its own execution. Using this programming technique, you can prevent your
Windows shell scripts from trying to run on other Windows operating systems.
@ECHO off
command executes. Using the IF EXIST statement you can take steps to prevent
these types of errors.
file is a placeholder representing the name of the file to be searched for, and
command specifies a command that will execute if the specified file is found.
In the next example, a Windows shell script begins by determining whether a file
called Games.txt exists within a folder called C:\Scripts. If the file exists, then the
script says so using an ECHO statement before using a SET statement to display a
prompt requesting permission to overwrite the file with a new file. If the user
types in a response of n, then the script leaves the existing file alone and termi-
nates its own execution. However, if the user responds by entering a y (or another
character other than n), then the script redirects the contents of an ECHO statement
using the > character. The effect of this statement is to replace the contents of the
file with the text supplied by the ECHO statement.
@ECHO off
IF /I %reply% == n (
) ELSE (
)
135
Determining Whether a Folder Currently Exists
C:\Scripts>dir
Directory of C:\Scripts
0 File(s) 0 bytes
C:\Scripts>
For example, the following Windows shell script demonstrates how to verify the
existence of a folder:
@ECHO off
IF EXIST C:\Scripts\. (
) ELSE (
ECHO C:\Scripts folder not found. Creating folder and report. & MKDIR C:\Scripts
)
136
In this example, the script checks to see if the C:\Scripts folder exists by looking
Windows Shell Script Programming for the Absolute Beginner
for C:\Scripts\. It the folder exists, a message is displayed. However, if the folder
does not exist, the ELSE part of the IF EXIST statement is executed and, as a result,
the C:\Script folder is created using the MKDIR command.
IF NOT
By adding the NOT keyword to the IF statement, you can test for the opposite of any
condition that you might want to check. The syntax for this form of the IF state-
ment is outlined below.
IF NOT condition1 == condition2 command
For example, you might want to use the IF NOT statement when working with vari-
ables. The following example demonstrates how to set up an IF NOT statement that
checks to see if a variable called Scripts has been set equal to C:\Scipts, and if it has
not, its value is changed.
IF NOT "%Scripts%" == "C:\Scripts" SET Scripts=C:\Scripts
I recommend that you use the IF NOT statement in every Windows shell script you
create (especially if you share them with other people) and that you set it up to
prevent the script’s accidental execution on unsupported Windows operating sys-
tems (e.g., Windows 95, 98, and Me). This can be easily accomplished by making
the statement a part of your standard Windows shell template as demonstrated
below.
@ECHO off
REM ***************************************************************************
REM
REM
REM
REM ***************************************************************************
IF NOT "%OS%" == "Windows_NT" ECHO Unsupported operating system & GOTO :EOF
IF NOT DEFINED
The NOT keyword seems especially suited to working with the IF DEFINED statement,
providing an easy means of checking to see if a variable does not exist. The syntax
for this form of the IF statement is outlined below.
IF NOT DEFINED variable command
For example, the following IF NOT DEFINED statement checks to make sure that an
environment variable called Scripts does not already exist before defining a script
variable of the same name. Using this technique, you can set up your Windows
shell scripts to look for environment variables that control their execution, but
still fall back and use hard-coded default values in the event that the environment
variables are not present.
IF NOT DEFINED %Scripts% SET Scripts=C:\Scripts
You may also invert the IF ERRORLEVEL statement with the NOT keyword by using the
following syntax:
IF NOT ERRORLEVEL exitcode command
For example, when executed the following script tries to copy a file named
TestScript.bat from the C:\Scripts folder to the C:\Temp folder. The script then
uses the IF NOT ERRORLEVEL statement to determine whether the copy operation suc-
ceeded. If an error occurred when copying the file, the script clears the screen,
displays an error message, and then terminates its own execution.
@ECHO off
IF NOT %ERRORLEVEL% == 0 CLS & ECHO Fatal error occurred & GOTO :EOF
IF NOT CMDEXTVERSION
The IF NOT CMDEXTVERSION statement is used to validate that the version of the Win-
dows shell being used to process the script is not lower than a specified value. The
syntax for this form of the IF statement is outlined below.
IF NOT CMDEXTVERSION VersionNo Command
For example, the following Windows shell script terminates its own execution in
the event it discovers that it is not running on a Windows 2000, XP, or 2003 operat-
ing system:
@ECHO off
Likewise, the following script terminates the script’s execution if it has not been
started on a Windows NT, 2000, XP, or 2003 operating system.
@ECHO off
Using this statement, you can determine whether a file or folder exists before try-
ing to work with it. For example, the following Windows shell script checks to see
if the C:\Scripts folder exists and then creates the folder if it doesn’t exist.
@ECHO off
ECHO C:\Scripts folder not found. Creating folder and report. & MKDIR C:\Scripts
) ELSE (
)
140
As you can see, using this form of the IF statement, you must enclose all of the
Windows Shell Script Programming for the Absolute Beginner
statements that you want the IF statement to execute inside a pair of matching
parentheses. For example, you could rewrite the previous compound command
example using a multi-line IF statement, as shown below.
IF NOT %ERRORLEVEL% == 0 (
CLS
GOTO :EOF
As you can see, even with this small example, the multi-line form of the IF state-
ment makes things a lot easier to read.
REM If the correct number was not guessed, check to make sure it is in bounds
IF %1 GTR 32767 ECHO Your guess is out of bounds! & GOTO :HELP
REM The guess was in bounds, so check to see if it was low or high
141
IF %1 LSS %MysteryNumber% GOTO :GuessAgain
In this example, the script set a variable called MysteryNumber equal to a randomly
selected number between 0 and 32,767. It then checks the value of an argument
passed to it to see if the value of the argument is equal to the value assigned to the
MysteryNumber variable. If the two values are equal, nothing happens. But if they are
not equal, the IF statements nested within the first IF statement begin to execute
in order to determine what the script should do next. If the nested IF statements
were moved from inside the first IF statement and placed outside of the state-
ment, as shown below, the script would still work. However, the previously embed-
ded IF statements would be needlessly executed in the event that the argument
passed to the script was equal to the randomly generated number.
@ECHO off
REM If the correct number was not guessed, check to make sure it is in bounds
IF %1 GTR 32767 ECHO Your guess is out of bounds! & GOTO :HELP
Rem The guess was in bounds, so check to see if it was low or high
Clearly, there is no point to executing the last four IF statements if the first IF
statement did not determine that a match had not occurred. Not only is this sec-
ond script less efficient, but it is also intuitively more difficult to read and under-
stand than the first script.
142
Performing Different Kinds
Windows Shell Script Programming for the Absolute Beginner
of Comparisons
Up to this point in this chapter, you have seen the use of the == characters repeat-
edly as a means of comparing two conditions to determine whether they are equal.
The Windows shell supports a number of other comparison operators, which you
can use to perform even more complex comparisons. These comparison operators
are listed in Table 5.2.
Operator Description
== Determines whether two values are equal
EQU Determines whether two values are equal
LSS Determines whether one value is less than another
GTR Determines whether one value is greater than another
LEQ Determines whether one value is less than or equal to another
GEQ Determines whether one value is greater than or equal to another
NEQ Determines if one value is not equal to another
For example, you can compare the value of a variable as shown below.
IF NOT "%OS%" == "Windows_NT" GOTO :EOF
Alternatively, you could rewrite this same statement using the EQU operator, as
shown below.
IF NOT "%OS%" EQU "Windows_NT" GOTO :EOF
The operators listed in Table 5.2 enable you to make numerous types of numeric
comparisons, as demonstrated by the following example:
SET /a Counter = 3
In this example, the value of a variable is arbitrarily set equal to 3 to facilitate the
comparison operation that follows. The next statement checks to see if the value
of Counter is less than or equal to 5. Since this is the case, the statement displays a
message in the Windows command console.
143
Back to the Guess a Number Game
COLOR 0E
CLS
SET RandomNo=%random%
SET /a NoGuesses = 0
TITLE = T H E G U E S S A N U M B E R G A M E - %RandomNo%
144
The first three statements disable the display of script statements, set the color
Windows Shell Script Programming for the Absolute Beginner
scheme of the Windows command console to yellow on back, and clear the screen.
The next statement uses the environment variable random to retrieve a random num-
ber between 0 and 32,767 and assign its value to a variable called RandomNo. Next, a
numeric variable called NoGuesses is defined and assigned an initial value of 0. The
script will use this variable to keep track of the number of guesses made by the
player. The last statement shown above displays the name of the game in the Win-
dows command console’s title bar.
K
TRIC Notice that I also displayed the value of the randomly generated number in the Win-
dows command console’s title bar. I did this to make tracking this value easy while
I developed this script. This way, each time that I ran and tested the script, I could
easily tell what the mystery number was and determine if the script was performing
as expected. Of course, when you are done developing and testing the script, you’ll
want to remove its display.
ECHO.
ECHO.
ECHO.
ECHO W E L C O M E T O T H E ...........
ECHO.
ECHO.
ECHO.
ECHO.
ECHO G G U U E S S A A NN N U U MM MM B B E R R
ECHO.
ECHO.
ECHO G A M E !!!
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
PAUSE
CLS
ECHO.
ECHO.
ECHO.
ECHO.
146
ECHO.
Windows Shell Script Programming for the Absolute Beginner
SET /a NoGuesses += 1
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
PAUSE
GOTO :BEGINLOOP
147
)
ECHO.
ECHO.
ECHO.
PAUSE
GOTO :BEGINLOOP
P
TRA The Guess a Number game assumes up front that the player will always enter a
number. However, people can be very unpredictable, especially when they interact
with computers. Many programming and scripting languages allow you to test input
to determine whether it is numeric, thus allowing you to accept or reject user input
based on its data type. Unfortunately, Windows shell script does not provide this
capability. You might think that since the script is set up to expect numeric input
that an error will occur if the player enters non-numeric input. However, because of
the manner in which the Windows shell works, it won’t produce an error. Instead,
any text input entered by the player will be evaluated as being greater than the
mystery number (or any number for that matter).
winning the game and to display the mystery number and the total number of
guesses that it took to guess the number. These two pieces of data are presented by
embedding the variables that contain this information inside the ECHO statements
as shown below in bold.
CLS
COLOR E0
ECHO.
ECHO * * * * * * * * * * * *
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO * * * * * * * * * * * *
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
GOTO :EOF
149
K
TRIC Although it is not required in this situation, I added the GOTO :EOF statement to the
REM ***************************************************************************
REM
REM
REM Description: This Windows shell script game challenges the play to try to
REM guess a number between 0 & 32,767 in the fewest possible number of guesses
REM
REM ***************************************************************************
COLOR 0E
CLS
REM Define & initialize a variable to track the player's number of guesses
SET /a NoGuesses = 0
REM Write the name of the game in the Windows command console's title bar.
REM Also display the randomly selected number to the right of the game's name
TITLE = T H E G U E S S A N U M B E R G A M E - %RandomNo%
ECHO.
ECHO.
ECHO.
ECHO.
ECHO W E L C O M E T O T H E ...........
ECHO.
ECHO.
ECHO.
ECHO.
ECHO G G U U E S S A A NN N U U MM MM B B E R R
ECHO G G U U E S S A A N NN U U M M B B E R R
ECHO.
ECHO.
ECHO G A M E !!!
ECHO.
ECHO.
ECHO.
ECHO.
151
ECHO.
PAUSE
:BEGINLOOP
CLS
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
REM Add one to the total number of guesses made by the player
SET /a NoGuesses += 1
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
152
ECHO Your guess was too low. Try again.
Windows Shell Script Programming for the Absolute Beginner
ECHO.
ECHO.
PAUSE
GOTO :BEGINLOOP
ECHO.
ECHO.
ECHO.
PAUSE
GOTO :BEGINLOOP
CLS
ECHO.
ECHO * * * * * * * * * * * *
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO * * * * * * * * * * * *
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
GOTO :EOF
Once you have finished creating the entire script, give it a go and see how it works.
If you did not make any typos when keying it in, you should find that it works
exactly as advertised. When you test the script, try feeding it a range of different
data. For example, start by entering a number between 1 and 32,767. Once that
works, try supplying it with a negative number and with a number greater than
32,767. Once you are sure that the script is handling these numbers correctly, try
entering a few text characters as input and see what happens then.
154
Summary
Windows Shell Script Programming for the Absolute Beginner
In this chapter, you learned how to work with all of the forms of the IF statement
supported by the Windows shell. You learned how to check for the existence of
files, folders, and variables. You also learned how to test for errors and figure out
what version of the Windows shell is being used to run your scripts. On top of all
this, I showed you how to create multi-line IF statements as well as how to nest IF
statements within one another to create powerful conditional logic tests. You also
learned how to invert conditional tests using the NOT keyword. Finally, I showed
you how to create the Guess a Number game, in which you learned how to use
conditional logic to create a game that runs until the player successfully guesses a
randomly generated number.
EXERCISES
1. To make the game easy to debug, I added the display of the randomly selected
mystery number to the title bar. Once you have the game up and running prop-
erly, disable the display of this number.
2. Modify the Guess a Number game so that it collects additional statistics be-
yond the number of guesses attempted. For example, track the number of high
guesses and low guesses separately.
3. Modify the Guess a Number game to give players better clues as they begin to
get close to the mystery number. For example, as soon as players get within
200 of the mystery number you might tell them that they are getting warm, and
when they get within 20 you might tell them that they are getting hot.
4. Modify the Guess a Number game so that it offers to restart itself and let the
player play another game.
Process
Collections of Data
I
n order to create computer games or really powerful administrative scripts,
you need a way of repeating a series of steps in order to effectively process
collections of data. For example, in the Guess a Number game that you cre-
ated in Chapter 5, “Applying Conditional Logic,” you needed to set the game up so that
it would repeatedly give the user chances to guess the mystery number. This kind of
iterative or repetitive processing is known as looping.
The Windows shell provides the FOR command as your tool for creating loops. Like the
IF command, the FOR command comes in many different flavors, allowing you to create
Windows shell scripts that loop through collections of files and folders, command
output, and text strings, and also to repeatedly execute one or more commands. By
creating scripts that iteratively loop through collections of data, you can process enor-
mous amounts of data and perform tasks in seconds that would otherwise take you
hours to perform manually, and you can do so without the mistakes that humans often
make when performing tedious work.
Specifically, you will learn
• How to process collections of files and folders
• How to execute a collection of statements a predetermined number of times
• How to loop through and process the output produced by the execution of your
script commands
• How to process the contents of files
156
Windows Shell Script Programming for the Absolute Beginner
Project Preview:
The Six-Million-Dollar Quiz
In this chapter’s main project, you will learn how to create the Six-Million-Dollar
Quiz. This quiz will test the player’s knowledge of the 1970s TV show, The Six Mil-
lion Dollar Man. By completing this script, you will learn how to create and con-
trol a text-based menu as well as how to create Help and About screens for your
games. The game will present the player with 10 questions and then grade the
answers entered by the player. The results will be displayed on the Windows com-
mand console as well as in a text report, which the script will store on the
computer’s hard drive.
Like all the other games in this book, the game will begin by presenting the player
with a welcome screen. However, this welcome screen will serve a dual purpose by
also presenting the player with a text menu that controls the game execution, as
shown in Figure 6.1.
FIGURE 6.1
The game’s
welcome screen
also provides a text-
based menu that
controls the game’s
execution.
By typing Help, the player can view information that explains the operation of the
game, as shown in Figure 6.2. This help text remains on the screen until the player
presses a key, at which time the welcome screen is redisplayed.
By typing About, the player can view information about the game and its author, as
shown in Figure 6.3. Again, the player will be returned to the welcome screen after
pressing a key.
When the player begins, the game presents a series of 10 questions. Some are “fill in
the blank” questions, as demonstrated in Figure 6.4. Others are true/false or yes/no.
157
FIGURE 6.3
By creating an About
screen, you provide
a place to advertise
information about
yourself and
your game.
FIGURE 6.4
Once the player has answered all of the questions, the game will grade his answers
and present a score card, as demonstrated in Figure 6.5.
Finally, the game creates a text report that provides detailed information about
the player’s quiz results, as demonstrated in Figure 6.6.
158
Windows Shell Script Programming for the Absolute Beginner
FIGURE 6.5
FIGURE 6.6
Examining the
detailed score card
file created by
the game.
Creating Loops
You’ve already seen how to create loops within Windows shell scripts using labels
and the GOTO command. This type of loop provides the ability to jump from one
point in a script to an earlier point in order to repeat the execution of previous
steps, yet this type of loop is generally considered somewhat clumsy. I’ll show you
a much better way to group statements together for frequent execution in Chapter 7,
“Creating Procedures and Subroutines.”
The Windows shell provides support for a second type of loop using the FOR com-
mand. Loops created with the FOR command are highly specialized. A number of
variations of the FOR loop can be established, each of which is designed to process a
159
different type of data. Specifically, you can create FOR loops that can iteratively
The /switch parameter is used to specify the types of data that the loop will process.
A list of the switches supported by the FOR command is provided in Table 6.1.
Switch Description
/l Sets up the loop to process a range of values
/f Sets up the loop to process all elements stored within a string
/d Sets up the loop to process all files stored within a specified folder
/r Sets up the loop to process all subfolders stored within a specified
parent folder
P
TRA The FOR loops iterator is case-sensitive. This means that I and i are not considered
the same. Be careful and make sure that you are consistent when referencing the
FOR loops iterator variable so that you don’t accidentally mix up the case.
Each of the variations of the FOR command mentioned above are outlined in detail
in the sections that follow.
You can further refine the execution of this type of loop by specifying any of the
options listed in Table 6.2.
Option Function
DELIMS=x Changes the characters used to delimit data from the default of a
blank space to the specified collection of characters
EOL=c Specifies an end-of-line character
SKIP=n Sets a specific number of lines to be skipped at the top of the file
TOKENS=a,b, a-c Sets the tokens to be used when processing data
ION
INIT A token represents a piece of data in a text string.
DEF
161
This particular form of the FOR loop parses out the contents of the specified string
ECHO %%a
ECHO %%b
ECHO %%c
ECHO %%d
ECHO %%e
By specifying DELIMS=, I have set up the FOR loop to parse out arguments passed to
the script and separated by the , character. By specifying TOKENS=1-5, I have config-
ured the FOR loop so that it processes only the first five arguments passed to the
script, regardless of how many are actually passed. When executed, this script dis-
plays a list of the first five arguments passed to the script. However, you could
easily modify the functionality of this script by replacing the ECHO command with
a different command. For example, you could change each ECHO command to DEL in
order to delete a list of files passed to the script.
Before moving on to the next type of FOR loop, look at one more example. In this
example, shown below, a Windows shell script has been set up to process the con-
tents of a string variable. This variable has been assigned a value comprised of five
names, each of which is separated, or delineated, by a blank space.
162
@ECHO off
Windows Shell Script Programming for the Absolute Beginner
ECHO %%a
ECHO %%b
ECHO %%c
Since the default delineator for the FOR command is a blank space, I did not have to
specify the DELIMS option this time. In addition, since I only wanted to parse out the
first three names stored in the string, I set the TOKENS option equal to 1-3.
The options parameter represents different parsing capabilities for the FOR com-
mand, as listed in Table 6.2. Also, take note of the fact that the command whose
output is to be parsed must be enclosed inside both a pair of matching single
quotation marks as well as a pair of parentheses.
Now look at this form of the FOR statement in action. In this example, I’ve created a
Windows shell script that executes the SET command. When executed without any
additional arguments, the SET command displays a listing of environment vari-
ables, which can be somewhat hard to read, as demonstrated below.
C:\>set
COMPUTERNAME=WRKSTN0001
ComSpec=C:\WINDOWS\system32\cmd.exe
HOMEDRIVE=C:
LOGONSERVER=\\WRKSTN0001
NUMBER_OF_PROCESSORS=1
OS=Windows_NT
Path=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\COMMAND;C:\DOS;C:\WINDOWS\system3
2\WBEM
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH
PROCESSOR_ARCHITECTURE=x86
PROCESSOR_LEVEL=6
PROCESSOR_REVISION=0600
ProgramFiles=C:\Program Files
PROMPT=$p$g
SESSIONNAME=Console
SystemDrive=C:
SystemRoot=C:\WINDOWS
TEMP=C:\DOCUME~1\JERRYF~1\LOCALS~1\Temp
TEMPDIR=d:\Temp
TMP=C:\DOCUME~1\JERRYF~1\LOCALS~1\Temp
USERDOMAIN=WRKSTN0001
USERNAME=Jerry Ford
winbootdir=C:\WINDOWS
windir=C:\WINDOWS
In the next script, below, I have reformatted the SET command’s output to help
make it easier to read. I accomplished this by specifying the = character as the
DELIMS parameter and specifying the TOKENS parameter as 1-2.
164
@ECHO off
Windows Shell Script Programming for the Absolute Beginner
ECHO.
When the script is executed, it issues the SET command and then iterates its way
through the command’s output, displaying the name of a variable on one line
followed by the variable’s value on the next line and then a blank line. The results
is a much cleaner listing, as demonstrated by the partial output shown below.
Variable Name: USERNAME
The nice thing about this form of the FOR loop is that it automatically hides the
output produced by the command. This way, I can use ECHO statements to choose
what output, if any, I want to display.
collection specifies the location of the folder where the files to be processed reside.
For example, you could use the FOR command to display all Microsoft Word files
located in a folder called C:\MyDocs using the following statement:
FOR %%i IN (C:\MyDocs\*.doc) DO ECHO %%i
Notice that I used the * character to instruct the script to process all files with a
.doc file extension. The * character is an example of a wild card character. It is used
to create matches among files based on a pattern. In the example above, the pat-
tern was set up to match all files ending with the .doc file extension. I could have
just as easily looked for all files that begin with the letters Jan and that also end
with a .doc file extension by specifying Jan*.doc.
The Windows shell supports a second type of wild card character: the ? character.
Unlike the * character, the ? character limits the pattern match to a single charac-
ter. For example, Jan?.doc would limit matches to files whose file name begins with
Jan, and includes a single character between Jan and the .doc file extension, such
as Jan7.doc.
You can set up the FOR statement to process more than one file type at a time by
separating each file type with a blank space. For example, the following Windows
shell script demonstrates how to process all files that begin with either a .bat or
.cmd file extension and are located within the same folder as the script.
@ECHO off
:DisplayConsole
ECHO.
ECHO -------------------------------------------------------------------------------
ECHO.
ECHO.
ECHO.
ECHO -------------------------------------------------------------------------------
ECHO.
START %response%
CLS
GOTO :DisplayConsole
When run, this script will display a screen similar to the one shown in Figure 6.7.
At the bottom of the display is a prompt created using the SET command. This
prompt allows you to enter the name of a Windows shell script. The script then
uses the START command to open a new Windows command console and run the
specified script.
FIGURE 6.7
ION
INIT The terms directory and subdirectory are often used synonymously as terms that
DEF
refer to Windows folders. However, a subdirectory is actually a directory that is
subordinate to whatever parent directory is being referenced.
167
The /D switch specifies that subfolders (or subdirectories) are to be processed. collec-
SET /A count = 0
ECHO.
ECHO.
ECHO ------------------------------------------
ECHO.
SET /A count += 1
ECHO %%i
ECHO.
ECHO ------------------------------------------
ECHO.
ECHO.
PAUSE
Note that to display all of the subfolders, you must add an * character to the end of
the parent folder’s name. As written, the script expects the user to pass it a folder
name such as C:\Games. The script then appends \* to the end of the argument to
create C:\Games\*. When executed, this script will produce results similar to those
shown below.
Folder listing for: D:\Games
------------------------------------------
D:\Games\Dos
D:\Games\TextBased
168
D:\Games\Windows
Windows Shell Script Programming for the Absolute Beginner
------------------------------------------
You may also use the FOR command to perform a recursive examination of all the
subfolders residing within a particular parent folder. To do so, use the following
syntax of the FOR command:
FOR /R [parentfolder] %%variable IN (.) DO command
ION
INIT When used within the context of displaying folders, the term recursive means to
DEF
iteratively step your way through the Windows file system tree, displaying or pro-
cessing each successive collection of subfolders.
The /R switch instructs the FOR command to recursively examine all folders resid-
ing underneath the specified parent (or top-level) folder. Also note that you must
enclose the period character within a matching pair of parentheses exactly as shown
above. For example, the following statement demonstrates how to display every
subfolder residing under the C:\Games folder:
FOR /R C:\Games %%i IN (.) DO ECHO %%i
C:\Games\Dos\.
C:\Games\Dos\Old\.
C:\Games\Dos\Old\.
C:\Games\TextBased\.
C:\Games\TextBased\Batch\.
C:\Games\TextBased\Interactive\.
C:\Games\Windows\.
169
Reading Text Files
For example, suppose you had the following information stored in a text file called
C:\Contact.txt:
===========================================================
===========================================================
In its current size, this file is small and easy to work with. But as the file grows
over time, it may become difficult to work with. By creating a Windows shell script,
you can easily read and process some or all of the data stored in this file.
The first six lines in the file consist of headers and two blank lines. Each of the
remaining lines in the file contains tab-delimited information about different
personal contacts, including their names, e-mail addresses, and phone numbers.
The following script demonstrates how to use a FOR loop to display the first names
of all the people listed in the file:
FOR /F %%i IN (contacts.txt) DO ECHO %%i
In the absence of a TOKENS parameter, the script will default to "TOKENS=1". As a re-
sult, this statement processes the file and displays only the information stored in
170
the first token of each line (e.g., the first word in each line). As a result, the state-
Windows Shell Script Programming for the Absolute Beginner
Personal
===========================================================
name
Molly
William
X-Man
Mike
Mark
Nick
If you want to process all of the information stored in the file, you could rewrite
the statement as shown below:
FOR /F "TOKENS=*" %%i IN (contacts.txt) DO ECHO %%i
As you can see, the TOKENS option has been added to the statement and set equal to
*, which means that all tokens should be processed. When executed, this state-
ment would display the following output in the Windows command console:
===========================================================
===========================================================
If you wish, you could reformat the previous statement so that it processes only
specific tokens. For example, to limit processing to the name and phone number
of each individual listed in the file, you would specify TOKENS=1,3. In addition, you
171
can skip the processing of the file’s headers by adding the SKIP option and setting
In this example, tokens 1 and 3 map out to arguments %%i and %%j. When executed,
this statement displays the output shown below.
Name: Molly
Phone: 550-8888
Name: William
Phone: 550-9999
Name: X-Man
Phone: 050-9876
Name: Mike
Phone: 550-1234
Name: Mark
Phone: 550-7744
Name: Nick
Phone: 666-8912
P
TRA Be mindful of using the FOR command to process files that include blank spaces in
their file names. Unless you use the following syntax, you’ll end up with an error:
Using this syntax, the filenameset parameter is replaced with the TYPE "filename"
parameter. TYPE is a required keyword and filename is the name of the file. Make
sure you include the single and double quotation marks as shown above. For ex-
ample, the following statement could be used to process all the data stored in a file
whose name is My Contacts.txt.
The final form of loop supported by the FOR command is one that iterates a prede-
termined number of times. In this form of the loop, you must provide the FOR com-
mand with a number indicating a starting point, an increment number, and a
final number that once reached terminates the loop’s execution. The syntax for
this form of the FOR loop is outlined below.
FOR /L %%variable IN (begin,increment,end) DO command
For example, the following statement uses this form of the FOR loop to count to 3.
The loop begins at 1, increments by 1 upon each iteration, and stops after the
third iteration.
FOR /L %%i IN (1,1,3) DO ECHO %%i
Now look at a somewhat more useful way to use this form of the FOR loop. In this
example, I will use the FOR loop to display the contents of an output screen. As you
can see, I was able to create the screen using only four statements (excluding the
@ECHO off statement).
@ECHO off
PAUSE
Figure 6.8 shows the screen displayed when this script is executed.
Now compare the number of statements that it took to display this output to
the number of statements you’ve used with previous methods in this book, as
shown below.
@ECHO off
ECHO.
173
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
PAUSE
FIGURE 6.8
FOR loop do most of the work for you, but it also can be used to simplify your code
and make your scripts smaller and easier to manage.
P
TRA The form of the FOR loop discussed here always checks the value of its begin and
end parameters before executing. If you accidentally assign a value to the end pa-
rameter that is greater than the begin parameter, your loop will never run. Your script
will skip right past it without saying a word, resulting in unexpected results and a
problem that may be difficult to track down and fix. So keep an eye on your start,
increment, and end values when working with this form of the FOR loop.
ION
INIT Pseudo code is a rough, English-like outline of the logic used in all or part of a script.
DEF
Using pseudo code, you can outline a high-level design for particularly compli-
cated sections of your script by simply writing a rough logical outline of the steps
involved. For example, one portion of the Six-Million-Dollar Quiz involves the dis-
play of a text-based menu on the game’s welcome screen. Since you have not worked
with text-based menus before, you’ll probably find it very helpful to outline its
operation using pseudo code, as demonstrated below.
• Display a Welcome menu and set it up to display Play, Exit, Help, and About options.
• Prompt the player to enter an option.
• If the player enters an invalid option, clear the screen and redisplay the
Welcome menu.
175
• If the player presses Enter without entering an option, clear the screen and
As you will soon see, the rest of the steps outlined in the previous pseudo code
example can also be translated directly into code.
sections that follow. When you get to step 3, you can refer back to the pseudo code
example shown earlier and see how the pseudo code outline was used to guide the
development of the code in that part of the script.
COLOR 0E
CLS
TITLE = THE S I X M I L L I O N D O L L A R Q U I Z
SET /A Right = 0
SET /A Wrong = 0
ECHO.
ECHO.
177
ECHO.
ECHO.
ECHO.
ECHO.
ECHO S I X M I L L I O N D O L L A R Q U I Z
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
Another thing that makes this welcome screen different is the display of a text-
based menu at the bottom of the screen. In order to make the menu work, the
PAUSE statement that you have seen used here in the past has been replaced by a SET
statement that prompts the player to choose one of the listed menu options.
As you can see, this section of the script consists of a series of IF statements that
determine what to do based on the input typed in by the player. Each possible
course of action is implemented using the GOTO command, which switches script
execution flow to the specified label.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO designed to test your knowledge of The Six Million Dollar Man TV series.
ECHO Some questions are "fill in the blank," some are True/False, and some are
ECHO Yes/No. Your score will be presented after you have answered all the
ECHO questions.
ECHO.
ECHO.
179
ECHO -------------------------------------------------------------------------
ECHO.
ECHO.
ECHO 2. Type Exit and press Enter to stop playing the game.
ECHO.
ECHO 3. Type About and press Enter to learn more about the game and its author.
ECHO.
ECHO.
ECHO.
PAUSE
CLS
GOTO :StartGame
ECHO.
ECHO.
ECHO.
ECHO.
ECHO Written by
ECHO.
ECHO.
ECHO. ------------------------
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
PAUSE
CLS
GOTO :StartGame
ECHO.
ECHO.
ECHO.
181
ECHO.
CLS
As you can see, the answer given by the player is stored in a variable called quest1.
The code required to display and collect the rest of the quiz’s questions is the same
as that shown above. Rather than reproduce the same set of statements repeat-
edly, I’ve listed all of the quiz’s questions and their associated answers below.
• What was the Six-Million-Dollar Man’s first name? Steve
• Did he have 1 or 2 bionic arms? 1
• Did he have a bionic eye or ear? Eye
• What was his real last name? Majors
• What was the first name of the Six-Million-Dollar Man’s real wife? Farrah
• What was the last name of the actress who played the bionic woman? Wagner
• Did the bionic woman have a bionic eye or bionic ear? Ear
• T/F: The bionic woman cost more than the Six-Million-Dollar Man. F
• T/F: The Six-Million-Dollar Man was known as Heath on the “Big Valley.” T
• Yes/No: Did the Six-Million-Dollar Man ever marry the bionic woman? Yes
MKDIR C:\Scripts
The first statement creates the new report using the > redirection character. This
redirection character will either create the report if it does not already exist or
overwrite it if it already exists. The remaining three statements append the name
of the quiz and two blank lines to the report file.
IF /I %quest1% == Steve (
ECHO 1. What was the Six-Million-Dollar Man's first name? >> C:\TEMP\Quiz.txt
SET /A right += 1
) ELSE (
ECHO 1. What was the Six-Million-Dollar Man's first name? >> C:\TEMP\Quiz.txt
SET /A wrong += 1
As you might expect, the code required to grade the remaining nine questions is essen-
tially the same as that shown above, so, for the sake of space, I have decided not to list it
here. However, you will find it in the fully assembled script at the end of this chapter.
183
Recording Quiz Results
C:\TEMP\Quiz.txt
ECHO.>> C:\TEMP\Quiz.txt
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO -------------------------------------------------------------------------------
184
ECHO.
Windows Shell Script Programming for the Absolute Beginner
ECHO.
ECHO.
ECHO.
ECHO -------------------------------------------------------------------------------
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
GOTO :EOF
Finally, even though its not necessary at this point in the script, the GOTO :EOF state-
ment executes, forcing the termination of the script.
REM ***************************************************************************
REM
REM
REM Description: This Windows shell script game tests the player's knowledge of
REM
REM ***************************************************************************
COLOR 0E
CLS
REM Display the name of the game in the Windows command console's title bar
TITLE = THE S I X M I L L I O N D O L L A R Q U I Z
REM Define and initialize variables that will be used to track the total number
SET /A Right = 0
SET /A Wrong = 0
:StartGame
ECHO.
ECHO.
186
ECHO.
Windows Shell Script Programming for the Absolute Beginner
ECHO.
ECHO.
ECHO.
ECHO.
ECHO S I X M I L L I O N D O L L A R Q U I Z
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
:HELP
ECHO.
ECHO.
ECHO.
ECHO.
ECHO Some questions are "fill in the blank," some are True/False, and some are
ECHO Yes/No. Your score will be presented after you have answered all the
ECHO questions.
ECHO.
ECHO.
ECHO -------------------------------------------------------------------------
ECHO.
ECHO.
ECHO.
ECHO 2. Type Exit and press Enter to stop playing the game.
ECHO.
ECHO 3. Type About and press Enter to learn more about the game and its author.
ECHO.
ECHO.
188
ECHO.
Windows Shell Script Programming for the Absolute Beginner
PAUSE
CLS
GOTO :StartGame
:About
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO Written by
ECHO.
ECHO.
ECHO. ------------------------
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
189
ECHO.
ECHO.
ECHO.
PAUSE
CLS
GOTO :StartGame
:Play
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
CLS
ECHO.
ECHO.
ECHO.
ECHO.
190
ECHO.
Windows Shell Script Programming for the Absolute Beginner
CLS
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
CLS
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
CLS
ECHO.
191
ECHO.
ECHO.
ECHO.
SET /p quest5= 5. What was the first name of the Six-Million-Dollar Man's real wife?
CLS
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
SET /p quest6= 6. What was the last name of the actress who played the bionic woman?
CLS
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
SET /p quest7= 7. Did the bionic woman have a bionic eye or bionic ear?
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
SET /p quest8= 8. T/F: The bionic woman cost more than the Six-Million-Dollar Man.
CLS
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
SET /p quest9= 9. T/F: The Six-Million-Dollar Man was known as Heath on the "Big Valley."
CLS
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
CLS
MKDIR C:\Scripts
REM Create the Quiz.txt file if it does not exist. Overwrite it if it does exist
REM Determine whether the right or wrong answer was given and append the
IF /I %quest1% == Steve (
ECHO 1. What was the Six-Million-Dollar Man's first name? >> C:\TEMP\Quiz.txt
SET /A right += 1
) ELSE (
ECHO 1. What was the Six-Million-Dollar Man's first name? >> C:\TEMP\Quiz.txt
IF /I %quest2% == 1 (
SET /A right += 1
) ELSE (
SET /A wrong += 1
IF /I %quest3% == Eye (
SET /A right += 1
) ELSE (
IF /I %quest4% == Majors (
SET /A right += 1
) ELSE (
SET /A wrong += 1
IF /I %quest5% == Farrah (
ECHO 5. What was the first name of the Six-Million-Dollar Man's real wife? >> C:\TEMP\Quiz.txt
SET /A right += 1
) ELSE (
ECHO 5. What was the first name of the Six-Million-Dollar Man's real wife? >> C:\TEMP\Quiz.txt
IF /I %quest6% == Wagner (
ECHO 6. What was the last name of the actress who played the bionic woman? >> C:\TEMP\Quiz.txt
SET /A right += 1
) ELSE (
ECHO 6. What was the last name of the actress who played the bionic woman? >> C:\TEMP\Quiz.txt
SET /A wrong += 1
IF /I %quest7% == Ear (
ECHO 7. Did the bionic woman have a bionic eye or bionic ear? >> C:\TEMP\Quiz.txt
SET /A right += 1
) ELSE (
ECHO 7. Did the bionic woman have a bionic eye or bionic ear? >> C:\TEMP\Quiz.txt
SET /A wrong += 1
197
)
ECHO 8. True/False: The bionic woman cost more than the Six-Million-Dollar Man. >>
C:\TEMP\Quiz.txt
SET /A right += 1
) ELSE (
ECHO 8. True/False: The bionic woman cost more than the Six-Million-Dollar Man. >>
C:\TEMP\Quiz.txt
SET /A wrong += 1
IF /I %quest9% == T (
ECHO 9. True/False: The Six-Million-Dollar Man was known as Heath on the "Big Valley." >> C:\TEMP\Quiz.txt
SET /A right += 1
) ELSE (
ECHO 9. True/False: The Six-Million-Dollar Man was known as Heath on the "Big Valley." >> C:\TEMP\Quiz.txt
IF /I %quest10% == Yes (
ECHO 10. Yes/No: Did the Six-Million-Dollar Man ever marry the Bionic woman? >> C:\TEMP\Quiz.txt
SET /A right += 1
) ELSE (
ECHO 10. Yes/No: Did the Six-Million-Dollar Man ever marry the Bionic woman? >> C:\TEMP\Quiz.txt
SET /A wrong += 1
REM Append a few blanks lines and then append score card data
ECHO.>> C:\TEMP\Quiz.txt
CLS
REM Display score card data in the Windows command console and inform the player
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO -------------------------------------------------------------------------------
ECHO.
ECHO.
ECHO.
ECHO.
ECHO -------------------------------------------------------------------------------
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
GOTO :EOF
200
Summary
Windows Shell Script Programming for the Absolute Beginner
In this chapter, you learned how to use the FOR statement in numerous different
ways in order to iterate through collections of files and folders as well as to process
the results returned by commands. You then created the Six-Million-Dollar Quiz
where you learned, among other things, how to implement and control a text-
based menu system and how to create a report file.
EXERCISES
1. Modify the Six-Million-Dollar Quiz so that it displays the correct answers to any
question missed by the player.
2. Modify the Six-Million-Dollar Quiz so that the Score Card Report is not auto-
matically generated. Instead, display a prompt at the end of the game that asks
players whether they would like the report to be generated.
3. Each script statement that writes or appends data to the Quiz.txt file has the name
and location of the report file hard coded on it. Make the script easier to maintain
and modify by defining a variable that specifies the location where the file should
be stored and then replace each hard-coded reference with this variable.
4. Add logic to the end of the Six-Million-Dollar Quiz that grades the score the
player earned on the quiz. For example, assign A+ if all questions were answered
correctly, a B+ if only one question was missed, and so on.
Creating
7
C H A P T E R
Procedures and
Subroutines
T
he focus of this chapter is to teach you how to improve the overall organization
and design of your Windows shell scripts by introducing you to subroutines
and procedures. Specific emphasis will be placed on procedures as an orga-
nizational tool for enhancing script design. This chapter will also cover two other impor-
tant topics: the localization of variables and the creation of reusable modules of code.
Specifically, you will learn
• How to use the GOTO command to create subroutines
• How to use the CALL command to set up procedures
• How to create internal and external procedures
• How to localize variables using procedures
• How to set up procedures that process arguments
202
Windows Shell Script Programming for the Absolute Beginner
Project Preview:
The Rock, Paper, Scissors Game
This chapter’s main project is called the Rock, Paper, Scissors game. This game is
based on the childhood game where two people knock their own hands together
in unison three times, and then use one hand to make the shape of a rock, a piece
of paper, or a pair of scissors. The game will begin, as shown in Figure 7.1, by dis-
playing a welcome screen. This welcome screen has a dual purpose in that it also
displays the rules of the game, just in case the player is not familiar with them.
FIGURE 7.1
As Figure 7.2 shows, the player is prompted to type in one of the three game objects.
FIGURE 7.2
The game then makes its own random selection and compares its selection to that
of the player, displaying the results as shown in Figure 7.3.
203
The game will allow players to enter their selections using upper, lower, or mixed
case. However, only the words Rock, Paper, or Scissors are valid entries. If the player
makes a typo when entering their selection, the error message shown in Figure 7.4
will be displayed.
FIGURE 7.4
valid entries.
At the end of each game, players are asked whether they would like to play again.
Players may play as many games as they wish. When they finally decide to stop
playing, then the game screen shown in Figure 7.5 will appear, providing a sum-
mary of the number of games won, lost, or tied. In addition, the number of invalid
selections (or hands) is also displayed.
FIGURE 7.5
The Windows shell provides another use for GOTO command and LABEL statement:
creating subroutines. A subroutine is created whenever you use the GOTO com-
mand and the LABEL statement to switch processing control to a later section of
the script (as opposed to a loop, where processing control is passed back to an
earlier section of the script).
The Windows shell also allows you to define procedures using the CALL command
and the LABEL statement. Using procedures, you switch processing control from
one portion of the script to another section and then back again when the proce-
dure finishes executing.
Understanding Labels
Even though you have seen them used many times, I have not yet formally defined
labels. Labels are markers that you place inside your Windows shell scripts. Labels
are used to establish loops, subroutines, and procedures. The syntax for the LABEL
statement is shown below.
:LABEL
As you can see, a label consists of the colon character followed by the label’s name.
Label names are not case-sensitive, and you may use any combination of letters
and numbers as well as the underscore character when specifying labels.
Defining Subroutines
When you set up a subroutine and then execute it, your script skips the execution
of any statements that occur after the GOTO command and before the specified LABEL
statement, as depicted in Figure 7.6.
205
Subroutines are
created using the
GOTO command and
a LABEL statement.
As you can see in Figure 7.6, a GOTO command executes and calls a subroutine named
:ProcessFiles. The arrow shows how the script execution skips over all statements
between the GOTO command and the :ProcessFiles label.
Subroutines have complete access to any arguments that may have been passed to
the script. In addition, any changes made to variables within a subroutine affect
the entire script.
K
TRIC The Windows shell provides a built-in function name :EOF (end of file), which you
have seen used throughout this book. Windows shell scripts automatically termi-
nate execution at the end of the script file. Therefore, when you use the GOTO com-
mand to execute the :EOF subroutine, you are really just telling your script to act as
if it has just reached the end of the script file.
206
Look at a working example of a script that contains three subroutines, as shown below.
Windows Shell Script Programming for the Absolute Beginner
@ECHO off
COLOR 0E
CLS
ECHO.
IF /I %reply%==Delete (
GOTO :DeleteFiles
IF /I %reply%==Rename (
GOTO :RenameFiles
IF /I %reply%==Exit (
GOTO :Exit
GOTO :EOF
:DeleteFiles
207
ECHO Deleting all files stored in C:\TEMP
GOTO :EOF
:RenameFiles
GOTO :EOF
:Exit
GOTO :EOF
P
TRA Be careful when using wild card characters to identify multiple files. They make it
easy to accidentally delete files that you want to keep.
This script is designed to maintain the C:\Temp folder. It can perform three differ-
ent sets of actions, each of which is organized into its own function. The first func-
tion is called :DeleteFiles, and its job is to delete all the files stored in the folder.
The second subroutine is called :RenameFiles, and its job is to rename all files found
in the folder using a .bak file extension. The third subroutine is called :Exit. It’s job
is to terminate the script without performing any other action in the event that
the user either ran the script by accident or changed their mind about deleting or
renaming the files stored in the C:\Temp folder.
P
TRA When keying in the previous example, make sure that you include at least one blank
space at the end of the text specified as the SET command’s message prompt. Other-
wise the message prompt and the user’s input will run together.
When executed, the script displays a menu that prompts the user to specify an
action. The script then analyzes the user’s reply and executes the appropriate sub-
routine. Since each subroutine ended with a GOTO :EOF statement, each subroutine
terminates the script’s execution when it executes. Therefore the GOTO :EOF state-
ment not only performs script termination but is also used to define the end of
each subroutine.
208
Improving Script Organization
Windows Shell Script Programming for the Absolute Beginner
with Procedures
As I have already stated, the CALL command can be used along with the LABEL state-
ment to set up procedures. Unlike subroutines, which switch processing control to
another part of the script and then terminate at the end of the file, procedures
execute and then return processing control back to the statement that follows the
CALL command that executed the procedure in the first place.
The Windows shell supports two different types of procedures, as outlined below.
• Internal. A procedure that is defined within the script that when called,
executes and then returns control back to the statement that follows the
CALL command.
• External. A call to another script. The calling script then waits for the
called script to execute and terminate at which time the calling script begins
executing again.
As you can see, the CALL statements begin with the CALL command followed by a
space, then a colon, and finally the name of the procedure. The format that must
be followed when creating a procedure is outlined below.
:ProcedureName
GOTO :EOF
The beginning of the procedure is marked by a LABEL called :ProcedureName. The end
of the procedure is marked by the GOTO :EOF statement. Everything in between makes
up the procedure itself.
209
Internal procedures
are created using
the CALL command
and a LABEL
statement.
P
TRA Don’t forget to end all your procedures with the GOTO :EOF statement. Otherwise,
the Windows shell will treat any statements that follow a procedure as part of that
procedure, producing unpredictable results.
Unlike subroutines, which have complete access to all the arguments passed to the
script, procedures are expected to accept and process their own arguments. To
pass arguments to a script, you simply add the arguments, separated by spaces, to
the end of the CALL statement, as outlined below.
CALL :ProcedureName arg1 arg2 arg3 ……
Procedures can then access these procedure arguments as %1, %2, %3, and so on in
the same manner that scripts access script arguments. Since procedures have their
own unique set of arguments, they are not permitted to have direct access to script
arguments. This is true even if a procedure does not process any procedure-level
arguments of its own. However, you can always pass script-level arguments to
210
procedures if need be. For example, to call a procedure named :ProcessFiles and
Windows Shell Script Programming for the Absolute Beginner
pass it all of the script arguments, you would use the following statement:
CALL :ProcessFiles %*
OK, now look at how to use procedures as an organizational tool for script develop-
ment. In this example, the Unpredictable.bat script that was covered in Chapter 2,
“Interacting with the Windows Shell,” has been redesigned using procedures.
@ECHO off
REM ***************************************************************************
REM
REM
REM Description: This Windows shell script randomly adjusts the Windows shell
REM
REM ***************************************************************************
CLS
CALL :GetRandomVariable
CALL :FirstConfiguration
GOTO :EOF
211
)
CALL :SecondConfiguration
GOTO :EOF
If %TestVariable% GTR 0 (
CALL :ThirdConfiguration
GOTO :EOF
:GetRandomVariable
SET TestVariable=%random%
GOTO :EOF
:FirstConfiguration
CLS
COLOR 02
ECHO.
PROMPT
GOTO :EOF
:SecondConfiguration
CLS
COLOR 0E
PROMPT $d$g
GOTO :EOF
:ThirdConfiguration
CLS
COLOR E0
ECHO.
PROMPT $p
GOTO :EOF
As you can see, the script’s Procedure Section consists of a procedure call and three
conditional IF statements which also make procedure calls as appropriate. When
reorganized in this manner, the Main Processing Section assumes the job of manag-
ing the script’s overall execution flow. However, the actual work is performed by a
collection of four procedures located in the script’s Procedure Section.
Procedures streamline a script’s organization and help to create modular code. By
modular, I mean that collections of related statements are grouped together. Group-
ing statements in this manner facilitates your ability to create reusable code. In
addition, it makes script maintenance easier by isolating functionality and pro-
viding scripts with a predictable structure.
Like internal procedures, you may pass arguments to external procedures. When
the called script terminates its execution, the calling script resumes its own execu-
tion beginning with the statement following the CALL statement. Figure 7.8 depicts
the way that external procedures work.
You may make as many calls to external scripts as you wish. Each external script is
executed within the same execution environment as the calling script. Therefore,
213
An external
procedure allows a
script to execute
another script and
wait on the called
script to finish
executing before
resuming its own
execution.
changes made by the called script to script variables originally defined by the call-
ing script will be in effect once the calling script resumes its own execution.
To demonstrate the operation of external procedures, I redesigned the Unpredictable2.bat
script as shown below. This time I extracted the statements that had made up the
script’s last three internal procedures and pasted them into three external scripts,
which will be called and executed as external procedures. I named the scripts
FirstConfig.bat, SecondConfig.bat, and ThirdConfig.bat.
@ECHO off
REM ***************************************************************************
REM
214
REM Script Name: Unpredictable3.bat
Windows Shell Script Programming for the Absolute Beginner
REM
REM Description: This Windows shell script randomly adjusts the Windows shell
REM
REM ***************************************************************************
CLS
CALL :GetRandomVariable
CALL FirstConfig.bat
GOTO :EOF
CALL SecondConfig.bat
GOTO :EOF
If %TestVariable% GTR 0 (
CALL ThirdConfig.bat
:GetRandomVariable
SET TestVariable=%random%
GOTO :EOF
The following statements show the contents of the new FirstConfig.bat script.
CLS
COLOR 02
ECHO.
PROMPT
COLOR 0E
ECHO.
PROMPT $d$g
COLOR E0
ECHO.
PROMPT $p
When executed, the new Unpredictable3.bat script calls each of its external proce-
dures in sequence, producing the same results as the previous version of the script.
216
P
TRA External scripts and the calling script are running within the same instance of the
Windows Shell Script Programming for the Absolute Beginner
Windows shell. This means that the called script has access to any script variables
already defined by the calling script. This also means that any changes made to the
script variables by the called script will also be in effect when the calling script
begins executing again. So, unless you intend that the calling and called scripts
share script variables in this manner, be sure that you use different sets of variables
within each script.
One advantage of this redesigned process is that it helps to further isolate the
subroutines for debugging purposes. In other words, if I find later that I need to
modify the statements stored in just one of the procedures, I can do so without
affecting the statements stored in the main script or in the other external proce-
dures. As a result, the effects of a typo are minimized and isolated to just the one
procedure instead of an entire script.
K
TRIC As you begin writing more and more Windows shell scripts, eventually you may find
that you begin to rewrite certain common procedures over an over again. For ex-
ample, you might develop four or five scripts, all of which need to access the con-
tents of a network drive. Using the NET USE command, you can develop an internal
procedure that establishes a remote network connection to the network drive. How-
ever, rather than duplicate this procedure in each script that needs it, you can save
it as a separate script and then call that script as a procedure from any script that
needs it. This way, you won’t have to keep reinventing the wheel.
SETLOCAL
ENDLOCAL
GOTO :EOF
Using this format, any variables defined within the procedure are isolated from
the rest of the script and are discarded when the procedure terminates.
P
TRA When localizing variables within procedures, take extra care to make sure you re-
member to execute the ENDLOCAL command. Otherwise, your procedure variables
will become script variables with potentially damaging effects. One thing you should
specifically guard against is the use of GOTO commands within procedures, because
that could transfer processing control to a different part of the script without first
finishing the procedure. In this case, you can turn the GOTO command into a com-
pound command in order to retain variable localization as demonstrated below.
SETLOCAL
SET /A ret = 5
ENDLOCAL
GOTO :EOF
218
In this procedure, the value of a variable named ret is set equal to 5. However, this
Windows Shell Script Programming for the Absolute Beginner
variable and its value are not accessible to the rest of the script.
Using a programming technique called variable tunneling, you can get around this
limitation. Variable tunneling works like this: First you create a variable containing
whatever information you wish to pass back to the rest of the script, and then you
turn the ENDLOCAL command into a compound command using the following syntax:
ENDLOCAL & SET ret=%ret%
The result will be a statement that ends the scope of procedure variables while
tunneling out, or making accessible, the ret variable, as demonstrated in the fol-
lowing example:
:DemoProcedure
SETLOCAL
SET /A RET = 5
GOTO :EOF
ION A flowchart is a graphic outline that provides a high-level overview of the compo-
INIT
DEF
nents of a script and shows their relationship to one another.
219
TABLE 7.1 ROCK, PAPER, SCISSORS RULES
FIGURE 7.9
Using a flowchart to
help create a
preliminary design
for your Windows
shell script.
I N T HE R EAL W ORLD
The larger and more complex the project, the more beneficial flowcharting becomes.
Programmers use flowcharts to break down projects into discrete tasks. This makes
it easier to focus on the development of each individual component of the script by
knowing how it relates to other components. Flowcharting also helps programmers
who work on teams to break down projects into different parts, each of which may
be worked on by a different programmer.
221
Translating Flowchart Design into Script
COLOR 0E
SET /a NoWins = 0
SET /a NoLosses = 0
SET /a NoTies = 0
SET /a NoInvalid = 0
222
Creating the Main Processing Section
Windows Shell Script Programming for the Absolute Beginner
The Main Processing Section, shown below, looks a little different than the Main
Processing Section of other scripts that you have seen in this book. This Main Pro-
cessing Section is designed to control the game’s overall execution by making calls
to the appropriate procedures. In addition to procedure calls, the Main Processing
Section includes a label called :StartAgain and an IF...Else statment. By placing the
label at the beginning of the Main Processing Section, the IF...Else statement is able
to initiate a replay of the game if the player elects to play another round. Otherwise,
the :DisplayStatus procedure is called and the script terminates its execution.
CALL :DisplayMenu
:StartAgain
CALL :CollectChoice
CALL :GetComputerChoice
CALL :CompareChoices
CALL :CheckForInvalid
CALL :DisplayResults
GOTO :StartAgain
) ELSE (
CALL :DisplayStats
GOTO :EOF
GOTO :EOF
223
Developing the :DisplayMenu Procedure
CLS
ECHO W E L C O M E TO
ECHO.
ECHO R O C K, P A P E R, S C I S S O R S !
ECHO.
ECHO.
ECHO.
ECHO Rules:
ECHO.
ECHO.
ECHO.
ECHO.
PAUSE
GOTO :EOF
224
Like all procedures, this one ends with the GOTO :EOF statement, which returns the
Windows Shell Script Programming for the Absolute Beginner
processing control of the script back to the statement immediately following the
statement that called this procedure.
SET response=N
SET results=None
CLS
GOTO :EOF
SET GetRandomNumber=%random%
SET CardImage=scissors
GOTO :Continue
SET CardImage=paper
:Continue
GOTO :EOF
Note the inclusion of the :Continue label in this procedure. I added this label to
allow the procedure to skip the execution of any remaining statements as soon as
the first conditional test proves true. For example, if the randomly generated num-
ber is over 22,000, then there is no reason for the procedure to process the other
statements outside of those located in its first conditional test.
IF /I %answer% == rock (
IF %CardImage% == rock (
IF %CardImage% == scissors (
226
SET results="You Win"
Windows Shell Script Programming for the Absolute Beginner
IF %CardImage% == paper (
IF /I %answer% == scissors (
IF %CardImage% == rock (
IF %CardImage% == scissors (
IF %CardImage% == paper (
IF /I %answer% == paper (
IF %CardImage% == rock (
IF %CardImage% == scissors (
IF %CardImage% == paper (
GOTO :EOF
The value assigned to the variable called results is a string describing the results of
the game. In addition, the values assigned to the NoWins, NoLosses, and NoTies vari-
ables are incremented as appropriate.
IF %results%==None (
CLS
ECHO.
228
ECHO Use all lower case when you enter your choice.
Windows Shell Script Programming for the Absolute Beginner
PAUSE
GOTO :EOF
The game continues after the player reads the error message and presses a key.
CLS
ECHO G A M E R E S U L T S
ECHO.
ECHO -------------------------------------
ECHO.
ECHO.
ECHO.
ECHO -------------------------------------
ECHO.
229
ECHO Results: %Results%
GOTO :EOF
CLS
ECHO G A M E S T A T I S T I C S
ECHO.
ECHO -------------------------------------
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO -------------------------------------
GOTO :EOF
OK, now you are ready to complete the development of the Rock, Paper, Scissors
game. Why don’t you try to do so before examining the fully assembled script that
I have listed in the next section.
REM ***************************************************************************
REM
REM
REM
REM ***************************************************************************
REM Display the name of the game in the Windows command console's title bar
TITLE = R o c k, P a p e r, S c i s s o r s
SET /a NoWins = 0
SET /a NoLosses = 0
SET /a NoTies = 0
SET /a NoInvalid = 0
CALL :DisplayMenu
REM This label provides a callable marker for restarting the game
:StartAgain
CALL :CollectChoice
REM Call the procedure that randomly determines the computer's choice
CALL :GetComputerChoice
REM Call the procedure that determine if the player won, lost or tied
CALL :CompareChoices
CALL :CheckForInvalid
REM Call the procedure that displays the results of the game
CALL :DisplayResults
REM Analyze the player's response and either start a new game or display
232
REM game statistics (assume an N if response is anything but a Y or y)
Windows Shell Script Programming for the Absolute Beginner
GOTO :StartAgain
) ELSE (
CALL :DisplayStats
GOTO :EOF
GOTO :EOF
:DisplayMenu
CLS
ECHO W E L C O M E TO
ECHO.
ECHO R O C K, P A P E R, S C I S S O R S !
ECHO.
ECHO.
ECHO.
ECHO Rules:
ECHO.
ECHO.
233
ECHO 2. Paper covers rock and wins.
ECHO.
PAUSE
GOTO :EOF
:CollectChoice
REM Define variables needed to store and analyze the player's response
SET response=N
SET results=None
CLS
GOTO :EOF
234
REM This procedure randomly determines the computer's choice
Windows Shell Script Programming for the Absolute Beginner
:GetComputerChoice
SET GetRandomNumber=%random%
REM If the random number is greater than 22,000, the computer picked rock
SET CardImage=rock
GOTO :Continue
REM If the random number is greater than 11,000, the computer picked scissors
SET CardImage=scissors
GOTO :Continue
SET CardImage=paper
REM This label is used to skip unnecessary conditional tests in this procedure
:Continue
GOTO :EOF
:CompareChoices
IF /I %answer% == rock (
IF %CardImage% == rock (
IF %CardImage% == scissors (
IF %CardImage% == paper (
IF /I %answer% == scissors (
IF %CardImage% == rock (
IF %CardImage% == scissors (
IF %CardImage% == paper (
IF /I %answer% == paper (
IF %CardImage% == rock (
IF %CardImage% == scissors (
IF %CardImage% == paper (
GOTO :EOF
:CheckForInvalid
IF %results%==None (
CLS
ECHO.
ECHO Use all lower case when you enter your choice.
PAUSE
GOTO :EOF
:DisplayResults
CLS
ECHO G A M E R E S U L T S
ECHO.
ECHO -------------------------------------
ECHO.
ECHO.
ECHO.
ECHO -------------------------------------
ECHO.
REM Ask the player whether he would like to play another game
GOTO :EOF
:DisplayStats
CLS
ECHO G A M E S T A T I S T I C S
ECHO.
ECHO -------------------------------------
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
ECHO.
239
ECHO -------------------------------------
GOTO :EOF
Now that you have completed the Rock, Paper, Scissors game, I think you’ll agree
with me that using procedures to organize your scripts is definitely the way to go.
Not only do procedures make things more manageable by grouping together related
collections of statements, but they also facilitate the development of reusable code
by allowing the same procedure to be called repeatedly as many times as necessary.
Summary
In this chapter, you learned how to reorganize your Windows shell scripts using
subroutines and procedures. This included learning how to create both internal
and external procedures as well as how to localize variables within procedures
and how to tunnel out data from procedures. You were also introduced to flow-
charting as a tool for assisting your development of Windows script files. Finally,
you learned how to create the Rock, Paper, Scissors game and to organize the en-
tire game using procedures.
EXERCISES
1. Modify the Rock, Paper, Scissors game’s welcome screen so that it includes a
menu with access to Help, About, Exit, and Play menu selections.
2. Display an additional line of text at the bottom of the Game Results screen
that explains the results of the game. For example, if the player picked Rock
and the computer picked Scissors, the message should read something like
“Rock crushes scissors!”
3. Track and display additional statistical information at the end of the Rock, Pa-
per, Scissors game. For example, track how long the player played. (Hint: Per-
form substring operations against the output produced by the TIME, convert
everything to seconds, and then subtract the start time from the finish time.)
Also, provide the player with some percentages including the percentage of
games won, lost, and tied.
4. Create your own unique version of the Rock, Paper, Scissors game using whatever
objects you wish. In addition, expand the number of objects supported by the game.
This page intentionally left blank
Debugging and
8
C H A P T E R
Error Handling
The focus of this final chapter is to help you deal with errors that are bound to occur as
you develop your scripts. To begin, I’ll discuss the different types of errors that you will
experience, and then I will give you advice on how to deal with them. You’ll learn how
to display intermediary results during script execution and how to create an optional
debug execution mode.
In addition to all this, you’ll learn how to report on errors that your scripts are unable to
avoid. This reporting will include the creation of error reports and the generation of
custom error messages. I’ll also show you how to set up scripts that, when executed
as procedures, will return an exit code to their calling script.
Specifically, you will learn
• How to display intermediate results during script execution
• How to create scripts that include an optional script debug mode
• How to create error reports when problems occur within scripts
• How to pass exit code data back to calling scripts from scripts executed as
external procedures
242
Windows Shell Script Programming for the Absolute Beginner
FIGURE 8.1
The Tic-Tac-Toe
game’s welcome
menu presents
players with a
variety of options.
When the players are ready to begin the game, the Tic-Tac-Toe game board is dis-
played along with the rules of the game. Player X, always the first player to go, is
then prompted to make an initial move, as shown in Figure 8.2.
FIGURE 8.2
The Tic-Tac-Toe
game board and
rules are displayed
throughout
the game.
As the game progresses, the Tic-Tac-Toe game board is updated continually to re-
flect each player’s moves, as demonstrated in Figure 8.3.
243
The game validates each player’s move to ensure that it is within the range of
coordinates supported by the game (i.e., A1–A3, B1–B3, and C1–C3) and that play-
ers do not attempt to select squares that have already been selected. When players
do make errors, the screen shown in Figure 8.4 is displayed, and the player who
made the error is then given another chance to make their next move.
FIGURE 8.4
Invalid selections or
attempts to select
an already selected
square on the board
are caught by
the script.
The game tracks all game activity and automatically determines when a player
wins or when the game ends in a tie, as demonstrated in Figure 8.5.
FIGURE 8.5
The game
automatically
determines when
players win or tie.
244
Like all good computer games, the Tic-Tac-Toe game provides players with access to
Windows Shell Script Programming for the Absolute Beginner
FIGURE 8.6
In addition, the Tic-Tac-Toe game provides access to an About screen where players
can find more information about the game and its author, as shown in Figure 8.7.
FIGURE 8.7
I think you will agree that the Tic-Tac-Toe game represents a very good example of
how complicated and graphical text-based computer games can be.
Understanding Windows
Shell Script Errors
No matter how good a programmer becomes, one thing will always remain true—
errors will happen. Errors can be especially frustrating to programmers who are
just getting started. One of the goals of this chapter is to help prepare you for
dealing with errors when they occur. Another goal is to arm you with advice and
tips for avoiding errors in the first place. However, the reality is that some errors
simply cannot be avoided; often the best you can hope to do is to set up your scripts
to terminate as gracefully as possible, perhaps by logging the error or displaying a
user-friendly error message.
245
Syntax Errors
ION
INIT Syntax errors are errors that occur when programmers fail to follow the syntax rules
DEF
that govern the formatting of commands.
Syntax errors are usually caught by the Windows shell when your script first begins
to run and will prevent your script from executing. The Windows shell displays an
error message indicating the cause of the first syntax error that it finds within the
script. Using the information provided by the error message and a little detective
work, you can eliminate most syntax errors during script development and testing.
Run-Time Errors
Another category of error that you will run into is execution, or run-time, errors.
Run-time errors occur only when the statements that generate them execute. There-
fore, unless you are careful to test the execution of every statement within your
script, run-time errors can sneak through. For example, you might have a script that
contains a procedure that is not always used. If this procedure contains a statement
that would generate a run-time error, you would not know it until some time later.
ION
INIT An execution error, or run-time error, is one that happens as a result of the script
DEF
attempting to perform an illegal action. A good example is when a GOTO or CALL
command attempts to reference a label that has not been defined within the Win-
dows shell script.
The good news is that in most cases you can avoid run-time errors by carefully
designing and then testing your scripts during development. Unfortunately, you
may not be able to entirely prevent run-time errors from occurring. For example,
users can be unpredictable. You can never be completely assured that they will
supply your scripts with data that make sense, resulting in run-time errors. Other
causes of run-time errors include environment problems. For example, if your script
is designed to create a report but the user’s hard disk has become full, your script
will fail with an error.
246
Logical Errors
Windows Shell Script Programming for the Absolute Beginner
Another category of errors that every programmer runs into from time to time is
logical errors. Logical errors occur when you tell a script to do one thing when you
really meant for it to do something else. As a result, the script does exactly what
you told it to do but the output that you expected is wrong.
ION
INIT A logical error is one that occurs as a result of a mistake made by the programmer,
DEF
such as telling a script to add two numbers that should have been subtracted.
Logical errors usually make their presence known in the form of unexpected out-
put. In other words, the script seems to run without any problems, but the end
result isn’t what you intended. Since logical errors do not announce themselves in
the form of error messages, they can be the most difficult type of errors to track
down and fix. As a result, most logical errors are fixed only by reviewing all or part
of your script line-by-line to figure out where you went wrong. However, I will
show you a few tricks in this chapter that will help you track down logical errors.
Fortunately, most logical errors can be prevented by taking the time to plan the
design of your scripts properly. For example, a good design might start with a
flowchart and a pseudo code outline of the logic involved in critical procedures.
But even with the best preliminary designs, logical errors sometimes still manage
to creep into scripts. However, by developing your scripts in a modular fashion
using subroutines and procedures, and by carefully testing, you can usually catch
any logical errors during script development.
SET /A X = 5
SET /A Y = 10
IF X GTR Y
) ELSE (
PAUSE
There is an error in this script. If you were to save and run the script, the error
message you would see is shown below.
The syntax of the command is incorrect.
As you can see, the Windows shell has told you that it found an error but has not
provided you with any other useful information. If you look closely, you’ll see that
the error is a missing left parenthesis at the end of the fourth line in the script.
Now look at another example of a common Windows shell script error.
@ECHO OFF
SET WindowsFiles=%indir%
ECHO %WindowsFiles%
PAUSE
In this example, the name of the windir environment variable has been misspelled.
The Windows shell automatically assigns an empty value to any undefined vari-
able. As a result, the script variable called WindowsFiles does not have any data asso-
ciated with it. At this point, the script is still running happily along. However,
248
when the script’s ECHO statement attempts to display the contents assigned to the
Windows Shell Script Programming for the Absolute Beginner
ECHO is off.
Again, not much information was provided by this error, although it does suggest
that the error was generated by the execution of an ECHO statement. Of course, as
you can see, the real error exists in the SET statement. This error is easy enough to
track down in a small script like this one. However, as scripts grow in size and
complexity, finding these types of errors is not always easy.
The next script demonstrates another common Windows shell scripting error.
@ECHO OFF
SET /A X = 5
SET /A Y = 10
SET /A Z = 15
IF Z GTR Y (
IF Y GTR X (
IF X GTR 0 (
PAUSE
When executed, the following error message will be displayed. While cryptic, some
useful information is provided this time. Specifically, you know that somewhere
within the script the Windows shell found something other than the ) character
that it was expecting.
) was unexpected at this time.
Since the ( and ) characters are commonly used to create multi-line IF statements,
you might begin by examining the syntax of any recently added IF statement within
the script. If you do, you will find that the closing ) character associated with the
second IF statement was accidentally inverted to a ( character.
249
K
TRIC Start script development by defining the contents of the Initialization Section. Even
Now suppose that something happened one day to the company’s network. Maybe
the network went down or the computer where the shared network drive resides
might have crashed. If you tried to run this script before the network problem was
resolved, the following error could occur.
The system cannot find the drive specified.
In this example, there is nothing wrong with the script. Instead, an uncontrol-
lable environmental problem has inhibited its execution as run-time.
SET /A X = 5
SET Y=C:\Temp
SET Z = X * Y
ECHO Z = %Z%
PAUSE
Logically, however, the script falls short and generates the output shown below. To
fix this type of error, you must track down the location within your script where
the other variable should have been defined and add it.
Z =
trace the execution of each component of your scripts during testing. In addition
to tracing script execution, you’ll also want to keep track of your variables to make
sure they are being assigned data properly. Again, you can do this by using the ECHO
statement to display variable values, as demonstrated below.
ECHO Variable: TotalCount = %TotalCount%
By adding ECHO statements after any statement that sets or modifies variables, you
can track their values during the execution of your scripts. Once you have your
scripts fully tested and working as you want them to work, you can either delete
these extra ECHO statements or, better yet, comment them out using the REM state-
ment, as demonstrated below.
REM ECHO Variable: TotalCount = %TotalCount%
By commenting out these statements, you can keep them around should you need
to use them again later to debug the script again. I have an even better suggestion
that you can use to make this tracing and debugging technique even more useful.
It involves a little more work up front, but if you are working on a critical script, it
is probably worth the extra effort.
You’ll still need to embed statements throughout your scripts that display infor-
mation about which sections are currently executing and what the current values
assigned to variables are. What changes is the manner in which you enable and
disable debugging statements. Instead of writing a debugging statement as
ECHO Variable: TotalCount = %TotalCount%
Notice that a variable called trace has been substituted for the ECHO or REM com-
mands. When written in this manner, you provide the ability to toggle statements
between ECHO and REM mode by placing a statement similar to the following at the
beginning of your script:
IF /I "%1"=="Debug" (SET trace=ECHO) ELSE (SET trace=REM)
As you can see, this statement sets the value of trace equal to ECHO when the script
is passed an argument of Debug. Otherwise, it sets the value of trace to REM. The net
effect is that if you run the script by simply entering its name at the command
prompt and pressing Enter, the value of trace is set equal to REM and all of the extra
statements that you embedded in your script are turned into comments. This would
be the default execution mode for the script.
253
Using this example, all it takes to enable debugging is to use the following syntax
K
TRIC The tracing and debugging technique presented in this chapter works because the
Windows shell always substitutes variable values before executing statements.
Now look at an example of this debugging technique in action. The following script
is called TestScript.bat. As you can see, it is rather small and includes a number of
debugging statements, the first of which enables or disables tracing mode based
on whether the word Debug is passed to it as a script argument.
@ECHO off
IF ERRORLEVEL 1 (
IF ERRORLEVEL 1 (
GOTO :EOF
254
When executed in non-debug mode, this script will execute without displaying
Windows Shell Script Programming for the Absolute Beginner
any text in the Windows command console. However, when executed in debug
mode, output similar to the following will be displayed:
c:\scripts>TestScript.bat debug
c:\scripts>
K
TRIC If you find that data is passing by too quickly on the Windows command console’s
screen when you’re testing scripts in debug mode, you can always slow things down
a bit by adding a few well placed PAUSE commands to your script.
As you can see, this is a very good debugging technique, but it does take extra
effort on your part to implement it. Its usefulness will depend on a number of
factors, including the complexity and importance of the script with which you are
working. A small script consisting of a few lines probably won’t justify the extra
work, whereas a script that you are writing for your employer might very well
require the extra effort.
CLS
ECHO.
ECHO.
PAUSE
IF ERRORLEVEL 1 (
ECHO.
ECHO.
IF ERRORLEVEL 1 (
ECHO.
PAUSE
GOTO :EOF
In this example, the script was set up to report on errors while continuing to ex-
ecute. Another way that this script could have been written would have been to
stop its execution at the first occurrence of an error. Alternatively, additional logic
could have been added to retry the copy operation.
The Windows shell supports different variations of the IF ERRORLEVEL statement. To
learn more about how this statement works, refer to Chapter 5, “Applying Condi-
tional Logic.”
IF ERRORLEVEL 1 (
IF EXIST C:\TEMP\ScriptLog.log (
) ELSE (
GOTO :EOF
This script begins by attempting to copy any files found in the current working
directory to the computer’s C:\TEMP folder. It then checks to see if an error oc-
curred. If an error did occur, the IF EXIST statement checks to see if the ScriptLog.log
257
file already exists. If it does not exist, it is created and written to. Otherwise, the
FIGURE 8.8
Examining your
script’s error log file.
Using the logic in this example, you could easily adapt any of your scripts to record
similar entries to the log file, making it a shared error log. For more detailed infor-
mation on how to generate report and log files, refer to Chapter 3, “Windows Shell
Scripting Basics.”
IF ERRORLEVEL 1 (
GOTO :EOF
K
TRIC Note that in the previous example both the standard and error output produced by
the COPY command were redirected to an error log file named ScriptLog.log by
appending 2>&1 to the end of the COPY statement.
IF ERRORLEVEL 1 (
GOTO :EOF
259
P
TRA The NetSend.bat script depends on the built-in Messenger service being enabled
Figure 8.9 shows the graphical pop-up dialog that is displayed when this script
executes and experiences an error.
FIGURE 8.9
command to display
script output in a
graphical pop-up
dialog.
The /B switch is optional. When used, it passes back to the calling script a numeric
value specified by the ExitCode placeholder. To see how this works, look at the fol-
lowing pair of scripts.
260
The first script will be called as an external procedure. When executed, it attempts
Windows Shell Script Programming for the Absolute Beginner
to copy all files with a .bak file extension from the current working directory to
C:\Temp. Any output or errors are redirected to C:\Temp\ScriptLog.log. If an error oc-
curs when performing the copy operation, the script’s :EXIT procedure is executed.
This procedure issues the EXIT command and passes back an exit code of 4 to the
calling or parent script.
@ECHO off
GOTO :EOF
:EXIT
EXIT /B 4
The following statements make up the calling, or parent, script. As you can see, it
calls the external procedures (e.g., TestScript.bat), waits for it to finish executing,
and then checks the exit code returned by the external procedure to see if it is
equal to 4.
@ECHO off
CALL TestScript.bat
IF ERRORLEVEL 4 (
Windows commands are not case-sensitive, so you won’t get into trouble if you
mix up their case when you include them in your Windows shell scripts. However,
mixing case in this manner can make your scripts difficult to read. So be consis-
tent in whatever case you decide to use. However, you need to remember that while
mixing case will not cause script errors, you still need to closely follow the syntax
rules specified for each individual command. For example, keep an eye on the
order of command switches. While most Windows commands allow you to list
command switches in any order you wish, others will not. Also, make sure that
you run any command that you plan to use manually from the command prompt
first to ensure that you understand how it works before adding it to your script.
K
TRIC Whenever possible, reference your environment variables to avoid having to hard
code data into your scripts. This will make your scripts easier to support. It also
makes them more portable. For example, Microsoft has changed the location of the
Windows system root folders. On Windows NT and 2000 it’s C:\Winnt but on Win-
dows XP it is C:\Windows. If you ever need to access this folder, you can reference
the environment variable %systemroot% to find it without having to be concerned
with what operating system your script is running on.
263
Handling Files and Folders
ION
INIT An endless loop is one that runs forever, preventing your script from ever finishing
DEF
or completing its task.
For example, you could accidentally create an endless loop by setting up a FOR com-
mand that is supposed to count from 1 to 5 using an increment of 1. However, by
accidentally typing in an increment of –1, an endless loop is created because no
matter how many times the Windows shell adds –1 to the value of the loop’s iterator,
it will never equal 5. So double-check any code that creates a loop and make sure
that it will eventually end.
K
TRIC If, despite your best efforts, an endless loop does occur, you can break out of it if it’s
a script that you started manually. Press CTRL+C and respond with a Y when prompted
to terminate the script. However, if the script was started in background mode using
the Windows Task Scheduler service, you’ll need to terminate it using the Windows
Task Manager.
264
Also, remember that the FOR command’s iterator character is case-sensitive. There-
Windows Shell Script Programming for the Absolute Beginner
COLOR 0E
TITLE = T I C - T A C - T O E
CLS
266
The first statement turns off the automatic display of script statements, and the next
Windows Shell Script Programming for the Absolute Beginner
three statements set the Windows command console’s color scheme to yellow on black,
post the name of the game in the console’s title bar, and clear the console’s display.
SET Player=X
SET Winner=None
SET /A NoMoves = 0
CALL :InitializeBlanks
CALL :Welcome
GOTO :StartOver
GOTO :EOF
Next, the :InitializeBlanks procedure is called. This procedure sets variables located in
each square of the game board equal to a blank space. This way, when the game board
267
is initially displayed, it will look empty. Next, the :Welcome procedure is called. Its job is
SET A1=
SET A2=
SET A3=
SET B1=
SET B2=
SET B3=
SET C1=
SET C2=
SET C3=
GOTO :EOF
P
TRA Make sure that when you work on this procedure you remember to type a blank
space at the end of each SET statement. Without them, the game board, which is
displayed by the :DisplayBoard procedure, won’t display correctly.
268
Building the Welcome Screen
Windows Shell Script Programming for the Absolute Beginner
The game’s welcome screen, shown below, should look familiar to you by now. It uses
the FOR and ECHO commands to format and display a greeting message and to display a
menu of options. It then collects the player’s instruction using a SET statement.
:Welcome
CLS
ECHO W E L C O M E T O T I C - T A C - T O E
ECHO.
ECHO.
ECHO.
GOTO :EOF
CLS
ECHO.
269
ECHO.
ECHO.
ECHO.
ECHO.
ECHO 1 2 3
ECHO. Rules:
ECHO.
ECHO _____^|_____^|_____
ECHO ^| ^|
ECHO.
ECHO.
ECHO.
ECHO.
GOTO :EOF
The trick to making the :DisplayBoard procedure work is the embedding of vari-
ables within each square of the board. Of course, when embedded in this manner
it makes it difficult to line up the game board. Therefore, you will probably have to
test this procedure a few times and make small adjustments until you get it right.
K
TRIC Make things easy on yourself when working on this procedure by first copying the
procedure into its own script. Then hard code variables representing each location on
the board and assign these variables an X or an O. In addition, assign a hard-coded
value to the player variable. By temporarily turning the procedure into its own mini-
script, you can focus on getting it to look and work just the way you want it to (less the
temporarily hard-coded variables) before you copy it back into the Tic-Tac-Toe game.
270
K
TRIC At this point, all you should have is your template and the first two sections. Next, I
Windows Shell Script Programming for the Absolute Beginner
recommend that you create the :Play, :Help, :About, :InitializeBlanks, and :Wel-
come procedures but that you leave them empty. Once you have done this, stop and
test the script to make sure it doesn’t have any syntax errors. In addition, by testing
each of the conditions that are tested for in the Main Processing Section, you can
verify the welcome screen’s menu operation.
Providing Help
The game’s :HELP procedure, shown below, is designed to provide the players with
access to additional instruction should they need it.
:HELP
CLS
ECHO.
ECHO.
ECHO the computer controls the action. Player X always goes first. The game
ECHO tells each player when it is his turn. When prompted to take a turn players
ECHO must type the coordinates of the square into which they wish to place their
ECHO marker (i.e., the X or O character). For example, to place a marker in the
ECHO.
ECHO The game tracks the progress of each game and will automatically determine
PAUSE
GOTO :EOF
271
Taking Credit for Your Work
:About
CLS
ECHO.
ECHO Written by
ECHO.
ECHO.
ECHO ------------------------
ECHO.
PAUSE
GOTO :EOF
K
TRIC Now that you have filled in the statements that go in the :HELP and :About proce-
dures, I recommend that you stop and test your script to make sure that you have not
accidentally made any typos that result in syntax errors. If you did, it will be a lot
easier to track them down now, before you add any more complexity to the script.
break down this procedure into small pieces and cover each piece in sequence.
The :Play procedure begins, as shown below, with three IF statements that deter-
mine whether the game has been won. These three statements determine whether
Player X or Player O has won the game or if a tie has occurred. If the game has been
won or a tie has occurred, then the game is over and the :DisplayGameResults proce-
dure is called, after which the game’s Welcome menu is displayed by executing a
GOTO statement that switches processing control back to the :StartOver label.
:Play
IF "%Winner%"=="X" (
CALL :DisplayGameResults
PAUSE
GOTO :StartOver
IF "%Winner%"=="O" (
CALL :DisplayGameResults
PAUSE
GOTO :StartOver
IF "%Winner%"=="Nobody" (
CALL :DisplayGameResults
PAUSE
GOTO :StartOver
If the game has not yet been won or tied, then the :DisplayBoard procedure is called
and any already selected squares are shown as being filled in with their respective
Xs or Os. The current player (initially Player X) is then prompted to take a turn. The
data entered by the player is then validated by the :ValidateResponse procedure to
ensure that it’s a valid board game square and that the chosen square has not
already been taken.
273
CALL :DisplayBoard
CALL :ValidateResponse
Next an If...Else statement is executed. If the player’s move was valid, the value of
NoMoves is incremented by 1, and the :FillInSquare procedure is called. Otherwise,
an error message is displayed and the player will be given another chance (because
the value of NoMoves is not incremented and the game will not switch player turns).
IF %ValidMove%==True (
CALL :FillInSquare
) ELSE (
CLS
PAUSE
The next IF statement in the :Play procedure is charged with either declaring the
game a tie when all the squares on the game board have been filled and a winner
has not been declared at the beginning of the procedure or with calling the :SeeIfWon
procedure. The job of the :SeeIfWon procedure is to examine the game board and
see if either player has managed to line up three consecutive squares.
IF %NoMoves% == 9 (
SET Winner=Nobody
) ELSE (
274
CALL :SeeIfWon
Windows Shell Script Programming for the Absolute Beginner
The procedure’s final IF statement switches the value of the player variable from X
to O or from O to X at the end of each turn.
IF %ValidMove%==True (
IF "%player%"=="X" (
SET Player=O
) ELSE (
SET Player=X
Finally, the last statement in the procedure uses the GOTO command to restart the
procedure again, as shown below.
GOTO :Play
GOTO :EOF
K
TRIC Because of its complexity and because its success depends on the procedures it
calls, I recommend that after keying in the statements that make up this procedure
that you stop working on the script and that you develop the rest of the procedures
as temporary, stand-alone scripts. You can then use hard-coded variables to inde-
pendently test each procedure and make sure they work as expected before copy-
ing them all back into the Tic-Tac-Toe game. At that point, your script will be fully
assembled. Following this approach, and assuming that you properly tested the op-
eration of each remaining procedure before copying it into the Tic-Tac-Toe script,
any errors that occur are likely to be found in the :Play procedure.
SET ValidMove=True
IF /I "%response%" == "" (
SET ValidMove=False
GOTO :EOF
Next, the procedure examines the player’s move to see if it matches a valid board
entry, as shown below. If the player did not enter A1, A2, A3, B1, B2, B3, C1, C2 or C3 then
the value of ValidMove is set equal to false.
IF /I NOT %response%==A1 (
IF /I NOT %response%==A2 (
IF /I NOT %response%==A3 (
IF /I NOT %response%==B1 (
IF /I NOT %response%==B2 (
IF /I NOT %response%==B3 (
IF /I NOT %response%==C1 (
IF /I NOT %response%==C2 (
IF /I NOT %response%==C3 (
SET ValidMove=False
GOTO :EOF
)
276
The next collection of tests performed by the procedure checks to see whether the
Windows Shell Script Programming for the Absolute Beginner
square selected by the player has already been taken. The variable embedded within
an available square will either be set equal to a blank or will contain either an X or
and O if it has been taken previously.
IF /I %response%==A1 (
SET ValidMove=False
IF /I %response%==A2 (
SET ValidMove=False
IF /I %response%==A3 (
SET ValidMove=False
IF /I %response%==B1 (
SET ValidMove=False
IF /I %response%==B2 (
SET ValidMove=False
IF /I %response%==B3 (
SET ValidMove=False
)
277
)
SET ValidMove=False
IF /I %response%==C2 (
SET ValidMove=False
IF /I %response%==C3 (
SET ValidMove=False
GOTO :EOF
Goto :EOF
CLS
ECHO ^| ^|
ECHO _____^|_____^|_____
ECHO ^| ^|
ECHO _____^|_____^|_____
ECHO ^| ^|
ECHO ^| ^|
GOTO :EOF
279
Determining When a Game Is Over
IF /I "%A1%"=="%player%" (
IF /I "%A2%"=="%player%" (
IF /I "%B1%"=="%player%" (
IF /I "%B2%"=="%player%" (
IF /I "%C1%"=="%player%" (
IF /I "%C2%"=="%player%" (
IF /I "%A1%"=="%player%" (
IF /I "%B2%"=="%player%" (
IF /I "%A3%"=="%player%" (
IF /I "%B2%"=="%player%" (
)
280
)
Windows Shell Script Programming for the Absolute Beginner
IF /I "%A1%"=="%player%" (
IF /I "%B1%"=="%player%" (
IF /I "%A2%"=="%player%" (
IF /I "%B2%"=="%player%" (
IF /I "%A3%"=="%player%" (
IF /I "%B3%"=="%player%" (
GOTO :EOF
REM ***************************************************************************
REM
REM
REM ***************************************************************************
COLOR 0E
REM Display the name of the game in the Windows command console's title bar
TITLE = T I C - T A C - T O E
CLS
:StartOver
SET Player=X
SET Winner=None
SET /A NoMoves = 0
SET /A NoMoves = 0
REM Reset all the squares on the game board to show blanks
CALL :InitializeBlanks
REM Display the Welcome screen and prompt the players for instructions
282
CALL :Welcome
Windows Shell Script Programming for the Absolute Beginner
GOTO :StartOver
GOTO :EOF
:InitializeBlanks
SET A1=
SET A2=
SET A3=
SET B1=
SET B2=
SET B3=
SET C1=
SET C2=
SET C3=
GOTO :EOF
CLS
ECHO W E L C O M E T O T I C - T A C - T O E
ECHO.
ECHO.
ECHO.
GOTO :EOF
:DisplayBoard
CLS
ECHO.
284
ECHO.
Windows Shell Script Programming for the Absolute Beginner
ECHO T I C - T A C - T O E
ECHO.
ECHO.
ECHO.
ECHO 1 2 3
ECHO. Rules:
ECHO.
ECHO _____^|_____^|_____
ECHO ^| ^|
ECHO.
ECHO.
ECHO.
ECHO.
GOTO :EOF
:HELP
CLS
ECHO.
ECHO.
ECHO the computer controls the action. Player X always goes first. The game
ECHO tells each player when it is his turn. When prompted to take a turn players
ECHO must type the coordinates of the square into which they wish to place their
ECHO.
ECHO The game tracks the progress of each game and will automatically determine
PAUSE
GOTO :EOF
:About
CLS
ECHO Written by
ECHO.
ECHO.
ECHO ------------------------
ECHO.
PAUSE
GOTO :EOF
:Play
REM If player X has won then find out if a new game should be started
IF "%Winner%"=="X" (
CALL :DisplayGameResults
PAUSE
GOTO :StartOver
REM If player O has won then find out if a new game should be started
IF "%Winner%"=="O" (
CALL :DisplayGameResults
PAUSE
287
GOTO :StartOver
REM If the players tied find out if a new game should be started
IF "%Winner%"=="Nobody" (
CALL :DisplayGameResults
PAUSE
GOTO :StartOver
CALL :DisplayBoard
CALL :ValidateResponse
IF %ValidMove%==True (
REM Add 1 to the total number of valid selections made in the game
CALL :FillInSquare
) ELSE (
PAUSE
REM If a total of 9 valid selections have been made the board is full
IF %NoMoves% == 9 (
SET Winner=Nobody
) ELSE (
CALL :SeeIfWon
IF %ValidMove%==True (
IF "%player%"=="X" (
SET Player=O
) ELSE (
SET Player=X
:ValidateResponse
SET ValidMove=True
IF /I "%response%" == "" (
SET ValidMove=False
GOTO :EOF
REM Ensure that a valid square was specified (A1-A3, B1-B3 & C1 - C3)
IF /I NOT %response%==A1 (
IF /I NOT %response%==A2 (
IF /I NOT %response%==A3 (
IF /I NOT %response%==B1 (
IF /I NOT %response%==B2 (
IF /I NOT %response%==B3 (
IF /I NOT %response%==C1 (
IF /I NOT %response%==C2 (
IF /I NOT %response%==C3 (
SET ValidMove=False
GOTO :EOF
)
290
)
Windows Shell Script Programming for the Absolute Beginner
IF /I %response%==A1 (
SET ValidMove=False
IF /I %response%==A2 (
SET ValidMove=False
IF /I %response%==A3 (
SET ValidMove=False
IF /I %response%==B1 (
SET ValidMove=False
IF /I %response%==B2 (
SET ValidMove=False
IF /I %response%==B3 (
291
IF NOT "%B3%"==" " (
IF /I %response%==C1 (
SET ValidMove=False
IF /I %response%==C2 (
SET ValidMove=False
IF /I %response%==C3 (
SET ValidMove=False
GOTO :EOF
:FillInSquare
Goto :EOF
:DisplayGameResults
CLS
REM Display the final board and display a message indicating game results
ECHO ^| ^|
ECHO _____^|_____^|_____
ECHO ^| ^|
ECHO _____^|_____^|_____
ECHO ^| ^|
ECHO ^| ^|
REM Check up, down, & diagonally to see if the player has won
:SeeIfWon
IF /I "%A1%"=="%player%" (
IF /I "%A2%"=="%player%" (
IF /I "%B1%"=="%player%" (
IF /I "%B2%"=="%player%" (
IF /I "%C1%"=="%player%" (
IF /I "%C2%"=="%player%" (
IF /I "%A1%"=="%player%" (
IF /I "%B2%"=="%player%" (
IF /I "%A3%"=="%player%" (
294
IF /I "%B2%"=="%player%" (
Windows Shell Script Programming for the Absolute Beginner
IF /I "%A1%"=="%player%" (
IF /I "%B1%"=="%player%" (
IF /I "%A2%"=="%player%" (
IF /I "%B2%"=="%player%" (
IF /I "%A3%"=="%player%" (
IF /I "%B3%"=="%player%" (
GOTO :EOF
OK, now that you have the complete script, it’s time to kick its tires and see how it
handles. While you can certainly play the Tic-Tac-Toe game by yourself, it is de-
signed for two. So grab a friend and impress them with your new Windows shell
script game.
Summary
In this final chapter, I provided you with lots of different ways of dealing with
problems that are bound to arise as you begin developing your own shell scripts.
This information included a discussion of syntax, logic, and run-time errors. I then
provided you with instruction on how to trace logic flow and display intermediate
295
results within scripts. I also showed you how to write scripts that, when called as
EXERCISES
1. Modify the Tic-Tac-Toe game so that it visually identifies whose turn it is. For
example, use a yellow-on-black color scheme when it is Player X’s turn and a
green-on-black color scheme when it is Player O’s turn.
2. There is a lot of room for improvement in the Tic-Tac-Toe game’s lone error
message. Modify the game so that instead of simply reporting all player errors
as an invalid move, the game tells players exactly what they did wrong. For
example, differentiate between invalid sections and attempts to select a square
that has already been selected.
3. Modify the Tic-Tac-Toe game so that it tracks wins, losses, and ties over time,
and present this information to players at the final conclusion of the game.
This page intentionally left blank
Windows Shell
A
A P P E N D I X
Scripting
Administrative
Scripts
I
n addition to serving as a great introductory computing language, Windows
shell scripting serves a very practical purpose: assisting the automated
administration of computer and network tasks. As such, this book would be
remiss if it did not provide you with some practical examples of Windows shell scripts
designed to do something other than play games. In this appendix, you will find a collec-
tion of seven scripts that demonstrate various tasks that can be automated using Win-
dows shell scripts. Some of the scripts have more practical value than others. However,
you can use them as a foundation for developing scripts that suit your specific needs.
Specifically, you will learn
• How to programmatically connect to network disk drives
• How to automate the creation of user and administrator accounts
• How to automate the Windows disk defrag process
• How to automate the execution of your Windows shell scripts
• How to create a network chat script
• How to execute and control third-party utilities and programs from within
Windows shell scripts
298
Windows Shell Script Programming for the Absolute Beginner
ION
INIT DriveLetter is an alphabetic representation of a disk drive. Windows computers use
DEF
letters of the alphabet to represent connections to local and network drives. As such, a
maximum of 26 network drive connections can be set up or mapped on your computer.
ION
INIT The \\ServerName\ShareName parameter defined previously is an example of the
DEF
application of the Universal Naming Convention, or UNC. The UNC establishes stan-
dards for identifying local and network resources. UNC names begin with two back
slashes followed by the name of a network device, another slash, and then the name
of the shared resource.
You can also use the NET USE command to break connections to network resources.
To disconnect a connection to a shared network drive, use the following syntax:
NET USE DriveLetter: /DELETE
DriveLetter represents the drive letter currently associated with the connection
and /DELETE is a switch that tells the NET USE command to terminate the computer’s
connection.
299
The following example provides a working demonstration of how to set up and
REM ***************************************************************************
REM
REM
REM
REM ***************************************************************************
REM Abort execution if run on a computer running Windows NT, 2000, XP, or 2003.
ECHO.
ECHO.
ECHO.
ECHO.
GOTO :EOF
SET DriveLetter=X:
REM Define a variable that specifies the location of the network drive.
300
SET NetworkDrive=\\SERV0001\C
Windows Shell Script Programming for the Absolute Beginner
REM Display the name of the script in the Windows command console's title bar.
TITLE = MapNtwkDrive.bat
COLOR 0E
CALL :DisplayUserMsg
CALL :EstablishConnection
IF %ERRORLEVEL%==0 (
REM If an error did not occur, then prompt the user to verify that the
CALL :VerifyConnection
REM Call the procedure that disconnects the network drive connection
CALL :BreakConnection
GOTO :EOF
ECHO.
ECHO.
ECHO.
ECHO.
PAUSE
GOTO :EOF
:EstablishConnection
CLS
ECHO.
ECHO.
REM Use the NET USE command to connect to the specified network drive
IF ERRORLEVEL 1 (
ECHO.
ECHO.
ECHO.
302
ECHO.
Windows Shell Script Programming for the Absolute Beginner
PAUSE
GOTO :EOF
REM Prompt the user to check to make sure the drive connection was
REM established.
:VerifyConnection
ECHO.
ECHO.
ECHO Please verify that the new network drive connection has been established
ECHO.
ECHO.
ECHO Instructions:
ECHO ------------
ECHO.
ECHO Click on Start and then My Computer. You should not see a drive
ECHO.
ECHO.
PAUSE
GOTO :EOF
REM Use the NET USE command to delete the connection as specified by its
IF ERRORLEVEL 1 (
ECHO.
ECHO.
ECHO.
ECHO.
) ELSE (
ECHO.
ECHO.
ECHO.
ECHO.
GOTO :EOF
The script begins by verifying that it has been started on a computer running Win-
dows NT, XP, 2000, or 2003. It then defines a variable named DriveLetter and as-
signs it a value of X:. Next a variable named NetworkDrive is defined and assigned
the UNC address of a shared network folder. The script then posts a text message
in the Windows command console’s title bar and changes the console’s color
scheme to yellow on black.
P
TRA This example assumes that the X: drive letter is not already in use on the computer
where the script will be executed. If X: is already used, change this drive letter
assignment to a different letter.
304
Next, a series of procedure calls is executed. The :DisplayUserMsg procedure displays
Windows Shell Script Programming for the Absolute Beginner
an informational message in the Windows command console and waits for the
user to press a key. The :EstablishConnection then uses the NET USE command to cre-
ate a network connection with the network folder specified by the NetworkDrive
variable. This procedure then uses an IF ERRORLEVEL statement to determine whether
the command was successful, and displays an error message if it was not. Next, the
:VerifyConnection procedure is executed. This procedure displays a message instruct-
ing the user to verify that the network connection has indeed been established
and waits for the user to press a key, as shown in Figure A.1.
FIGURE A.1
The user is
prompted to verify
that the new
network drive
mapping has been
established
successfully.
Figure A.2 demonstrates how the network drive would appear if the script were
run on a computer running Windows XP.
FIGURE A.2
The mapped
network drive
appears as an icon
with a network
cable connection
shown beneath it.
305
Finally, the :BreakConnection procedure runs, this time using the NET USE command
Account Administration
Windows offers a number of commands that support the command line adminis-
tration of user accounts. These commands include
• NET USER. Creates new user accounts.
• NET GROUP. Adds user accounts to global groups.
• NET LOCALGROUP. Adds user accounts to local groups.
• NET ACCOUNTS. Configures user account password policies.
These commands enable you to configure both local and domain user accounts
and groups.
In the next Windows shell script example, I will demonstrate how to automate the
creation and administration of user accounts. The name of the script will be
AdminCreator.bat. It will be designed to create a new user account whose name will
be passed to it as an argument, and the script will then add that user account to
the local administrators group. The syntax required to execute this script properly
is outline below.
AdminCreator UserName
K
TRIC Windows Resource Kits provide a command line utility called ADDUSERS.EXE that you
can also use to create new accounts. This command line utility is designed to facili-
tate the creation of accounts stored as a list in a comma-delimited text input file.
REM ***************************************************************************
REM
REM
306
REM Description: This script demonstrates how to create a local user account
Windows Shell Script Programming for the Absolute Beginner
REM
REM ***************************************************************************
REM Abort execution if run on a computer running Windows NT, 2000, XP, or 2003.
ECHO.
ECHO.
ECHO.
ECHO.
GOTO :EOF
IF "%1"=="" (
ECHO.
ECHO.
ECHO.
ECHO Syntax:
ECHO.
ECHO.
ECHO.
GOTO :EOF
REM Display the name of the script in the Windows command console's title bar.
307
TITLE "AdminCreator.bat"
SET user=%1
CLS
CALL :GetConfirmation
PAUSE
IF /I "%reply%"=="Y" (
CALL :CreateAccount
CALL :AddToAdminGroup
) ELSE (
CALL :ScriptExecutionAborted
GOTO :EOF
:GetConfirmation
ECHO.
ECHO.
SET /P reply=You have instructed this script to create a new admin account for %user%. Continue?
GOTO :EOF
REM Create the new user account and check for an error.
:CreateAccount
IF ERRORLEVEL 1 (
CLS
ECHO.
ECHO.
ECHO.
ECHO.
PAUSE
GOTO :EOF
GOTO :EOF
REM Add the new account to the local Administrators group & check for an error.
:AddToAdminGroup
ECHO.
ECHO.
ECHO.
ECHO.
PAUSE
GOTO :EOF
GOTO :EOF
REM Display the following message if the user chose to abort script execution.
:ScriptExecutionAborted
ECHO.
ECHO.
ECHO Script execution aborted. New account for %user% not created.
ECHO.
ECHO.
GOTO :EOF
sets a variable named user equal to the argument passed to the script. The console’s
screen is then cleared and a series of procedures are executed before the script
terminates its own execution.
The first procedure called is :GetConfirmation. It uses the SET command to require that
the user respond with a y or Y to confirm that the script should continue executing.
Once confirmation is received, the :CreateAccount and :AddToAdminGroup procedures are
executed. If confirmation is not received, the :ScriptExecutionAborted runs instead.
The :CreateAccount procedure uses the NET USER command to create the new user
account as shown below.
NET USER %user% * /ADD
Another IF ERRORLEVEL statement is then executed to verify that this command pro-
cessed successfully. If it did not, an error message is displayed. When executed, the
:ScriptExecutionAborted procedure displays a message indicating that the script’s
execution was aborted and that the new account was not established.
The following output shows the results the script would display if it were executed
and passed an account name of Alex0001.
C:\Scripts>admincreator Alex0001
Options: [Y/N]
You have instructed this script to create a new admin account for
Alex0001. Continue?
Options: [Y/N]
You have instructed this script to create a new admin account for
Alex0001. Continue? N
311
Press any key to continue . . .
C:\Scripts>
Options: [Y/N]
You have instructed this script to create a new admin account for
Alex0001. Continue? Y
C:\Scripts>
Figure A.3 shows that the new account was created and that it has been added to
the local administrators group.
FIGURE A.3
In the next example, I will demonstrate how to execute the DEFRAG.EXE command
line utility to run a process that defragments the computer’s local hard disk drive.
This script will also generate a summary text report of its activities.
ION
INIT Over time, the organization of files stored on hard disk drives becomes fragmented.
DEF
This results in slow performance and extra wear and tear on the drive. When a drive
is defragmented, its files are reorganized and stored more efficiently.
@ECHO off
REM ***************************************************************************
REM
REM
REM Description: This scripts demonstrates how to run the defrag utility from
REM
REM ***************************************************************************
ECHO.
ECHO.
ECHO.
ECHO.
GOTO :EOF
313
)
CALL :DeleteExistingRpt
CALL :CreateNewDefragRpt
CALL :PerformDefrag
GOTO :EOF
:DeleteExistingRpt
GOTO :EOF
:CreateNewDefragRpt
GOTO :EOF
:PerformDefrag
IF ERRORLEVEL 1 (
) ELSE (
ECHO %date% %time% DEFRAG.EXE has completed its execution. >> %DefragRpt%
GOTO :EOF
FIGURE A.4
Examining the
report created by
the defrager script.
The AT Command
The Windows AT command allows you to set up the scheduled execution of your
Windows shell scripts. Using the AT command without any additional arguments,
you can display a listing of currently scheduled tasks as demonstrated below.
C:\>AT
-----------------------------------------------------------------------------
called Defrager.bat and is set up to run every Saturday at 5 A.M. The second script is
named DiskClean.bat and is set up to run at 11 A.M. on the next day.
HINT Only administrators can configure scheduled tasks on Windows NT, XP, 2000, and 2003.
The following command demonstrates how to use the AT command to set up the
scheduled execution of a new task for a script called TestScript.bat.
AT 22:00 /EVERY:M,T,W,Th,F,S,Su CMD /C TestScript.bat
In this example, the Windows shell script that will run as a scheduled task will be
executed every day of the week at 10 P.M. You can also use the AT command to delete
scheduled tasks by passing it the ID assigned to the task, as demonstrated below.
AT 1 /DELETE
Here I told the AT command to remove the DiskClean.bat script from the execution
schedule.
K
TRIC If you want to delete all of the currently scheduled tasks, you can save time by ex-
ecuting the AT command as follows:
AT /DELETE
The AT command can also be used to set up the execution of scripts on other net-
work computers. To accomplish this, you must use the UNC format of the target
computer’s computer name, as demonstrated below.
AT \\ServerName 22:00 /EVERY:M,T,W,Th,F,S,Su CMD /C Defrager.bat
There are more uses of the AT command than I have room to cover in this appendix.
To learn more about this command, type AT HELP in the Windows command prompt
or search for information about the command in the Windows help system.
P
TRA When run by the Windows Scheduler Service, your scripts will not have access to
the same set of resources that are available when you execute them manually. For
example, any mapped drives you may have set up are not available to the script. In
these situations, you must equip your scripts with the ability to set up connections
to whatever resources they may require.
317
The following script demonstrates how you can use the AT command within Win-
REM ***************************************************************************
REM
REM
REM Description: This script demonstrates how to schedule scripts using the
REM
REM ***************************************************************************
ECHO.
ECHO.
ECHO.
ECHO.
GOTO :EOF
REM Define a variable that specifies the location of this script log file.
318
SET ReportFile=C:\Scripts\ATReport.txt
Windows Shell Script Programming for the Absolute Beginner
CALL :SetUpSchedLog
CALL :SetUpSchedule
GOTO :EOF
REM This procedure writes a date and time entry to a report file.
:SetUpSchedLog
GOTO :EOF
REM This procedure sets up the scheduled execution of other Windows shell
:SetUpSchedule
GOTO :EOF
319
The script begins by ensuring that is has not been started on an unsupported Win-
Each of these scripts is set up to run at different times and different days of the
week. The procedure also redirects any output produced by the execution of each
of these AT commands to the script’s log file.
Figure A.5 shows the scheduled tasks as they will appear when viewed from the
Windows Scheduled Tasks folder.
FIGURE A.5
Examining the
scheduled tasks
configured by
the Windows
shell script.
Figure A.6 shows how the script’s log file will look when the script runs successfully.
P
TRA Scripts set up by the AT command to run under the control of the Windows scheduler
service but are not associated with specific user accounts may fail if the script attempts
to access secured resources. If this is the case, use the Windows Task Scheduler Wiz-
ard to configure the automated execution of your scripts. The wizard provides the ability
to run scripts using the security access provided by specified user accounts.
320
Windows Shell Script Programming for the Absolute Beginner
FIGURE A.6
HINT On Windows NT, XP, 2000, and 2003, only administrators are permitted to create and
manage scheduled tasks.
The Windows Scheduled Task Wizard walks you through the steps required to set
up an automated execution schedule for your scripts using any of the following
schedules:
• Daily
• Weekly
• Monthly
• One time only
• At startup
• At login
By default, scheduled tasks run by using a special built-in Windows account called
LocalSystem. Unfortunately, this account lacks sufficient security permissions to run
many tasks. One advantage the Windows Scheduled Task Wizard has over the AT
command is the ability to easily associate user accounts and their associated pass-
words with specific tasks. This allows tasks that require specific levels of access to
execute using the security access of the specified user account.
P
TRA If you elect to associate a user account and its password with a scheduled task, the
started task will stop executing if the user account’s password expires. In addition,
the task will stop running if the user account’s password is changed and you forget to
return and update the password in the scheduled task. One way around this problem
is to create a new user account whose sole purpose is to run scheduled tasks. You
can then set up the account so that its password will not expire and will never change.
321
Starting the Task Scheduler Service
FIGURE A.7
Specifying the
name and location
of your Windows
shell script.
4. Enter a task name and then select an entry from the list of available schedul-
ing options, as shown in Figure A.8.
322
Windows Shell Script Programming for the Absolute Beginner
FIGURE A.8
Selecting the
execution frequency
for your Windows
shell script.
5. If you select the Daily schedule, the wizard will display the following list of
options, allowing you to further refine the task execution schedule.
• Start time. Specifies the time that the task is to begin running.
• Perform this task. Configures the task to run daily, on weekdays, or every
__ days.
• Start date. Specifies the date on which the task should first be run.
Fill in the required information, click on Next, and then skip to step 11.
6. If you select the Weekly schedule, the wizard will display the following list of
options, allowing you to further refine the task execution schedule.
• Start time. Specifies the time that the task is to begin running.
• Every __ weeks. Configures the task to execute on a set period of weeks.
• Select the day(s) of the week below. Specifies the one or more days of the
week on which the task should be executed.
Fill in the required information, click on Next, and then skip to step 11.
7. If you select the Monthly schedule, the wizard will display the following list
of options, as shown in Figure A.9, allowing you to further refine the task
execution schedule.
• Start time. Specifies the time that the task is to begin running.
• Day. Specifies the day of the month that the task is to run.
• The _ _. Specifies the day of the month on which to run the task.
• Of the month(s). Specifies the month(s) on which to run the task.
Fill in the required information, click on Next, and then skip to step 11.
8. If you select the One time only schedule, the wizard will display the following
list of options, allowing you to further refine the task execution schedule.
• Start time. Specifies the time that the task is to begin running.
• Start date. Specifies the date on which the task is to start running.
Fill in the required information, click on Next, and then skip to step 11.
323
Providing detailed
information
regarding the
script’s execution
schedule.
9. If you select the When my computer starts schedule, the wizard will display the
following list of options, as shown in Figure A.10, allowing you to further re-
fine the task execution schedule.
• Enter the user name. Specifies the name of a user account to associate
with the task.
• Enter the password. Specifies the account’s associated password.
• Confirm password. A confirmation of the specified account’s password.
Fill in the required information, click on Next, and then skip to step 12.
FIGURE A.10
Associating a
user account and
its password with
your Windows
shell script.
10. If you select the When I log on schedule, the wizard will display the following
list of options, allowing you to further refine the task execution schedule.
• Enter the user name. Specifies the name of a user account to associate
with the task.
• Enter the password. Specifies the account’s associated password.
• Confirm password. A confirmation of the specified account’s password.
Fill in the required information, click on Next, and then proceed to step 12.
324
11. The wizard then displays the following list of options:
Windows Shell Script Programming for the Absolute Beginner
• Enter the user name. Specifies the name of a user account to associate
with the task.
• Enter the password. Specifies the account’s associated password.
• Confirm password. A confirmation of the specified account’s password.
12. Click on Finish.
Once finished, the wizard adds an entry for the new task in the Scheduled Tasks
folder, as demonstrated in Figure A.11.
FIGURE A.11
P
TRA In order for this script to work, the computer that runs it must also be running the
Windows Messenger service. Otherwise the NET SEND won’t be able to send and
receive any messages.
@ECHO off
REM ***************************************************************************
325
REM
REM
REM
REM ***************************************************************************
REM Display the name of the script in the Windows command console's title bar.
COLOR 0E
REM Call the procedure that displays the script's welcome screen.
CALL :WelcomeScreen
REM This label provides a callable marker for restarting the script.
:TryAgain
REM Call the procedure that prompts the user to enter the name of the
CALL :CollectUserName
REM If the user hits Enter without specifying a computer name, start over.
326
IF /I "%answer%" == "" CLS & GOTO :TryAgain
Windows Shell Script Programming for the Absolute Beginner
CALL :StartChatting
GOTO :EOF
:WelcomeScreen
CLS
ECHO.
ECHO N e t S e n d I n s t a n t N e t w o r k M e s s a g e
ECHO.
ECHO.
ECHO Operation:
ECHO.
ECHO 1. When prompted, enter the network username of the person with whom
ECHO.
ECHO 2. Messages from that person will appear in graphical popup dialogs
ECHO.
ECHO 3. To send messages, type your text messages when prompted and press
ECHO the Enter key. Type a new network username when prompted and press
ECHO.
ECHO 5. When done chatting, type Quit and press the Enter key.
PAUSE
GOTO :EOF
:CollectUserName
CLS
GOTO :EOF
REM This procedure collects the message to be sent and sends it.
:StartChatting
CLS
ECHO.
328
ECHO.
Windows Shell Script Programming for the Absolute Beginner
ECHO Type a message and press the Enter key to send it or type Quit to
SET /p MsgText=Message:
REM If the user hit Enter without typing any text, prompt for input again
REM If the user entered Switch, then start over allowing the user to
GOTO :StartChatting
GOTO :EOF
This script begins by posting a message to the Windows command console’s title
bar. It then changes the console’s color scheme to yellow on black. Next, the
:WelcomeScreen procedure is called. This procedure displays the welcome screen shown
Figure A.12 and waits for the user to press a key before continuing.
Next the script calls the :CollectUserName procedure. This procedure uses a SET state-
ment to prompt the user to enter the name of a networked computer to which
messages will be sent (to mimic a chat session). Two IF statements then process the
user’s response, which is assigned to a variable named answer. If the user didn’t
type an entry, then a GOTO statement is used to transfer processing control to the
329
:TryAgain label, which is located at the beginning of the script. If the user typed
Quit, the script clears the display screen and terminates its own execution.
Next, the :StartChatting procedure is called. This procedure uses a SET statement to
collect input from the user and stores it in a variable called MsgText, as demon-
strated in Figure A.13.
FIGURE A.13
FIGURE A.14
Of course, for the NetSend.bat script to work effectively, copies of it must be distrib-
uted to both individuals who wish to chat with one another over the network.
The MESSAGEBOX.EXE utility’s syntax is even easier to access. Simply locate and double-
click MESSAGEBOX.EXE, and you’ll see the pop-up dialog shown in Figure A.15.
FIGURE A.15
Viewing the
MESSAGEBOX.EXE
command line
utility’s syntax.
As an example of how to work with these types of external command line utilities,
look at the following Windows shell script. It uses the MSGBOX command line utility
to generate a graphical pop-up dialog that displays a message with YES/NO buttons
asking the players if they would like to play another game.
@ECHO off
REM ***************************************************************************
REM
REM
REM
332
REM ***************************************************************************
Windows Shell Script Programming for the Absolute Beginner
ECHO.
ECHO.
ECHO.
ECHO.
GOTO :EOF
REM Define a variable that specifies the location of the MSGBOX.EXE program.
SET msgbox=C:\Scripts\MSGBOX.EXE
CALL :DisplayResults
:DisplayResults
GOTO :EOF
:Exit
%msgbox% "Thanks for playing! \n\nPlease come back soon!" "MSGBOX.EXE Demo"
GOTO :EOF
REM This procedures shows how the script waits on the user to
:PlayAgain
ECHO.
ECHO.
ECHO This is where you would execute the GOTO command to restart the game.
ECHO.
ECHO.
GOTO :EOF
The script begins by ensuring that it has not been inadvertently started on an
unsupported Windows operating system. Next it defines a variable named msgbox
that stores the location of the MSGBOX.EXE command line utility. The script then
calls the :DisplayResults procedure. This procedure uses the MSGBOX.EXE command
line utility to display the graphical pop-up dialog shown in Figure A.16.
334
Windows Shell Script Programming for the Absolute Beginner
FIGURE A.16
Note that the MSGBOX.EXE utility translates the occurrence of \n characters into line
feed and character return operations. This gives you some control over the man-
ner in which text is displayed within the pop-up dialog.
Next, a pair of IF ERRORLEVEL statements interrogate the exit code returned by the
MSGBOX.EXE utility to determine which button the player clicked. An exit code of 7
indicates that the player clicked on the NO button, and an exit code of 6 indicates
that the player clicked on the YES button. If the NO button was clicked, the :Exit
procedure is called. This procedure uses the MSGBOX.EXE utility to display a message
in another pop-up dialog as shown in Figure A.17. If the player clicked on the YES
button, the :PlayAgain procedures is called instead.
FIGURE A.17
Displaying text
messages using a
pop-up dialog.
The –min parameter enables WinZip to run minimized so that you won’t see its GUI
when your scripts run it. You must select from one of the following switches to
define the action parameter:
• -a. Create a new Zip file.
• -f. Refresh an archive.
• -u. Update an existing archive.
• -m. Move an archive.
You can include any of the following parameters in place of the options placeholder:
• -r. Adds files and folders to the Zip file.
• -p. Includes information about folder membership for each file.
• -hs. Includes any hidden and system files.
• -s. Specifies an optional password, which results in a Zip file that is password pro-
tected and encrypted. The password is specified using the format of –sPassword.
You may also optionally specify any one of the following switches in place of the
options placeholder:
The following Windows shell script demonstrates how to leverage WinZip’s built-in
command line support to automate the creation of a new Zip file. In this example,
336
the script will create a Zip file that that stores all of the Windows shell scripts found
Windows Shell Script Programming for the Absolute Beginner
REM ***************************************************************************
REM
REM
REM
REM ***************************************************************************
SET ScriptFileLoc=C:\Scripts\*.bat
SET ZipFileName=C:\Scripts\Script.ZIP
REM Call the procedure that temporarily adds the WinZip folder to the
CALL :UpdatePath
REM execution.
337
CALL :DisplayWarning
CALL :CreateArchive
GOTO :EOF
REM This procedures adds the WinZip folder to the end of the search path.
:UpdatePath
SET path=%path%;%InstallLocation%
GOTO :EOF
REM This procedure displays a message that gives the user a chance to halt
:DisplayWarning
ECHO.
ECHO.
ECHO This script creates a new Zip file containing copies of all the
ECHO.
PAUSE
GOTO :EOF
:CreateArchive
CLS
REM Check for any errors and display the WINZIP32 command exit code if
REM appropriate.
IF ERRORLEVEL 1 (
CLS
ECHO.
ECHO.
ECHO An exit code of %ERRORLEVEL% was reported. As a result, the Zip file
ECHO.
ECHO.
) ELSE (
ECHO.
ECHO.
ECHO A Zip file containing all the scripts located in %ZipFileName% has been
ECHO.
ECHO.
PAUSE
GOTO :EOF
The script begins by setting up three variables. The first variable is called
InstallLocation. It is assigned a string representing the location of the folder where
WinZip has been installed on the computer. The second variable is named
ScriptFileLoc. It is assigned a string representing the folder where the scripts to be
added to the Zip file are located. The third variable is named ZipFileName. It is as-
signed a string representing the complete file and path name of the Zip file that
the script is to create.
339
The script then makes three procedure calls before terminating its own execution.
FIGURE A.18
Examining
the contents of
the Zip file created
by the Windows
shell script.
This page intentionally left blank
What’s on
B
A P P E N D I X
the CD-ROM?
T
o become an expert Windows shell script programmer, you must spend plenty
of time writing new scripts. When first starting out, it helps a lot to have a
collection of sample scripts from which to begin working. If you created and
tested the sample scripts in this book as you read along, you should now have that
foundation. However, just in case there were a couple of scripts that you did not get
the chance to complete, I have provided copies of each script on the book’s CD-ROM.
This appendix provides a brief reference to each of the scripts that you will find.
In addition to the book’s scripts, you will find shareware copies of two excellent text
editors. I will provide you with a high-level overview of the capabilities and benefits
of each editor.
342
Windows Shell Script Programming for the Absolute Beginner
multiple files at the same time. This is an especially handy feature when you find
yourself cutting and pasting lines of code from one script to another.
First Script
Second Script
Third Script
FIGURE B.1
EditPad Lite is distributed as freeware, which means that it is free for non-com-
mercial use. Its major features include
• Advanced search and replace over all open files
• Unlimited redo and undo
• Line and column numbering
• Indent and outdent options
• Optional word wrapping
• The ability to configure dozens of preferences that affect the editor’s operation
• Open any of the last 16 files using the Reopen menu
• Perform lowercase, uppercase, and invert case operations
• A print preview capability
345
HINT To learn more about the JGsoft EditPad Lite text editor, visit www.editpadlite.com/
FIGURE B.2
One of EditPad Pro’s best features is its ability to define a syntax color-coding scheme
for specific types of files like Windows shell script files. Once configured, the syn-
tax color-coding feature makes Windows shell scripts easier to work with by high-
lighting keywords in scripts using different colors. For example, all comments may
be displayed as red text, making them easier to find and modify. EditPad Pro comes
with a number of predefined syntax color-coding schemes that support many dif-
ferent file types. While it does not provide a default color-coding scheme for Win-
dows shell scripts, you can visit JGsoft’s Web site at www.editpadpro.com/cgi-bin/
cscslist.pl (as shown in Figure B.3) and download various predefined color schemes
for a host of different files types, including Windows shell scripts.
346
Windows Shell Script Programming for the Absolute Beginner
FIGURE B.3
By applying the
appropriate syntax
color-coding
scheme you can
turn EditPad Pro into
a Windows shell
script editor.
EditPad Pro assists you in downloading and installing syntax color-coding schemes
on its Preferences dialog, as shown in Figure B.4. Here a scheme named MS-BATCH
Files (a term that is synonymous with Windows shell scripts) has been downloaded
and then selected from the Syntax Coloring drop-down list. The syntax color scheme
is then associated with all files that have a .bat or .cmd file extension.
FIGURE B.4
Configuring EditPad
Pro to support
Windows shell
scripts.
Once one of the many available Windows shell script compatible color-coding schemes
is downloaded and installed, EditPad Pro can be used as a fully featured Windows
shell script editor, complete with syntax color coding (as shown in Figure B.5).
347
A syntax color-
coding scheme uses
font color, bold text,
and italics to help
make scripts easier
to read and
work with.
Other major features provided by EditPad Pro not found in EditPad Lite include
• Customizable syntax color-coding schemes
• The ability to perform file comparisons
• Spell checking
• The ability to organize and manage multiple scripts as a project
• The ability to bookmark specific lines within a file for later reference
• Support for up to 16 clipboards, allowing the simultaneous storage and
retrieval of multiple strings
For more information on the features provided by EditPad Lite and EditPad Pro,
check out JGsoft’s Web site.
This page intentionally left blank
What Next?
C
A P P E N D I X
I
nstead of seeing this book as the end of your Windows shell scripting
education, you should think of it as the beginning. To become an accomplished
Windows shell script programmer, you will need to spend time developing and
honing your programming skills by writing and testing new scripts. You also need to
continue to read and learn more about Windows shell scripting. To help get you started,
I have put together a list of books and Web sites where you can go to learn more.
350
Windows Shell Script Programming for the Absolute Beginner
Recommended Reading
Following is a collection of books that will help you further develop your Windows
shell script programming skills.
www.labmice.net/scripting
The Scripting and Batch Programming Resources Web site (Figure C.1), provides
access to information on Windows shell scripting as well as other programming
languages. Here you will find a Windows command reference, a reference for Win-
dows Resource Kit commands and links to articles that provide all kinds of infor-
mation related to Windows shell scripting.
FIGURE C.1
Scripting resources
at www.labmice
.net/scripting/
default.htm.
352
www.robvanderwoude.com
Windows Shell Script Programming for the Absolute Beginner
Another excellent resource is Rob van der Woude’s Scripting Pages Web site (Fig-
ure C.2). Here you will find plenty of Windows shell scripting examples. However,
the site states that its main objective is to help teach you how to create scripts. So
you can expect to find plenty of information on how scripting works. In addition,
you will find information about a number of other scripting languages.
FIGURE C.2
www.onesmartclick.com/programming/batch-files.html
Another excellent site is www.OneSmartClick.com (Figure C.3). This site is loaded
with links to articles where you will find all kinds of information related to Win-
dows shell scripting.
www.windowsshellscripting.com
This final recommended site (Figure C.4) is good for finding more information
about Windows shell scripting. You will find tutorials covering Windows shell script-
ing as well as sample scripts that you can download. In addition, this site features
an online discussion forum where you can post questions and receive answers from
other Windows shell script programmers.
353
OneSmartClick
.com is loaded with
information links.
FIGURE C.4
www.
windowsshellscripting
.com offers
downloads and a
discussion forum.
This page intentionally left blank
Glossary
@. A Windows shell script command that suppresses the display of any statement
from the Windows command console.
@ECHO off.
A Windows shell script statement that suppresses the display of all
statements within a script.
.bat. The file extension assigned to batch files, also known as Windows shell
script files.
.cmd. The file extension assigned to command files, also known as Windows
shell script files.
:EOF.
A built-in Windows shell script function that simulates the end-of-file
marker, providing the ability to terminate procedures and scripts.
Application Event Log. A log file maintained by Windows NT, XP, 2000, and 2003
operating systems where application error messages are written.
Argument. An individual piece of data passed to a command, procedure, or
script at execution time.
Arithmetic Operators. Characters that you use to specify the type of mathematical
operation to perform within a script (+, -, *, /, and %).
Assignment Operators. Characters that you use when assigning values to
numeric variables using expressions (+=, -=, *=, /=, and %=).
ASSOC.A Windows command that displays or modifies file name extension
associations.
AT.A Windows command that provides the ability to view, create, and modify
scheduled tasks.
Batch Files. Files with a .bat file extension that contain Windows shell scripts.
CALL.A Windows shell command used to execute internal or external procedures
in which the calling script pauses and waits for the called script to finish execut-
ing before resuming its own execution.
CD (CHDIR). A Windows command used to change the current directory.
356
CHOICE.EXE.A Windows Resource Kit command that provides the ability to inter-
Glossary
Glossary
errors within scripts and programs.
Defrag. A Windows command-line utility program that defragments files stored
on hard drives to reorganize disk space and improve disk performance by creat-
ing larger contiguous sections of free space.
Defragmenter. A graphical Windows utility that defragments files stored on
hard drives to reorganize disk space and improve disk performance by creating
larger contiguous sections of free space.
DEL. A Windows command that removes or deletes one or more files.
Delimiter. A marker (e.g., a space, comma, tab character, etc.) that identifies the
boundaries between individual pieces of data passed to commands, procedures,
or scripts.
DIR.A Windows command that displays the files and folders located in the
specified folder or directory.
Directory. A term that is synonymous with the terms folder and subfolder.
Dynamic Environment Variables. Environment variables generated by the
operating system that change over time.
ECHO.
A Windows shell command that displays text and blank lines within the
Windows command console.
Endless Loop. A loop that never finishes processing and prevents a script from
completing its task.
ENDLOCAL.A Windows shell command that terminates variable localization by
restoring variables to their values as they existed before the preceding SETLOCAL
command was executed. (See SETLOCAL.)
Environment Variable. A variable defined and managed by the operating system.
ERASE. A Windows command that removes or deletes one or more specified files.
Error. A problem that occurs during the execution of a script.
ERRORLEVEL.
A dynamically generated variable that contains a numeric value repre-
senting the exit code created by the previously executed command.
Execution Environment. The environment in which a script runs. For Windows
shell scripts, this is the Windows shell.
358
EXIT.
A Windows command that terminates script execution and closes the
Glossary
Glossary
whether a file or folder exists.
IF NOT.
A form of the IF statement that provides the ability to perform a
conditional test and take an action based on a negative result.
Integrated Development Environment. An application that is used to facilitate
the development and debugging of other scripts or programs.
Internal Command. A command built into the Windows shell.
(See External Command.)
Internal Procedure. A procedure defined within the script that, when called,
executes and then returns control back to the statement that follows the
statement that called it. (See External Procedure.)
Iterate. The act of executing one or more commands repeatedly.
JScript. A Microsoft scripting language based on Netscape’s JavaScript
programming language.
Label. A marker placed inside Windows shell scripts to set up loops, subroutines,
and procedures.
Local Variables. Variables created within a procedure that cannot be accessed
outside of the procedure.
LOGEVENT.EXE.
A Windows Resource Kit command line utility that can be used to
write messages to the Windows application event log.
Logical Error. An error created when the programmer tells the script to do
something other than what it was actually intended to do, such as adding two
numbers that really should have been subtracted.
Loop. A collection of statements that are executed repeatedly.
MD (MKDIR). A Windows command that creates a new subdirectory or subfolder.
Modifiers. Parameters that can be used to change the behavior of a command’s
switches.
MOVE.A Windows command that moves one or more files from one location
to another.
Multi-line IF Statement. A form of the IF statement that allows programmers to
embed more than one statement inside IF statements.
Mutually Exclusive. A term that refers to situations in which only one of a col-
lection of options can be selected.
360
Nested IF Statement. One or more IF statements within another IF statement.
Glossary
Glossary
This output is then processed by the second command as input.
Pixel. The smallest area on the display screen that a computer can display or print.
POPD.
Changes the current folder to the folder stored by a corresponding PUSHD
command. (See PUSHD.)
Procedure. A collection of statements that can be executed as a unit. Procedures
are used to switch processing control from one portion of a script to another
section and then back again when the procedure finishes executing.
Procedure Variable. A variable that has been localized within a procedure, prohib-
iting other parts of the script from accessing the variable. (See Script Variable.)
PROMPT.
A Windows command that is used to modify the format of the Windows
command prompt.
Pseudo Code. A rough, English-like outline of the logic used in all or part of a script.
PUSHD.Changes the current working directory to the specified folder and stores
the previous folder for later reference by the POPD command. (See POPD.)
Python. A scripting language with a UNIX heritage that is named after the come-
dic troupe Monty Python.
random.
An environment variable that returns a randomly generated number
between 1 and 32,767.
RD (RMDIR). A Windows command that removes or deletes a specified folder.
Recursive. The process a script goes through when it reinitiates its own execu-
tion or the execution of a specific collection of statements.
Redirection. The altering of a command’s input or output from its default source.
REG.A Windows Resource Kit command line utility that provides the ability to
access and change information stored in the Windows registry.
Registry. A specialized database used by Windows computers to store information
about users, hardware, software, and operating system configuration settings.
REM. A Windows shell command that provides the ability to add comments to a script.
originally for execution on mainframe computers and later ported over to Windows.
Run-Time Error. A type of error that occurs when a script attempts to perform
an illegal action, such as referencing a non-existing disk drive. (Also known as an
Execution Error.)
Scheduled Task Folder. A folder in which Windows operating systems store and
manage scheduled tasks.
Scheduled Task Wizard. A graphical interface that assists in the creation of
scheduled tasks.
Script. An executable text file made up of one of more scripting language statements.
Script Editor. A specialized text editor that facilitates the development of scripts
by providing features such as statement color coding and line numbering.
Script Variable. A variable created during the execution of a Windows shell script
that can be accessed from any location within the script. (See Procedure Variable.)
SET. A Windows shell command that provides the ability to collect and assign val-
ues to variables.
SETLOCAL.A Windows shell command that records the current values assigned to
environment variables in the Windows shell, allowing them to later be restored
by the ENDLOCAL command. (See ENDLOCAL.)
SHIFT.A Windows shell command that alters the position of script parameters in
order to allow Windows shell scripts to access more than nine script input pa-
rameters.
Shortcut. A graphical link to an application or resource (often placed on the
Windows desktop).
SORT.A Windows shell command that sorts data provided to it as input and sends
the result to standard output.
Standard Error. The default location where the Windows shell sends all error
messages. (By default, this is the Windows command console.)
Standard Input. The location where the Windows shell looks for command
input. (By default, this is the computer’s keyboard.)
Standard Output. The default location where the Windows shell sends all
output. (By default, this is the Windows command console.)
363
START.
A Windows shell command that starts a new Windows shell session by
Glossary
opening a new Windows command console.
Statement. A line of code in a script or program.
String Substitution. The search for and replacement of a portion of text
within a string.
Subdirectory. Another term that refers to folders and subfolders.
Subroutine. A collection of statements that scripts jump to and continue pro-
cessing. Unlike procedures, subroutines do not return processing control back to
the statement that follows the statement that executed the subroutine.
Substring. A portion of text extracted from a text string.
Switch. An optional control that modifies the way in which a command is processed.
Syntax. A set of rules that outline the format in which commands must be
formulated for execution.
Syntax Error. A type of error that occurs when programmers fail to follow the
syntax rules that govern the formatting of commands.
systemroot.
An environment variable that specifies the location of the Windows
system root folders.
TEMP.
An environment variable that identifies the name of a folder that can be
used by applications for temporary storage.
time.An environment variable that stores a string representing the current
system time.
TIME. A Windows shell command that displays and modifies the system time.
TITLE. A Windows shell command that modifies the text displayed in the
Windows command console’s title bar.
Token. A representation of a piece of data located in a text string.
TMP.
An environment variable that identifies the name of a folder that can be
used by applications for temporary storage.
Tracing. The process of tracking either script execution flow or variable values
during the execution of a script.
TYPE.
A Windows command that displays the contents of files by sending their
output to standard output.
364
username.
An environment variable that stores the username of the currently
Glossary
logged on user.
Variable. A reference to a location in the computer’s memory where the script
stores a value.
Variable Tunneling. A technique used to pass procedure variables and their
values out of procedures where variable localization has been implemented.
VBScript. A WSH supported scripting language that consists of a subset of the
Visual Basic programming language.
VER. A Windows shell command that displays the Windows version number.
Wild Card. A special character (either * or ?) that can be used to create matches
among files based on a pattern.
WINDIR.
An environment variable that identifies the folder where Windows
system files are stored.
Windows Command Console. A window through which a new Windows shell
session can be accessed via the command prompt.
Windows Registry. A special built-in database that is a part of all Windows
operating systems, starting with Windows 95, where configuration information
is stored regarding system, application, hardware, and users settings.
Windows Shell. A text-based interface to the Windows operating system that
provides access to text-based commands and utilities.
Windows Shell Scripting. A built-in scripting language available on Windows NT,
XP, 2000, and 2003 that features a complete set of programming statements, thus
allowing for the development of scripts that include support for conditional logic,
iterative logic, and the storage and retrieval of data via computer memory.
Working Directory. A reference to the Windows folder on which the Windows
command console is currently focused.
WSH (Windows Script Host). An alternative scripting environment available on
all Windows operating systems starting with Windows 95.
WSH Object Model. A collection of objects provided by the Windows Script Host
that provides access to system resources such as printers and drives.
Index
A B
/A switch B argument, COLOR command, 42
CMD command, 30 background colors, 42
SET command, 100 .bat file extension, 4–5
About screen, creating, 179–180 batch files, 4–5
access blank lines, 18, 21, 93
access limits, variables, 99–100, 216–217 bold text, 45
insufficient authority, 261 built-in commands, list of, 34–35
accessing Buzz the Wonder Dog game example
environment variables, 94–95 assembled script, 111–121
Windows shell, 10 command console, configuring, 105
account administration, 305–311 game design, 105
administration, account, 305–311 project preview, 88–89
append operator, redirection, 67 reader instructions, 107
application event log, Windows, 8 story elements, 108–109
applications, third-party, 334–339 variable substitution, 109–111
archive-management program, 334 welcome screen, 106
arguments
B, COLOR command, 42 C
with blank lines, 93 /C switch, CMD command, 30–31
defined, 90 CALL command
F, COLOR command, 42 overview, 34
formatting rules, 29 syntax, 212
large numbers of, 92 case-sensitivity
modifiers, 28 commands, 29, 262
parameters, 28 labels, 204
PROMPT command, list of, 40 FOR loop, 160
rules for, 262 CD command, 34
switches, 28 chat-like scripts, 324–330
arithmetic operators, 102 CHDIR command, 34
assignment operators, 101 Close command, 14
ASSOC command, 34 closing windows, 14
AT command, script execution, 315–319 CLS command, 18
overview, 34
syntax, 42
Unpredictable Command Prompt game
example, 49
366
CMD command, 11 CALL
Index
Index
files, processing, 164–166 syntax, 41
folders, processing, 166–168 PUSHD, 35
iterating predefined number of times, RD, 35
172–174 REM
looping through command output, overview, 35
162–164 syntax, 60
looping through string contents, REN, 35
160–161 RENAME, 35
overview, 34, 158 RMDIR, 35
parsing options, 160 Save, 14, 17
switches supported by, 159 SET
syntax, 159 /A switch, 100
text files, reading, 169–171 /p option, 19, 94
format of, 27 DELIM parameter, 163
formatting rules, 29 numeric values, 94
FTYPE, 34 overview, 35
GOTO syntax, 93
overview, 34 Unpredictable Command Prompt game
:ProcessFiles subroutine, 205 example, 49
grouping, 70 variable values, changing, 98
IF, 34 SETLOCAL
internal versus external, 34 overview, 35
MD, 35 variable access limits, 99–100, 216–217
MKDIR SHIFT
compound commands, 69 arguments, large numbers of, 92
overview, 35 overview, 35
MOVE, 35 SORT, 66
mutually exclusive, 29 START
naming, 38 opening sessions using, 29–30
NET ACCOUNTS, 305 overview, 35
NET GROUP, 305 parameters, list of, 33
NET LOCALGROUP, 305 syntax, 32
NET USE, 216, 298 syntax, viewing, 28
NET USER, 305 text-based, 27, 174–175
PATH TIME, 35
overview, 35 TITLE
path variable, 36–37 Fortune Teller game example, 72
pathtext variable, 38 overview, 35
syntax, 36 syntax, 39
PAUSE Unpredictable Command Prompt game
Fortune Teller game example, 73–74 example, 50
overview, 35 TYPE
POPD, 35 error logs, 68
PROMPT input/output, redirection, 65–66
arguments, list of, 40 overview, 35
VER, 35
368
comments, adding to scripts, 60–61 displays, cluttered, 18
Index
Index
logic flow, tracing, 251–254 searching, 133–136
user education, 250–251 text files, reading, 169–171
user-friendly error messages, creating, folders
257–258 collections for, processing, 166–168
error logs, creating, 68 error handling, 263
execution, 245 LogFiles, 67
IF ERRORLEVEL statement, 131–132 searching, 133–136
logical Font tab (Command Prompt Properties
common types, 249–250 dialog box), 45
defined, 246 FOR command
messages, execution, 20 case-sensitivity, 160
run-time, 131 collections, 159
common types, 249 files, processing, 164–166
defined, 245 folders, processing, 166–168
syntax, 131 iterating predefined number of times,
common types, 246–248 172–174
defined, 245 looping
event logs, 8 through command output, 162–164
example code. See game examples through string contents, 160–161
execution overview, 34, 158
AT command, 315–319 parsing options, 160
commands, 28, 36 switches supported by, 159
execution environment, WSH, 7 syntax, 159
execution errors, 245 text files, reading, 169–171
exit code, 131 foreground colors, 26, 42
EXIT command formatting rules, commands, 29
external procedures, 260 Fortune Teller game example
overview, 34 assembled script, 79–85
syntax, 259 execution environment, 71–72
external procedures exit process, 77
creating, 212–216 game design, 71
defined, 208 game replay, 79
external versus internal commands, 34 player’s questions, 74–76
predictions, 78
F project preview, 58–59
F argument, COLOR command, 42 random answers, 77–78
File command, 14, 17 story line, 73–74
files welcome screen, 72–73
batch, 4–5 FTYPE command, 34
collections for, processing, 164–166
error handling, 263
extensions
.bat, 4–5
.cmd, 5
370
G CompareChoices procedure, 225–227
Index
Index
project preview, 26 types of, 126
random number selection, 49–50 IF...Else statement, 129
title bar, 50 indentation, 261
user, greeting, 51 input
Windows command console, clearing, 50 redirection, 63–65
GEQ comparison operator, 142 standard input, 64
GOTO command insufficient authority, error handling, 261
overview, 34 interface, graphical, 330–334
:ProcessFiles subroutine, 205 internal procedures
graphical interface, 330–334 defined, 208
graphical pop-up dialogs, error handling, setting up, 208–211
258–259 internal versus external commands, 34
grouping commands, 70 Internet resources, 351–353
GTR comparison operator, 142 italics, arguments in, 29
Guess A Number game example iterative logic, defined, 5
assembled script, 149–153 iterator variables, 159
correct guess, determining, 146–147
execution environment, 143–144 J
game design, 143 JGsoft EditPad Lite text-editor, 344
game results, 147–148 JGsoft EditPad Pro text-editor, 345–347
player input, 145–146 JScript scripting language, 9
project preview, 124–125
welcome screen, 144–145 K
GUI-based editors, 13 /K switch, CMD command, 30–31
Knock Knock game example
H assembled script, 22–24
Height setting controls, screen buffer size, 46 display of, formatting, 18–19
hello.bat script, 15 execution environment, 18
help label, 178–179 player input, validating, 19–20
player responses, collecting, 19
I project preview, 2–3
IF CMDEXTVERSION statement, 132–133 punch line, displaying, 21
IF command, 34 script development process, 17
IF ERRORLEVEL statement, 131–132
IF EXIST statement, 134–136 L
IF NOT CMDEXTVERSION statement, 138 labels, 204
IF NOT DEFINED statement, 137–138 Layout tab (Command Prompt Properties
IF NOT ERRORLEVEL statement, 138 dialog box), 46
IF NOT EXIST statement, 139 LEQ comparison operator, 142
IF NOT statement, 136–137 lines, blank lines, 18, 21, 93
IF statement LogFiles folder, 67
multi-line, 139–140 logging error messages, 256–257
nested, 140–141 logic, conditional and iterative, 5
overview, 127–128 logic flow, error handling, 251–254
372
logical errors O
Index
Index
defined, 208 assembled script, 230–239
setting up, 208–211 CheckForInvalid procedure, 227–228
precautions with, 264 CollectChoice procedure, 224
tunneling data out of, 217–218 CompareChoices procedure, 225–227
variable access, localizing, 216–217 DisplayMenu procedure, 223–224
:ProcessFiles subroutine, 205 DisplayResults procedure, 228–229
PROMPT command DisplayStats procedure, 229–230
arguments, list of, 40 flowcharts, as script development tool,
overview, 35 218–220
syntax, 41 GetComputerChoice procedure, 224–225
pseudo code, 174–175 Initialization section, 221
PUSHD command, 35 Main Processing section, 222
Python scripting language, 10 project preview, 202–203
Run dialog box, 29
Q run-time errors, 131
/Q switch, CMD command, 30 common types, 249
quotation marks, 2 defined, 245
R S
random values, 49–50 /S switch, CMD command, 30
RD command, 35 Save As dialog box, 14, 17
reading text files, 169–171 Save command, 14, 17
redirection Scheduled Task Wizard, 320–324
append operator, 67 scheduled tasks, 320–324
input/output, 64–65 script variables, 93
input sources, 63–64 Scripting and Batch Programming
operators, 65 Resources Web site, 351
SORT command, 66 scripting languages
registry, Windows, 8 JScript, 9
REM command Perl, 10
overview, 35 Python, 10
syntax, 60 REXX, 10
REN command, 35 third-party, 10
RENAME command, 35 VBScript, 9
reply variable, 19–20 scripts. See also game examples; shell
reports, creating, 66–68 scripts
resources hello.bat, 15
Internet, 351–353 passing data to, 90–91
recommended readings, 350–351 self-contained, 90
return code, 131 storing, 15
REXX scripting language, 10 searching files/folders, 133–136
RMDIR command, 35 self-contained scripts, 90
Rob van der Woude’s Scripting Pages Web semi-colon characters, 37
site, 352 sessions, starting, 29–30
374
SET command SORT command, 66
Index
Index
CMD command, list of, 30 InitializeBlanks procedure, 267
defined, 28 Main Processing section, 266–267
FOR loop, 159 player moves, 277–278
syntax project preview, 242–244
CALL command, 212 valid player selections, 274–277
CLS command, 42 welcome screen, 268
CMD command, 28 tilde (~), 104
COLOR command, 42 TIME command, 35
FOR command, 159 time of tasks, scheduling, 322
ECHO command, 42 TITLE command
EXIT command, 259 Fortune Teller game example, 72
IF statement, 126 overview, 35
PATH command, 36 syntax, 39
PROMPT command, 41 Unpredictable Command Prompt game
REM command, 60 example, 50
SET command, 93 Title command, 18
START command, 32 TOKENS parameter, 169
TITLE command, 39 tracing logic flow, 251–254
viewing, 28 tunneling, variable, 218
syntax errors, 131 TYPE command
common types, 246–248 error logs, 68
defined, 245 input/output, redirection, 65–66
system environment variables, 94 overview, 35
T U
/T switch, CMD command, 30–31 /U switch, CMD command, 30
tab-delimited text files, 169 UNC (Universal Naming Convention), 298
tasks, scheduled, 320–324 underscored (_), 11
TEMP environment variable, 95 Universal Naming Convention (UNC), 298
templates, creating, 61–63 Unpredictable Command Prompt game
text-based commands, 27, 174–175 example
text editors. See editors assemble script, 54
text files, reading, 169–171 colors, foreground and background, 51
third-party applications, 334–339 game design, 48–49
third-party scripting language, 10 project preview, 26
Tic-Tac-Toe game example random number selection, 49–50
About procedure, 271 title bar, 50
assembled script, 280–294 user, greeting, 51
board design, 268–269 Windows command console, clearing, 50
game control activity, 271–274 user account administration, 305–311
game design, 264–265 user education, error handling, 250–251
game over, 279–280 username variable, ECHO command, 51
game results, 278 utilities, Defragmenter, 6
help procedure, 270
376
V current working directory, 12
Index
variables registry, 8
access, localizing, 216–217 shell scripts
access limits, 99–100 alternatives to, 7–10
defined, 19, 93 supported operating systems, 7
environment uses for, 6–7
accessing, 94–95 windows, closing, 14
creating, 95 Windows 2000 Commands Pocket
defined, 93 Reference, 350
dynamic, 97 Windows command console, 11
system environment variables, 94 color options, 32
user environment variables, 94 customization options
viewing, 96–97 color settings, 47
iterator, 159 font settings, 45
mathematical, 100–102 options settings, configuring, 44–45
naming, 98–99 sizing, 46
path, PATH command, 36–37 Windows NT Shell Scripting, 351
pathtext, PATH command, 38 Windows Resource Kits, 8
reply, 19–20 Windows Script Host (WSH)
rules for, 262 advantages/disadvantages, 8–9
script, defined, 93 complexities, 9–10
string substitution, 103 execution environment, 7
substring operation, 103 Windows shell
tunneling, 218 accessing, 10
username, ECHO command, 51 overview, 11
values, changing, 98 sending commands to, 12
VBScript scripting language, 9 Windows Shell Scripting and WSH
VER command, 35 Administrator’s Guide, 350
viewing windowsshellscripting.com Web site,
environment variables, 94–97 352–353
syntax, 28 WinZip compression, 334–339
wizards
W Create Shortcut, 15
Web sites, resources, 351 Scheduled Task, 320–324
Width setting controls, screen buffer size, 46 WSH (Windows Script Host)
wild card characters, 165 advantages/disadvantages, 8–9
WINDIR environment variable, 95 complexities, 9–10
Windows execution environment, 7
application event log, 8
command prompt, 2
™
C++ Programming
®
Microsoft C# Programming
®
Java Programming
™
Palm Programming
™
License:
The enclosed software is copyrighted by the copyright holder(s) indicated on the software disc. You
are licensed to copy the software onto a single computer for use by a single user and to a backup
disc. You may not reproduce, make copies, or distribute copies or rent or lease the software in
whole or in part, except with written permission of the copyright holder(s). You may transfer the
enclosed disc only together with this license, and only if you destroy all other copies of the soft-
ware and the transferee agrees to the terms of the license. You may not decompile, reverse as-
semble, or reverse engineer the software.
Limited Liability:
THE SOLE REMEDY FOR BREACH OF THIS LIMITED WARRANTY SHALL CONSIST ENTIRELY OF RE-
PLACEMENT OF THE DEFECTIVE DISC. IN NO EVENT SHALL PREMIER PRESS OR THE AUTHORS BE
LIABLE FOR ANY OTHER DAMAGES, INCLUDING LOSS OR CORRUPTION OF DATA, CHANGES IN THE
FUNCTIONAL CHARACTERISTICS OF THE HARDWARE OR OPERATING SYSTEM, DELETERIOUS IN-
TERACTION WITH OTHER SOFTWARE, OR ANY OTHER SPECIAL, INCIDENTAL, OR CONSEQUEN-
TIAL DAMAGES THAT MAY ARISE, EVEN IF PREMIER AND/OR THE AUTHORS HAVE PREVIOUSLY
BEEN NOTIFIED THAT THE POSSIBILITY OF SUCH DAMAGES EXISTS.
Disclaimer of Warranties:
PREMIER AND THE AUTHORS SPECIFICALLY DISCLAIM ANY AND ALL OTHER WARRANTIES, EI-
THER EXPRESS OR IMPLIED, INCLUDING WARRANTIES OF MERCHANTABILITY, SUITABILITY TO A
PARTICULAR TASK OR PURPOSE, OR FREEDOM FROM ERRORS. SOME STATES DO NOT ALLOW FOR
EXCLUSION OF IMPLIED WARRANTIES OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAM-
AGES, SO THESE LIMITATIONS MIGHT NOT APPLY TO YOU.
Other:
This Agreement is governed by the laws of the State of Indiana without regard to choice of law
principles. The United Convention of Contracts for the International Sale of Goods is specifically
disclaimed. This Agreement constitutes the entire agreement between you and Premier Press re-
garding use of the software.