MicrosoftWindowsShellScriptingProgrammingfortheAbsolute
Beginner
byJerryLeeFord,Jr.
ISBN:1592000851
PremierPress©2004
IfyouarenewtoprogrammingwithWindowsShellScriptandare
lookingforasolidintroduction,thisisthebookforyou.Learnto
storeandretrieveinformationinvariables,debugscripts,create
conditionallogictests,andmore.
TableofContents
MicrosoftWindowsShellScriptProgrammingfortheAbsoluteBeginner
LetterFromtheSeriesEditor
Introduction
Chapter1 - IntroducingWindowsShellScripting
Chapter2 - InteractingwiththeWindowsShell
Chapter3 - WindowsShellScriptingBasics
Chapter4 - StoringandRetrievingInformationinVariables
Chapter5 - ApplyingConditionalLogic
Chapter6 - CreatingLoopstoProcessCollectionsofData
Chapter7 - CreatingProceduresandSubroutines
Chapter8 - DebuggingandErrorHandling
AppendixA - WindowsShellScriptingAdministrativeScripts
AppendixB - What'sontheCD-ROM?
AppendixC - WhatNext?
Glossary
Index
ListofFigures
ListofTables
ListofSidebars
CDContent
BackCover
IfyouarenewtoprogrammingwithWindowsShellScriptandarelookingfora
solidintroduction,thisisthebookforyou.Developedbycomputerscience
instructors,booksintheFortheAbsoluteBeginnerseriesteachtheprinciplesof
programmingthroughsimplegamecreation.Youwillacquiretheskillsthatyou
needformorepracticalShellScriptprogrammingapplications,andyouwill
learnhowtheseskillscanbeputtouseinreal-worldscenarios.Bestofall,by
thetimeyoufinishthisbook,youwillbeabletoapplythebasicprinciples
you’velearnedtothenextprogramminglanguageyoutackle.
Withtheinstructionsinthisbook,you’lllearnto:
Storeandretrieveinformationinvariables
Applyconditionallogicandcreateconditionallogictests
Improvescriptorganizationwithprocedures
Debugyourscriptsandhandleerrors
Createloopstoprocesscollectionsofdata
AbouttheAuthor
JerryLeeFord,Jr.isaMicrosoftCertifiedSystemsEngineerwithover15years
ofexperienceininformationtechnology.Heholdsamaster’sdegreeinBusiness
Administrationandhasbeenapart-timeITinstructorfor5years.Jerryisthe
authorofseveralbooks,includingMicrosoftWSHandVBScriptProgramming
fortheAbsoluteBeginner.
MicrosoftWindowsShellScript
ProgrammingfortheAbsolute
Beginner
JERRYLEEFORD,JR.
ANDYHARRIS,SeriesEditor
Copyright©2004byPremierPress,adivisionofCourseTechnology.
Allrightsreserved.Nopartofthisbookmaybereproducedortransmittedinany
formorbyanymeans,electronicormechanical,includingphotocopying,
recording,orbyanyinformationstorageorretrievalsystemwithoutwritten
permissionfromPremierPress,exceptfortheinclusionofbriefquotationsina
review.
ThePremierPresslogoandrelatedtradedressaretrademarksofPremierPress
andmaynotbeusedwithoutwrittenpermission.
Microsoft,Windows,Notepad,andVBScriptareeitherregisteredtrademarksor
trademarksofMicrosoftCorporationintheUnitedStatesand/orothercountries.
Allothertrademarksarethepropertyoftheirrespectiveowners.
Important:
PremierPresscannotprovidesoftwaresupport.Pleasecontactthe
appropriatesoftwaremanufacturer'stechnicalsupportlineorWeb
siteforassistance.
PremierPressandtheauthorhaveattemptedthroughoutthisbooktodistinguish
proprietarytrademarksfromdescriptivetermsbyfollowingthecapitalization
styleusedbythemanufacturer.
InformationcontainedinthisbookhasbeenobtainedbyPremierPressfrom
sourcesbelievedtobereliable.However,becauseofthepossibilityofhumanor
mechanicalerrorbyoursources,PremierPress,orothers,thePublisherdoesnot
guaranteetheaccuracy,adequacy,orcompletenessofanyinformationandisnot
responsibleforanyerrorsoromissionsortheresultsobtainedfromuseofsuch
information.ReadersshouldbeparticularlyawareofthefactthattheInternetis
anever-changingentity.Somefactsmayhavechangedsincethisbookwentto
press.
ISBN:1-59200-085-1
LibraryofCongressCatalogCardNumber:2003094425
PrintedintheUnitedStatesofAmerica
0405060708BH10987654321
PremierPress,adivisionofCourseTechnology
25ThomsonPlace
Boston,MA02210
SVP,RetailStrategicMarketGroup:AndyShafran
Publisher:StacyL.Hiquet
SeniorMarketingManager:SarahO'Donnell
MarketingManager:HeatherHurley
ManagerofEditorialServices:HeatherTalbot
AquisitionsEditor:ToddJensen
AssociateMarketingManager:KristinEisenzopf
ProjectEditor/CopyEditor:DanFoster,ScribeTribe
TechnicalReviewer:KeithDavenport
RetailMarketCoordinator:SarahDubois
InteriorLayout:DanielleFoster,ScribeTribe
CoverDesigner:MikeTanamachi
CD-ROMProducer:KeithDavenport
Indexer:SharonShock
Proofreader:KimBenbow
ToAlexander,William,Molly,andMary.
Acknowledgments
Anumberofindividualsdeservecreditfortheirworkonthisbook.Iespecially
wanttothankToddJensen,whoservedasthebook'sacquisitionseditorandwho
hasworkedwithmeonnumerousotherwritingprojects.Ialsowanttothankthe
book'sprojecteditorandcopyeditor,DanFoster,forhisguidanceand
suggestions.Finally,Iwanttoacknowledgethebook'stechnicaleditorandCDROMdeveloper,KeithDavenport,aswellaseveryoneelseatPremierPressfor
alltheirhardwork.
AbouttheAuthor
JerryLeeFord,Jr.isanauthor,educator,andITprofessionalwithover15years
ofexperienceininformationtechnology,includingrolesasanautomation
analyst,technicalmanager,technicalsupportanalyst,automationengineer,and
securityanalyst.JerryisaMCSEandhasearnedMicrosoft'sMCPandMCP+
Internetcertifications.Inaddition,hehasamaster'sdegreeinBusiness
AdministrationfromVirginiaCommonwealthUniversityinRichmond,Virginia.
Jerryistheauthorof12otherbooks,includingLearnJavaScriptinaWeekend,
LearnVBScriptinaWeekend,MicrosoftWindowsShellScriptingandWSH
Administrator'sGuide,VBScriptProfessionalProjects,andMicrosoftWindows
XPProfessionalAdministrator'sGuide.
Hehasover5yearsofexperienceasanadjunctinstructorteachingnetworking
coursesinInformationTechnology.JerrylivesinRichmond,Virginia,withhis
wife,Mary,andtheirchildren,William,Alexander,andMolly.
LetterFromtheSeriesEditor
Atsomepoint,you'veprobablybeguntowantmorecontrolofyourcomputer.
Youmaywanttomakeprogramsactalittlebitdifferentlythanthedefault
behavior,automatetedioustasks,orperformcertainjobsautomatically.
Ultimately,suchtaskscomedowntoprogramming.Theprogrammingworldcan
beveryintimidating,withalltheintegratedenvironments,complexlanguages,
anddizzyingvarietyofresources.Programminglookshard,and,frankly,itlooks
boring.
Inthisbook,JerryLeeFordwillshowyouhowtocontrolyourcomputerin
amazingways.You'lllearnsomerelativelyeasytricksthatwillprofoundly
improvethewayyouworkwithyourcomputer,andyou'lllearnthebasicsofthe
programmingartalongtheway.Windowsshellscriptingisnotthemost
complexprogrammingenvironment,andthat'samajorpartofitscharm.This
reasonablycleanlanguageisidealforbeginnerspreciselybecauseitisso
focused.
Whileshellscriptingisextremelyuseful,thatdoesn'tmeanlearningaboutithas
tobedryandboring.Likeallthebooksinthisseries,thisbookteachesthrough
simplegameprogramming.Nobody'sgoingtouseWindowsshellscriptingto
writethenextimmersive3-Dactiongame,butgamescanbeaninterestingway
tolearnabouttheprocessofwritingmoretraditionalprograms.Don'tworry,
therewillbelotsofpracticalexamplesasyougothroughthisbook.
Ifyou'renewtoprogramming,youwon'tfindabetterplacetostartthanthis
book.Ifyou'realreadyanexperiencedprogrammer,you'llbeamazedathowyou
canusetheskillsinthisbooktoleverageyourabilities.Regardless,you'lllearna
lotandhaveagoodtimedoingit.
AndyHarris
FortheAbsoluteBeginnerSeriesEditor
Introduction
Windowsshellscriptingisabuilt-inscriptinglanguagefoundonmodern
Windowsoperatingsystems.Itprovidestheabilitytocreateandrunsmall
programsorWindowsscriptfilesmadeupofWindowsshellscriptstatements
andWindowscommands.Windowsshellscriptsarecreatedasplaintextfiles
thataresavedwith.bator.cmdfileextensionsandrunfromtheWindows
commandprompt.
Windowsshellscriptsareoftensmallfilesthatcanbecreatedandtestedwithin
minutes.Infact,manygoodWindowsshellscriptsarelessthan10or15lines
long.ThismakesitaperfectlanguageforquicklyautomatingWindowstasks.
ThisalsomakesWindowsshellscriptingagreatfirstlanguagetolearn.
Unlikemanymodernprogramlanguages,Windowsshellscriptingisnotobject
oriented.Inaddition,itdoesnotrequireyoutofirstlearnhowtooperatea
complexdevelopmentenvironment.However,Windowsshellscriptingdoes
haveacompletecollectionofstatements—theelementsthatmakeupits
programminglanguage.Thisallowsfirst-timeprogrammerstofocusonlearning
thebasicsofprogramdesignwithoutbeingburdenedwiththeadded
requirementsimposedbymanyotherprogramminglanguages.
Windowsshellscriptsalsoprovideawaytoautomatecomplextasks,especially
thosepronetohumanerror.Oncecreated,Windowsshellscriptscanbeshared
withotherpeople,allowingyoutodistributeandshareyourwork.Using
Windowsshellscripts,youcanaccessandmanipulateWindowsresourcessuch
astheWindowsfilesystemanddiskandprinterresources,andyoucaneven
automatetheexecutionofnetworktasks.Inaddition,asthisbookwill
demonstrate,youcancreateWindowsshellscriptsthatautomateandcontrolthe
executionofallkindsofthings.Forexample,thisbookwillshowyouhowto
createWindowsshellscriptsthat
PlaycomputergameslikeRock,Paper,ScissorsandTic-Tac-Toe.
Copyandmovefilesandfolders.
Establishconnectionstonetworkresourcessuchasnetworkdiskdrivesand
folders.
Createtextreportsandlogfiles.
ExecuteWindowsutilitiessuchastheWindowsDiskDefragmenter.
Createuseraccountsandadministergroupaccountmembership.
Controlthird-partyapplicationssuchasWinZip.
WhyWindowsShellScripting?
Windowsshellscriptingisagreatlanguagefordevelopingsmallscriptsthat
automatecommonlyperformedtasks.Atthesametime,youcanuseittocreate
someincrediblycomplexscripts.However,inmostcasesyouwillfindthatmost
Windowsshellscriptsarenotverylarge.OftenWindowsshellscriptsareonlya
fractionofthesizeofprogramswritteninhigher-levellanguagessuchasVisual
BasicandC++.Thisreducescomplexityandresultsinshorterdevelopment
time.ItalsomakesWindowsshellscriptingagreattoolforrapiddevelopment,
allowingyoutoquicklycreateandtestscriptsandthenmoveontootherwork.
Windowsshellscriptingmakesanexcellentfirstprogramminglanguage.Asfar
asprogramminglanguagesgo,itisstraightforwardandeasytolearn.Yet,using
Windowsshellscriptingyoucanlearneventhemostcomplexprogramming
concepts.AllthatyouneedtobegincreatingWindowsshellscriptsisaplain
texteditorsuchasWindowsNotepad.
BylearningWindowsshellscripting,youwillbegintobuildafoundationfor
learningotherprogramminglanguages.OnceyouhavemasteredWindowsshell
scriptingyoumaywishtotackleotherscriptinglanguagessuchasVBScriptor
JScript,bothofwhichcanbeusedtoperformadvancedshellscriptingon
Windowscomputers.YoumayalsowanttouseWindowsshellscriptingasa
jumpingoffpointformoreadvancedobject-orientedprogramminglanguages
likeVisualBasicandC++.ThebottomlineisthatlearninghowtouseWindows
shellscriptswillgiveyouafoundationthatwillfacilitatelearningother
programminglanguages.
WhoShouldReadThisBook?
Ihavedesignedthisbooktoteachyouhowtobecomeaprogrammerusing
Windowsshellscripting.Apreviousprogrammingbackgroundisnotrequired.
However,youwillneedabasicunderstandingofcomputersingeneralanda
goodoverallworkingknowledgeofatleastoneMicrosoftoperatingsystem.
Sowhetheryouareafirst-timeprogrammerlookingforagoodlanguagetolearn
asyoubeginyourprogrammingcareeroryouarelookingtoquicklylearna
secondprogramminglanguage,thisbookcanhelpyou.Inaddition,Ithinkyou
willfindthatthisbook'sgames-basedapproachwillhelptokeepthingsfunas
youlearn.
WhatYouNeedtoBegin
Tousethisbookeffectively,youwillneedanumberofthings.First,youwill
needaWindowsoperatingsystemthatsupportsWindowsshellscripting.These
operatingsystemsinclude
WindowsNT4.0
Windows2000
WindowsXP
Windows2003
Youwillalsoneedaneditorthatsupportsthecreationofplaintextfiles.Asa
startereditor,youcanbeginworkingwiththeWindowsNotepadtexteditor.
However,overtimeyouwillprobablyfindthatNotepadisratherlimited,and
youwillwanttouseamoreadvancededitorthatsupportsfeatureslikesyntax
color-codingandadvancedsearch-and-replacefeatures.Tohelpyouout,Ihave
includedtwoexcellenteditorsonthisbook'scompanionCD-ROM.Tolearn
moreaboutthesetwoeditors,checkoutAppendixB,"What'sontheCD-ROM?"
HowThisBookIsOrganized
Iwrotethisbookbasedontheassumptionthatyouwouldreaditsequentially,
frombeginningtoend.Ifthisisyourfirstprogrammingexperienceorifyoufeel
thatyouneedaprogrammingrefresher,Isuggestthatyoureadthebookinthis
manner.IfyouareaveteranprogrammerandintendtolearnWindowsshell
scriptingasanadditionallanguage,youmaywanttoskiparoundandreadtopics
thatareofthemostinteresttoyou.
ThefirstpartofthisbookintroducesyoutoWindowsshellscripting.Itprovides
anoverviewofWindowsshellscriptingandtheWindowscommandprompt.
ThesecondpartofthisbookteachesyouthebasicsofWindowsshellscript
development.Itcovershowtodisplayscriptoutputandhowtousecomments
andvariables.Italsocoverstheshellscriptstatementsthatprovidetheabilityto
applyconditionallogicandestablishloops.
Thethirdpartofthisbookfocusesinonavarietyofadvancedtopics.HereI'll
showyouhowtoimprovetheorganizationofyourWindowsshellscriptsusing
proceduresandsubroutines.I'llalsogooverthestepsinvolvedindebuggingand
handlingscripterrors.
Thefinalpartofthisbookcontainsthebook'sappendixes.Hereyouwillfinda
collectionofreal-worldsamplescripts,informationaboutthematerialsfoundon
thebook'sCD-ROM,andinformationaboutplaceswhereyoucangotocontinue
yourWindowsshellscriptingeducation.
Adetailedbreakdownoftheinformationyouwillfindinthisbookisoutlined
below.
Chapter1—IntroducingWindowsShellScripting.Thischapterexplains
whatWindowsshellscriptingisandwhyitisanexcellentfirst
programminglanguagetolearn.Thischapterprovidesabriefhistoryof
WindowsshellscriptingaswellasacomparisontoMicrosoft'sother
scriptingtechnology,theWindowsScriptHost,andexplainsthedifferences
betweenthesetwoscriptingsolutions.Thischapterclosesbyteachingyou
howtowriteyourfirstWindowsshellscriptbyshowingyouhowto
developyourfirstWindowsshellscriptgame,theKnockKnockjoke.
Chapter2—InteractingwiththeWindowsShell.Thischapterprovides
youwithareviewoftheWindowsshellandexplainshowtoworkwithit
(e.g.,startinganewshell,issuingcommands,andclosingtheshell).The
chaptergoesontodiscusshowtoworkwiththeWindowscommand
promptandexplainsbasiccommandsyntax.Specificcommandsthataffect
theappearanceoftheWindowscommandconsolearethenreviewed.This
willleadintoadiscussiononcommandconsolecustomization.Finally,the
chapterconcludesbyshowingyouhowtowriteascriptcalledthe
UnpredictableCommandPrompt.
Chapter3—WindowsShellScriptingBasics.Inthischapter,Iwill
provideyouwithareviewofbasicWindowsshellscriptingtechniques,
includinghowtocontrolthedisplayofoutputandhowtoformatthe
displayusingblanklines.Iwilldiscusstheimportanceofcreatinga
documentationtemplate.Thischapterwillalsoshowyouhowtocontrol
shellinputandoutputandhowtoredirectcommandoutputinorderto
createreportandlogfiles.Thischapterwillalsoshowyouhowtocreate
theFortuneTellergame,whichanswersquestionsaskedofitbytheplayer.
Chapter4—StoringandRetrievingInformationinVariables.This
chaptershowsyouhowtowritescriptsthatacceptandprocessargument
inputatruntime.Youwillalsolearnhowtoretrieveinformationaboutyour
computerfromsystemvariables.Youwillthenlearnabouttherulesthat
applytothecreationofvariables.Thischapterwillalsodemonstrate
differentwaystomanipulatethevalueofnumericvariablesaswellashow
toaccessalloraportionoftextstoredinstringvariables.Thechapterwill
endbyteachingyouhowtocreate"TheStoryofBuzztheWonderDog"
game,whichcreatesacustomizedstorybasedoninformationitcollects
fromtheuser.
Chapter5—ApplyingConditionalLogic.Inthischapter,youwilllearn
howtoapplyconditionallogicinyourscripts.Thiswillenableyouto
createscriptsthatcancollectandtestthevalueofdataandthenalterthe
waythescriptexecutesdependingonthevalueofthedata.Youwillalso
learnhowtodevelopmorecomplicatedlogicbynestingonelogicaltest
withinanother.ThischapterconcludesbyintroducingtheGuessaNumber
game,inwhichtheplayerischallengedtoguessanumberbetween1and
32,000usingthefewestpossibleguesses.
Chapter6—CreatingLoopstoProcessCollectionsofData.Thischapter
coversthecreationofloopsasameansofprocessinglargeamountsofdata.
Itwilldemonstratehowtouseloopstoprocessstringcontents,command
output,andfileandfoldercontents.Thischapteralsointroducesyoutothe
useofpseudocodeasatoolforestablishingahigh-levelscriptdesign.This
chapterendsbyteachingyouhowtocreatetheSix-Million-DollarQuiz
game.Inthisgame,theplayerispresentedwithaseriesofquizquestions
that,onceanswered,aregradedandusedtogenerateagamescorecard
reportfile.
Chapter7—CreatingProceduresandSubroutines.Thischapter
introducesyoutotheuseofflowchartsasadesigntool.Italsoshowsyou
howtoexecuteonescriptfromwithinanotherscript.Thechapteralso
coverstheuseofproceduresandsubroutines,whichenableyoutoimprove
scriptorganizationwhilealsoreducingcomplexity.Thischapterconcludes
bycoveringthedevelopmentoftheRock,Paper,Scissorsgame.
Chapter8—DebuggingandErrorHandling.Inthisfinalchapter,I'll
introduceyoutoanumberofdifferenttopics.I'llgiveyoutipsonhowto
developyourscriptinamodularfashionandhowtotestyourscriptsone
moduleatatime.You'llalsolearnhowtotestintermediateresultsduring
scriptdevelopmentandtesting.Thingsconstantlychangeonacomputer
system,andasaresultyourscriptsmaybreakorexperienceproblemsover
time.Todealwiththesesituations,I'llprovideyouwithsomebasic
debuggingtechniquesandgiveyouadvicethatwillhelpyoutodetectand
dealwithscripterrors.Thischapterwillendbysteppingyouthroughthe
developmentofonefinalgameprojectcalledTic-Tac-Toe.
AppendixA—WindowsShellScriptingAdministrativeScripts.This
appendixprovidesyouwithacollectionofpracticalexamplesthat
demonstratetheuseofWindowsshellscriptinginreal-worldsituations.I
includedthisappendixtoassistyouinmakingatransitionfromthebook's
game-basedapproachtoreal-worldscriptdevelopment.
AppendixB—What'sontheCD-ROM?Inthisappendix,I'llsupplyyou
withinformationaboutthesamplescriptsthatyouwillfindonthebook's
accompanyingCD-ROM.I'llalsoprovideyouwithafreewarecopyofthe
EditPadLitetexteditorandasharewarecopyoftheEditPadProtexteditor
alongwithabriefoverviewofwhatthesetwoeditorscando.
AppendixC—WhatNext?Inthisappendix,Igiveyouadviceonhowto
continueyourWindowsshellscriptingeducation.I'llincludereferencesto
otherbooksthatIthinkyouwillfinduseful,andI'llalsoprovideyouwith
informationaboutanumberofWebsiteswhereyou'llfindmore
information,includingplentyoffreesamplescriptsthatyoucandownload.
Glossary.Thisunitprovidesyouwithaglossaryofthekeytermsused
throughoutthebook.
Thisbookusescomputergamedevelopmentasameansofteachingyouhowto
programusingWindowsshellscripting.Eachgameyouencounterwillbealittle
morecomplexthantheonebeforeit.Inthefirstfewchapters,you'llseescripts
thatwillincludeelementsnotyetcoveredinthatpointofthebook.Forthese
scripts,you'llneedtokeepreadingwiththeunderstandingthateverythingyou
seewilleventuallybeexplained.Meanwhile,Iwillprovideyouwithasmuch
informationasIcanwithoutoverwhelmingyouintheearlystagesofthebook.
ConventionsUsedinThisBook
Tomakeiteasierforyoutoreadandworkwith,thisbookusesanumberof
conventions.Theseconventionsaredescribedbelow.
HINT
Asyoureadalong,I'lloffersuggestionsfordifferentorbetterwaysof
doingthingsthatwillhelpmakeyouabetterandmoreefficient
programmer.
TRAP
I'llalsopointoutplaceswhereit'seasytomakemistakes,andI'llgive
youadviceforavoidingthem.
TRICK
Wheneverpossible,I'llshareshortcutsandtechniquesthatwillmake
thingseasierforyou.
DEFINITION
Toaidyourunderstanding,I'lldefinekeytermsalongtheway.
(Youcanalsorefertotheglossaryinthisbookforadditional
information.)
INTHEREALWORLD
Throughoutthebook,I'llstopalongthewaytopointouthowtheknowledgeand
techniquesyouarelearningcanbeappliedtoreal-worldscriptingprojects.
EXERCISES
Attheendofeverychapter,I'llincludeacollectionofsmallprojectsuggestions
thatyoucandotocontinuebuildingontheskillsyou'velearned.
Chapter1:IntroducingWindows
ShellScripting
Overview
WindowsshellscriptingisoneoftwoscriptingsolutionsprovidedbyMicrosoft
fordevelopingsmallprograms,orscripts,thatautomateavarietyoftaskson
Windowscomputers.(TheotherscriptingsolutionisknownastheMicrosoft
WindowsScriptHost,orWSH.)Scriptsprovideameansofdevelopingsmall
utilityprogramsthatautomatemundaneorcomplextaskswithaminimal
investmentoftimeandeffort.
WindowsshellscriptingprovidesawaytoperformtasksonWindowscomputers
withoutrequiringyoutowadethoughthearrayofwindowsanddialogsboxes
thatmakeuptheWindowsgraphicaluserinterface,orGUI.Scriptshelpto
eliminatetypingmistakesorothererrorsthatoftenoccurwhenyouperforma
taskmanually.Therefore,scriptsnotonlyhelpyouworkfasterbutmore
accuratelyaswell,especiallywhenyou'reworkingontaskscomprisedofalarge
numberofsteps.Inthischapter,I'llintroduceyoutoWindowsshellscripting
andprovideyouwiththebackgroundinformationyou'llneedfortherestofthe
book.Inaddition,I'llshowyouhowtodevelopyourfirstWindowsshellscript
game.
Specifically,youwilllearn
ThecapabilitiesofWindowsshellscripts
ThehistoryofWindowsshellscripting
ThedifferencesbetweenWindowsshellscriptsandtheWindowsScript
Host
Howtoconfigurethescriptdevelopmentandtestingenvironment
ProjectPreview:TheKnockKnockJoke
Thischapter,likeallotherchaptersinthisbook,concludesbyshowingyouhow
todevelopacomputergameusingWindowsshellscripting.Thegameyouwill
learntowriteinthischapteriscalledtheKnockKnockjoke.Bygoingthrough
thestepsrequiredtodevelopthisgame,youwilllearnthebasicmechanics
involvedincreatingandrunningWindowsshellscripts.
TheKnockKnockjokeisasimplescriptasfarasgame-basedWindowsshell
scriptsgo.YouwillrunitbyopeningtheWindowscommandprompt,typingin
thenameofthescript,andpressingtheEnterkey.Thescriptwillrespondby
displayingtheopeningKnockKnockmessage,asshowninFigure1.1.Theuser
mustthentype"Whoisthere?"(includingtheopeningandclosingquotation
marks)andpressEnter.Thescriptwillrespondbydisplayingthereplyof
Orange.Theusermustthentype"OrangeWho?"asshowninFigure1.2.
Figure1.1:TheKnockKnockgamebeginsbydisplayingaKnockKnock
message.
Figure1.2:Thegamepromptstheplayertorespondtothesecondpartofthe
joke.
DEFINITION
TheWindowscommandpromptappears,bydefault,intheform
ofadriveletterfollowedbyacolon,thebackslashcharacter,
andthenthe"greaterthan"symbol(forexample,C:\>).The
commandpromptacceptstextinputthatispassedtothe
operatingsystemforprocessing.
Finally,thescriptdisplaysthejoke'spunchlineasshowninFigure1.3.Ifthe
playermakesatypowhenenteringoneoftherequiredresponsestothejoke,one
ofthetwomessagesshowninFigure1.4and1.5willbedisplayed.
Figure1.3:Thegamedeliversthejoke'spunchline.
Figure1.4:Thegamenotifiestheplayerofanyincorrectinput.
Figure1.5:Withincorrectplayerinput,thegamemayprematurelyexitand
generateanerrormessage.
Don'tworryabouttryingtounderstandeverylineofcodethatyou'lltypeinto
thescript;you'lllearnwhateverythingmeansasyoureadthroughthisbook.The
importantthingtolearninthischapterarethestepsinvolvedincreatingand
savingyourfirstscript.Bycompletingthisscript,youwillprepareyourselffor
themoreadvancedprogrammingconceptsintroducedinlaterchapters.
OverviewofWindowsShellScripting
IntheveryearlydaysofWindowsoperatingsystems,therewasnopoint-andclickgraphicaluserinterface.Everythingwasdoneviathekeyboardbytyping
incommandsattheWindowscommandprompt.Thismeantthatusershadto
memorizeallkindsofcommandsinordertousetheircomputers.Worsestill,
mostWindowscommandscouldbeenteredusinganumberofvariations,
makingitvirtuallyimpossibletomemorizeallpossiblecommands.Naturally,
thismeantthatpeoplespentalotoftimelookingupcommands.Oftenusers
foundthattheyneededtotypethesamesetofcommandsoverandoveragain.
Tomakethiseasierandtoeliminatetypingerrors,usersandadministrators
createdbatchfiles.Abatchfileisaplain-textfilemadeupofthesameWindows
commandsthatyoutypeinattheWindowscommandprompt.Batchfileshavea
.batfileextension.Theyareexecutedbytypingintheirnameatthecommand
promptandpressingtheEnterkey.Theoperatingsystemthenexecuteseach
commandinthebatchfile,oneatatime,startingatthebeginningofthefile.
Intheearly1980s,Microsoftintroduceditsgraphicaluserinterfaceandmost
usershappilyleftbehindallmemoryofWindowscommandsandthecommand
prompt.However,batchfilesstillremainedvaluabletoolsforautomatingthe
executionofcollectionsofcommandsandutilities,andwereespeciallyusefulto
powerusersandadministrators.
BatchfilesremainedlimitedtosequentialWindowscommandexecution.The
onlyalternativesavailabletobatchfilesweremanuallyexecutingcommandsat
theWindowscommandprompt,purchasinganapplicationwrittentoperform
equivalentsettasks,orwritingacustomprogramusinganadvanced
programminglanguagesuchasCorC++tocreateanewcustomapplication
capableofperformingtherequiredtasks.
AsI'msureyoumustbethinking,noneofthesethreeoptionswasverypractical.
Theyrequiredeithertoomuchmoneyormoretimethanusersandadministrators
werewillingtospend.Finally,intheearly1990s,Microsoftintroduced
WindowsNT.ThisMicrosoftoperatingsystemfeaturedabuilt-inscripting
languageknownasWindowsshellscripting.Windowsshellscriptingdiffered
fromold-stylebatchfilesinthatitfeaturedacompletesetofprogramming
statements,thusallowingforthedevelopmentofscriptsthatincludedsupportfor
conditionallogic,iterativelogic,andthestorageandretrievalofdatausing
computermemory.
DEFINITION
Thetermconditionallogicreferstoascript'sabilitytoexamine
dataandthenadjustwhatitdoesbasedontheresultsofa
conditionalanalysis.
DEFINITION
Thetermiterativelogicreferstoascript'sabilitytorepeatedly
executeaseriesofstepsoverandoveragain.
DEFINITION
Astatementisalineofcode.Moststatementsfitonasingle
line;however,lengthystatementscanbespreadovermultiple
lines.
MicrosofthassinceaddedsupportforWindowsshellscriptingtoallWindows
operatingsystemsthathavebeenbuiltonWindowsNTtechnology(e.g.,
Windows2000,XP,and2003).
HINT
Whilethecollectionofprogrammingstatementsthatmakeupthe
Windowsshellscriptlanguagehasremainedessentiallythesameover
theyears,afewofthestatementshavebeenmodifiedtoextendtheir
functionality.Ratherthanattempttoidentifyandexaminedifferencesin
Windowsshellscriptingstatementsbetweeneachofthedifferent
Windowsoperatingsystems,thisbookusesWindowsXPasitsassumed
developmentplatform.
IfyouplanonwritingscriptsthatwillbeexecutedbyolderWindows
operatingsystems,youshouldretestthescriptsoneachoperating
systemtomakesurethattheyworkasyouexpectthemto.Inaddition,
youcancheckanyWindowscommand'ssyntaxtoseewhatsyntaxit
supportsonagivenoperatingsystembyaccessingtheWindows
commandpromptandtypingthenameofthecommandfollowedbya
spaceandthewordHELP.
Windowsshellscriptsaresavedwitha.bat("batch")or.cmd("command")file
extension.Thisway,whentheoperatingsystemisaskedtorunthem,itwill
knowtoexecutethemusingtheWindowsshell.
DEFINITION
The.cmdfileextensionisanotherfileextensionthatWindows
associateswithWindowsshellscripts.
WhatCanShellScriptsDo?
Windowsshellscriptscanaccomplishanytaskthatcanbecompletedfromthe
Windowscommandprompt.DespitecontinualeffortstoimprovetheWindows
graphicaluserinterfaceandtomakethingseasierforusersbyprovidingonlya
completepoint-and-clickexperience,Microsofthascontinuedtoupdateand
expandtheWindowscommandlinefunctionality(e.g.,eachnewWindows
operatingsystemaddsnewcommandsandrefinesexistingcommands).
Microsoftalsoaddscommandlineaccesstomanyofitsutilityprograms,
allowingthemtobeaccessedandcontrolledbyscripts.Forexample,the
Defragmenterutility(whichreorganizesfilesstoredonyourdiskdriveformore
efficientstorage)canberunfromtheWindowsgraphicaluserinterfaceon
WindowsXPbyselectingStart,AllPrograms,Accessories,SystemTools,and
thenDiskDefragmenter.Alternatively,youcanexecutethisutilityprogramfrom
withinaWindowsshellscript.Forexample,bytypingdefragC:/fyoucan
automatethedefragmentationofyourcomputer'sCdriveusingthisutility.
Windowsshellscriptscanbeusedtoautomateallofthefollowingcategoriesof
tasks:
Complicatedtasks.Thiscategoryofscriptedtasksincludesanytasksthat
arehighlysubjecttoerrorwhenperformedmanually,suchasthe
administrationofsystemresourceslikediskdrivesandprinters.
Repetitivetasks.Thesescriptedtasksincludeanytasksthatmustbe
performedoverandoveragain,suchasthedeletionofcertainfiletypes
fromspecificfoldersonaregularbasis.
Lengthytasks.Thesescriptedtasksincludeanytasksthattaketoolongto