《Windows脚本编程核心技术精解Chapter01.pdf》由会员分享,可在线阅读,更多相关《Windows脚本编程核心技术精解Chapter01.pdf(28页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、Chapter 1Script Development with EaseIn This Chapter?Write and edit script files?Create blank script files with a mouse click?Select script lines automatically?Get help when scripts misbehave?Execute scripts line by line?Log your scripts activity?Catch errors and handle them yourselfScripts are plai
2、n text files(see Figure 1-1),so you can use any text editor to develop them.However,most text editors are not designed to meetdevelopers needs.For example,they often lack the ability to mark specificlines youd like to take a closer look at.This is unfortunate because when theScripting Host encounter
3、s a problem,it tells you the line number that causedthe hiccupand its nice to have a convenient way of jumping to thatparticular line.In this chapter,youll learn how easy it is to use hidden script techniques toenhance any text editor that has line-marking capabilities.You will also discoverconvenie
4、nt ways of starting new script files with a mere right-click of the mousebutton.In addition,youll discover how scripts are executed line by line and learn about the Script Debugger,which allows you to step through your scriptcode while it is executed.This“slow motion”execution helps you understand t
5、he script mechanics and is also perfect for finding(and resolving)script errors easily.Writing Your First ScriptWriting scripts is as easy as launching your favorite text editor.Even thesimple Windows editor will sufficeJust select Run from your Start menuand enter NOTEPAD.If you like,you can even u
6、se your favorite word-processing software for writing scripts,by using line-numbering or other advanced features.Remember though,word processors dont save plain text files as a defaultthey use their own proprietary binary format.The Scripting Host cant4684-8 ch01.f.qc 3/3/00 9:30 AM Page 3decipher t
7、his format,so youll need to be sure to save your scripts as filetype plain text.In most cases,a plain text editor is the better choice.Now youll see your blank text editor window.This is your playground,theplace where you can start developing your scripts.The traditional first stepin programming boo
8、ks is to greet the world.Lets do it!Figure 1-1:Scripts are just plain text files.At this point,your script is a plain text file.In order to have Windowsinterpret it as a VBScript file and feed its contents to the Scripting Host,youll need to save it with the file extension.vbs(see Figure 1-2).Choose
9、Save As from the File Menu,change the Save in the listbox to Desktop,andenter the filename welcome.vbs.Figure 1-2:Save scripts with a.vbs file extension.Your script will be placed right on your desktop(see Figure 1-3).If you havecorrectly set up the Scripting Host as outlined previously,it will have
10、 thetypical script icon.4Part I:Scripting KickstartII4684-8 ch01.f.qc 3/3/00 9:30 AM Page 4Figure 1-3:A.vbsscriptTo see your script,just open up the file.It will pop up a small dialog box andsay hello to the world(see Figure 1-4).Figure 1-4:It works!Your script says hello to the world.Editing the co
11、ntents of a scriptDuring script development,you will probably edit a script many times,inorder to fix errors and adopt new features(see Figure 1-5).To keep thingssimple,its a good idea to break larger projects into small pieces and run thescript after each step is completed.This way,it is much easie
12、r to identify andcorrect script errors.Figure 1-5:Choose Edit to change a script anytime you feel like itTo change a script,right-click its icon and choose Edit.Make whateverchanges you like,and then save it again.Editing a script is like editing a letter,except that you cant open the script file to
13、 change it,because opening thefile always runs the script.Use the Edit command instead,or drag the scriptfile onto the program icon you want to use for displaying the file contents.Chapter 1:Script Development with Ease5II4684-8 ch01.f.qc 3/3/00 9:30 AM Page 5Conveniently starting new scriptsYou don
14、t have to go through all this clicking and renaming of file extensionsjust to start a new scripting project.Instead,use the scripting capabilities toplace a new command into the New menu.This way,its easy to get newscript files,of the right file type,anytime you want.To insert a new document type in
15、to your New menu,just execute thefollowing script:1-1.VBS this is the file extension the new command should generate:filetype=“.vbs”connect to WScript.Shell for registry access:set WSHShell=CreateObject(“WScript.Shell”)read in the name of the vbs-section:prg=ReadReg(“HKCR”&filetype&“”)read in the of
16、ficial name for vbs-files:prgname=ReadReg(“HKCR”&prg&“”)ask for a new nameask=“What should be the name for new VBScript scripts?”title=“New menu entry”prgname=InputBox(ask,title,prgname)save the new program description:WSHShell.RegWrite“HKCR”&prg&“”,prgname add a New menu entry asking for an empty n
17、ew file:WSHShell.RegWrite“HKCR”&filetype&“ShellNewNullFile”,“”reads a registry key should the key be invalid,complain and stop:function ReadReg(key)on error resume nextReadReg=WSHShell.RegRead(key)if err.Number0 then key could not be read:complain!error=“Error:Registry-Key“”&key _&“”could not be fou
18、nd!”MsgBox error,vbCriticalWScript.Quitend ifend functionThis script is a great example of how powerful the Scripting Host can be.With it,you can change the official name of.vbsfiles and write informationinto the windows registry to make the.vbsfiles available in the New menu.Just enter a name under
19、 which VBScript files will appear in your New menu(see Figure 1-6).6Part I:Scripting KickstartII4684-8 ch01.f.qc 3/3/00 9:30 AM Page 6It may take a few seconds before the new command becomes visible.To force Explorer to recognize the change,click an empty spot on the desktopand press F5.Figure 1-6:C
20、hoose a name for your.vbsscript filesTo start a new script(see Figure 1-7),right-click the mouse,choose New,andthen click the name you specified for.vbsfiles.Thats all there is to it.Windows will generate a new and empty.vbsfile for you.Figure 1-7:Start new script files with the help of New.All that
21、 is left to do is to rename the file and then right-click the file:Edit willopen the empty file in your text editor,and youll be ready to bring yourscript to life.For more information about how the script accomplishes all of this,seeChapter 13.For now,its just a convenient tool.Getting rid of a new
22、entry is even easier:1-2.VBSset WSHShell=CreateObject(“WScript.Shell”)filetype=“.vbs”Chapter 1:Script Development with Ease7II4684-8 ch01.f.qc 3/3/00 9:30 AM Page 7WSHShell.RegDelete“HKCR”&filetype&“ShellNew”MsgBox“Command removed!”Automatically renaming and opening new scriptsScripts can help you t
23、o automate routine tasksits their job.Lets startwith a convenient way to create new scripts from scratch!Placing file templates into the New menu is common practice for many filetypes,and you have just seen how to do this with.vbsfiles.The New menucan do much more,though.You can also place commands
24、into this menu,launching scripts that take over much of the work involved in getting new files.The next script places a new command into the New menu.This commanditself launches another script,and then the subsequent script takes over the responsibility of generating a new script file.1-3.VBS Name o
25、f your new command:commandname=“Get New VBScript file”connect to Wscript.Shell for registry access:set WSHShell=CreateObject(“WScript.Shell”)get path to windows folder:windir=WSHShell.ExpandEnvironmentStrings(“%WINDIR%”)name of the script to be executed by the new command:script=“newvbsfile.vbs”comm
26、and=“WSCRIPT.EXE“+windir+script+“”%2”the dummy file extension name this commands registers with:prgextension=“vbscustom”extension1=“HKCR.vbsneu”extension2=“HKCR”&prgextension&“”save the command to be executed:WSHShell.RegWrite extension1,prgextensionWSHShell.RegWrite extension1+“ShellNewcommand”,com
27、mand Name of the editor you want to open scripts with:WSHShell.RegWrite extension2+“Shellopencommand”,“NOTEPAD.EXE”WSHShell.RegWrite extension2,commandnameWSHShell.RegWrite extension2+“DefaultIcon”,“SHELL32.DLL,44”MsgBox“Command installed.”,_vbInformation+vbSystemModalOnce you run this script(see Fi
28、gure 1-8),youll discover a new entry in theNew menu called Get New VBScript File.8Part I:Scripting KickstartII4684-8 ch01.f.qc 3/3/00 9:30 AM Page 8In order to have Explorer update its menus,you may need to click an emptyspace on your desktop and press F5.Figure 1-8:Your new command launches a scrip
29、t,but its missing.Choosing this entry will raise an errorand thats good!Now you know yourscript is working well,because instead of placing an empty file somewhere,your command tries to execute another script,called newvbsfile.vbs.Yourcommand looks for this script inside your Windows folder,but becau
30、se youhavent placed it there yet,the command fails.It wont fail for long.Just place the following script into your Windows folderand call it newvbsfile.vbs:NEWVBSFILE.VBS look for the arguments the New menu supplied to this script:set args=WScript.Arguments no arguments?Then someone called this scri
31、pt directly:if args.Count=0 thenMsgBox“This script cannot be run directly”WScript.Quitelse access Scripting.FileSystemObject to get a hold of all the file system commands necessary to generate a new and empty script file:set fs=CreateObject(“Scripting.FileSystemObject”)where does the user wants the
32、script file to be placed?Read the arguments:path=args(0)strip off the preliminary file name we just want the path name:path=left(path,InstrRev(path,“”)ask for the name:doask=“I am going to place a new vbs file here:“”&_path&“”.”+vbCr+vbCrask=ask+“Whats the name of the new script file?”name=InputBox(
33、ask)if name=“”then oh,no file name specified!Quit!Chapter 1:Script Development with Ease9II4684-8 ch01.f.qc 3/3/00 9:30 AM Page 9status=3else a name was specified:generate new fully qualified path name for script file:filename=path+name+“.vbs”does this file exist already?if fs.FileExists(filename)th
34、en yes,overwrite it?ask=“Script“”+name _+“”already exists!Replace?”answer=MsgBox(ask,vbQuestion+vbYesNo)if answer=vbYes then delete old filestatus=2else ask for another name:status=0end ifelse generate new file:status=1end if end if ask until a valid file name was enteredloop while status=0if status
35、=3 then no file name was entered:MsgBox“Exit!”,vbInformationelse Create new text file and overwrite any existing file:set handle=fs.CreateTextFile(filename,true)handle.close open new script file automatically for editing:connect to WScript.Shell for Run-command:set WSHShell=CreateObject(“WScript.She
36、ll”)WSHShell.Run“NOTEPAD.EXE“+filenameend ifend ifIts easy to save this file to the Windows folder:Open the file in your editor,choose Save As from your File menu,and use%WINDIR%Enter as yourfilename.The Save As dialog box will immediately switch to your Windowsfolder,and you can save your file usin
37、g newvbsfile.vbsas the filename.Environment variables like%WINDIR%are recognized only with the new set of dialog boxes introduced with Windows 98.On Windows 95 systems,thisshortcut doesnt work.10Part I:Scripting KickstartII4684-8 ch01.f.qc 3/3/00 9:30 AM Page 10Now try your new command again!This ti
38、me,it will find the target script andexecute it.Your new script,newvbsfile.vbs,will politely ask for a filename,and will then automatically open a new file for editing(see Figure 1-9).Figure 1-9:Enter the name of your new script file.Getting Help When Scripts MisbehaveThe more you experiment with sc
39、ripts,the more you will encounter errors.This is absolutely normal.Errors are a great way of learning,and even themost experienced script developer will have to cope with errors every nowand then.Finding(and correcting)errors can be frustrating if you dont have the right tools and strategies to assi
40、st you.This chapter provides you with all the debugging information you need to know.Come back to this chapterwhenever your scripts dont do what you expect them to!Finding the right parts of your scriptsWhenever the Scripting Host encounters a problem,it pops up an errormessage(see Figure 1-10).It m
41、ay look a little ugly,but it provides all theinformation you need,including a short description of the most probablecause and a line number.This line number indicates the script line where the error was discovered.Figure 1-10:This message tells you on which line number an error occurred.The next ste
42、p is to take a look at the line.Open up the script in your editor,right-click the script icon,and choose Edit.Chapter 1:Script Development with Ease11II4684-8 ch01.f.qc 3/3/00 9:30 AM Page 11If your script is relatively short,its easy to identify the line number.Theresonly one caveatturn off word wr
43、apping!Word wrapping breaks long linesinto more than one line so you can view the entire line without the need forhorizontal scrolling.Word wrapping,however,interferes with an editorsability to count line numbers.Using the Notepad editor,open the Edit menu and turn off Word Wrap before you start cou
44、nting line numbers!Once your script grows,counting line numbers becomes tedious.Its just not practical to count a hundred or so lines.Unfortunately,as Ive mentionedpreviously,most editors dont feature GoTo commands that let you jump tospecific lines.Again,this is a great example of how scripts can h
45、elp out.Youcan develop a script that controls your favorite editor and have it jump rightto the line you specify.Use the following script:1-4.VBS mark a line Connect to WScript.Shell-Object which provides the SendKeys-Commandset wshshell=CreateObject(“WScript.Shell”)Ask which line number to highligh
46、t:line=inputBox(“Which line do you want to mark?”)Check whether entry is a number:if not isNumeric(line)thenMsgBox“You did not specify a number!”WScript.Quitelse convert number to Integer:line=Fix(line)is line number valid?if line1 thenMsgBox“Your line number is invalid!”WScript.Quitend ifend if wai
47、t 200 milliseconds(0.2 sec):WScript.Sleep(200)Jump to start of page:CTRL+HOMEwshshell.SendKeys“HOME”Move to line number:for x=1 to line-1wshshell.SendKeys“DOWN”WScript.Sleep 10next Mark line:Jump to beginning of line:HOME12Part I:Scripting KickstartII4684-8 ch01.f.qc 3/3/00 9:30 AM Page 12wshshell.S
48、endKeys“HOME”Mark to end of line:SHIFT+ENDwshshell.SendKeys“+END”To make this script work,save it at a location on your hard drive where it canstay for the next couple of months.Then,drag the script icon onto your Startbutton in the left corner of the task bar(see Figure 1-11).Figure 1-11:Drag scrip
49、ts onto the Start button to place them in the Start menu.Windows will place a shortcut into the Start menu.Next,open your Startmenu,right-click Start,and choose Open.Windows opens the Start menu as a folder,and you see your new link to your script.You will also see the Programs program.Dont delete o
50、r rename this folder!It contains all your program groups,and deleting it will empty the Programscommand located in the Start menu.You can either leave the shortcut inside of your Start menu,or you can storeit in one of your program groups where it wont occupy valuable Start menuspace.To move the sho