欢迎来到淘文阁 - 分享文档赚钱的网站! | 帮助中心 好文档才是您的得力助手!
淘文阁 - 分享文档赚钱的网站
全部分类
  • 研究报告>
  • 管理文献>
  • 标准材料>
  • 技术资料>
  • 教育专区>
  • 应用文书>
  • 生活休闲>
  • 考试试题>
  • pptx模板>
  • 工商注册>
  • 期刊短文>
  • 图片设计>
  • ImageVerifierCode 换一换

    Windows脚本编程核心技术精解Chapter01.pdf

    • 资源ID:70021352       资源大小:430.70KB        全文页数:28页
    • 资源格式: PDF        下载积分:15金币
    快捷下载 游客一键下载
    会员登录下载
    微信登录下载
    三方登录下载: 微信开放平台登录   QQ登录  
    二维码
    微信扫一扫登录
    下载资源需要15金币
    邮箱/手机:
    温馨提示:
    快捷下载时,用户名和密码都是您填写的邮箱或者手机号,方便查询和重复下载(系统自动生成)。
    如填写123,账号就是123,密码也是123。
    支付方式: 支付宝    微信支付   
    验证码:   换一换

     
    账号:
    密码:
    验证码:   换一换
      忘记密码?
        
    友情提示
    2、PDF文件下载后,可能会被浏览器默认打开,此种情况可以点击浏览器菜单,保存网页到桌面,就可以正常下载了。
    3、本站不支持迅雷下载,请使用电脑自带的IE浏览器,或者360浏览器、谷歌浏览器下载即可。
    4、本站资源下载后的文档和图纸-无水印,预览文档经过压缩,下载后原文更清晰。
    5、试题试卷类文档,如果标题没有明确说明有答案则都视为没有答案,请知晓。

    Windows脚本编程核心技术精解Chapter01.pdf

    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 plain 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 encounters 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 discoverconvenient 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 the 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 use 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 this 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 books 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).ChooseSave 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 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 contents 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 easier 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 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 dont 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 into 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 official 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 new 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 found!”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 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:Choose 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 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 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 to 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 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 of 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”command=“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”,command 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 Figure 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 script,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 because 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 script 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 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(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)then 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=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.Shell”)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 using 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 time,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 scripts,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 assist 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 may 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 step 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 wrapping!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 counting 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 help 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 highlight: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 wait 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.SendKeys“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 scripts 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 or 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

    注意事项

    本文(Windows脚本编程核心技术精解Chapter01.pdf)为本站会员(qwe****56)主动上传,淘文阁 - 分享文档赚钱的网站仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。 若此文所含内容侵犯了您的版权或隐私,请立即通知淘文阁 - 分享文档赚钱的网站(点击联系客服),我们立即给予删除!

    温馨提示:如果因为网速或其他原因下载失败请重新下载,重复下载不扣分。




    关于淘文阁 - 版权申诉 - 用户使用规则 - 积分规则 - 联系我们

    本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知淘文阁网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

    工信部备案号:黑ICP备15003705号 © 2020-2023 www.taowenge.com 淘文阁 

    收起
    展开