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

上传人:asd****56 文档编号:70322709 上传时间:2023-01-19 格式:PDF 页数:32 大小:429.70KB
返回 下载 相关 举报
Windows脚本编程核心技术精解Chapter03.pdf_第1页
第1页 / 共32页
Windows脚本编程核心技术精解Chapter03.pdf_第2页
第2页 / 共32页
点击查看更多>>
资源描述

《Windows脚本编程核心技术精解Chapter03.pdf》由会员分享,可在线阅读,更多相关《Windows脚本编程核心技术精解Chapter03.pdf(32页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。

1、Chapter 3Kidnapping ObjectsIn This Chapter?Find out more about objects?Connect to objects and list all available objects on your system?Analyze the inner structure of objects?Read secret TypeLibrary information to retrieve the commands stored inobjectsWhy should you deal with objects?Well,because VB

2、Script is merelysoftware glue.You can write little scripts that do useful things,but to really accomplish powerful automation tasks,VBScript is definitely notenough.In this chapter,all you need to do is sit back and enjoy the ride.This tour will show you how to get all the information you need to un

3、derstand scriptdevelopmentand Ill show you how to find out the names of all the hiddenmethods stored inside objects.Eventually,all of this information will fall into place without much brainwork.You want action fast?Then fast forward to Part II.You already knoweverything you need to execute scripts.

4、Part II is loaded with everydayexamples you can try out and use as a foundation for your own experiments.Do come back later,though,to find out all about hidden COM objects andhow to access their methods.What Objects Really AreVBScript only delivers the basic infrastructure.You can define decisions,f

5、unctions,and procedures,but VBScript has no command to access any ofthe interesting parts of your computer.These include reading values from theWindows Registry,for example,or checking for available disk space.The realwork has to be done by someone different.Fortunately,VBScript contains one very po

6、werful commandCreateObject.This command can access COM components installed on your system and“borrow”all the commands stored inside of this component.This is anincredible source of power.4684-8 ch03.f.qc 3/3/00 9:31 AM Page 85There is a lot of confusion about the technical terms.COM objects storefu

7、nctionality in a language-independent format.Some books refer to COMobjects as ActiveX objects;others use the old term OLE2.Just think of COMobjects as black boxes that contain useful stuff.You dont need to know howthe COM object achieves its results.As you will see,almost any modernsoftware stores

8、its functionality in a number of COM objects.These modulescan be accessed by anyone.Basically,through the use of COM objects,your scripts can do just abouteverything a regular program can do.There arent limits anymore.And evenbetter,you dont need to waste your time programming all of these functions

9、yourself.In fact,you dont even have to know much about programming.Chances are there are already predefined ActiveX objects on your system,bethey database access,Internet FTP transfer,or scanner control.Just pick theright ActiveX component and have your script boss it around.Thats the funpart about

10、scriptingyou get incredible power,yet you dont have to inventall the programs and functions yourself.Instead,borrow whatever functionalityyou need from whats already installed on your system.Recycle your software,and use its power to suit your needs.How Can I Talk To COM Objects?How do you identify

11、a COM object?COM objects come in two flavorseitherOCXor DLLfiles.To get a taste of how many potentially useful resources arewaiting for you,do a quick search:Open your Start menu,choose Find,anddo a search on files and folders.In the filename box,type in*.DLL*.OCX.Make sure you choose your hard driv

12、e as the search target.Hundreds of fileswill be listed,leaving you wondering which secrets await you inside.OCXfiles are ActiveX controls.They were originally designed to be hosted byWeb pages.DLLfiles are dynamic link libraries.They help to split programs(and Windows itself)into modules.Each DLLfil

13、e stores some functionality,and whenever more is needed,Microsoft and other companies add more DLLs.Both file types may or may not be suitable for scripting.In order for scripts toaccess the functions inside,the file needs to offer a special interface calledIDispatch.In addition,the file needs to be

14、 registered.You will learn moreabout this later in this chapter.COM objects work pretty much like VBScript command extensions.Plugthem in,and you get an extra set of commands.Plug in as many objects asyou need simultaneously.Its really that easy.Connecting to an ObjectYou want proof?Take a look at t

15、he following example.VBScript has no filesystem commands whatsoever,so it would be pretty useless if you wanted todesign your own disk utility.Thats why Microsoft added a special object to86Part I:Scripting KickstartII4684-8 ch03.f.qc 3/3/00 9:31 AM Page 86the scripting host called Scripting.FileSys

16、temObject.Plug it in,and youget all the file system commands you could possibly ask for:3-1.VBS get access to the ActiveX object:set fs=CreateObject(“Scripting.FileSystemObject”)call a method to make the object do something:set drive=fs.GetDrive(“C:”)MsgBox“Available Space on C:”&FormatNumber(drive.

17、AvailableSpace/10242)&“MB”This script determines the free space on drive C:(see Figure 3-1).To be able to do that,the script needs to borrow some functions from Scripting.FileSystemObject.So,the first thing the script does is call for help.It usesCreateObjectto get a reference to the object it wants

18、 to help outScripting.FileSystemObject.Figure 3-1:Find out available space on a drive with the help ofScripting.FileSystemObject.Your scripts will call for help all of the time.Their cries will be answered by many different objects throughout this book,so its a good idea to fullyunderstand this mech

19、anism.CreateObjectreturns a reference to the object.Because this reference is not a regular variable,like a number or a text string,you need to use the key word Setto assign it to a variable.The variable thenacts like the object,and the script above can use the variable fsto accessmethods and proper

20、ties of the new object.Setis a very important key word.VBScript doesnt need it,but you do.UseSetwhenever you want to store an object reference in a variable.Whenever you want to access the inside of the object,you just use yournewly created reference.The script wants to get a hold of a drive,so it c

21、allsGetDrive.GetDriveis part of the Scripting.FileSystemObject;its not a VBScript command.So,in order to call this function,you need to use yourreference stored in fs.This is why the script calls fs.GetDriveinstead ofGetDrive.Your script now has successfully called its first foreign function.GetDriv

22、ereturns another object called IDrive.This object represents the drive with all its technical details.You will see much more about thesefunctions in Chapter 8.Because GetDrivereturns an object,your scriptagain uses Setto store the object reference in a variable.Chapter 3:Kidnapping Objects87II4684-8

23、 ch03.f.qc 3/3/00 9:31 AM Page 87To find out the available space on the drive,the script asks for the driveproperty AvailableSpace.Because this information is stored in the IDriveobject,the script again uses the correct object reference.It asks for drive.AvailableSpace.Either AvailableSpacealone or

24、fs.AvailableSpacewould fail because this property only exists in the IDriveobjectandnowhere else.If youre wondering how to find out which object contains which information,its not black magic;its just a matter of information and documentation.Youwill see in a moment how easy it is to find out which

25、objects are returned andwhat information is contained in them.The FormatNumbercommand just serves cosmetic purposes.It formats theraw number,which is divided by 10242 to get megabytes instead of bytes.Whats all this fuss about“methods,”“properties,”and“functions?”Actually,a method is just a new term

26、 for either“function”or“procedure.”“Method”refers to some built-in mechanics inside an object that does something foryou.Properties,in contrast,are information stores that act like variables.This example provides all you need to know.It shows you all the steps thatare necessary to access an object.A

27、s you see,much of it involves gettingobject references and calling the right object methods.Knowing Which Objects Are AvailableHow did I know there was an object like Scripting.FileSystemObjectanyway?And how can you find out if there are more?Easy.Scripting.FileSystemObjectis part of the scripting h

28、ost,and itsfully documented.If you are curious,just take a look at the books CD andinstall msrelated/vbsdoc.exe.This file contains the official VBScript helpfile,and Scripting.FileSystemObjectis part of it.Its not the only object the WSH brings along,either,as you can see in Table 3-1.Table 3-1COM o

29、bjects included with the Scripting HostObject NameDescriptionScripting.FileSystemObjectA rich set of file system functions.Scripting.DictionaryReturns a dictionary object that stores key-value pairs.WScript.ShellA rich set of functions to read systeminformation:Read and write to the Registry,find ou

30、t path names to special folders,readDOS environment variables,and read thesettings stored in links.88Part I:Scripting KickstartII4684-8 ch03.f.qc 3/3/00 9:31 AM Page 88Object NameDescriptionWScript.NetworkFunctions to manage network connectionsand remote printers:Find out the name of thecurrently lo

31、gged-in user.Wondering why object names often share part of their name with otherobjects?If object names start with the same name like“Scripting”or“Wscript,”they are part of the same physical object file.So,bothScripting.FileSystemObjectand Scripting.Dictionarylive insideSCRRUN.DLL.Consider the firs

32、t part of the object name as the“Companyname”and the second part as the“Department.”All the Scripting Objects live inside SCRRUN.DLL,and all the WScript Objectsare stored inside WSHOM.OCX.You can view both files in the Windows systemfolder.Lets use this new freedom and borrow some external methods t

33、o check bothfiles and find out their file versions(see Figure 3-2).Figure 3-2:Retrieve location and version information of important COM objects.3-2.VBSCheck“wshom.ocx”Check“scrrun.dll”sub Check(filename)if LookFor(filename,path)then if file exists in either system folder,path now contains the pathn

34、ame find out file version:version=GetVersion(path)display resultsmsg=filename&“is stored here:“&path&vbCrmsg=msg+“Version:“&versionMsgBox msg,vbInformationChapter 3:Kidnapping Objects89II4684-8 ch03.f.qc 3/3/00 9:31 AM Page 89elseMsgBox filename&“was not found.”end ifend subfunction LookFor(filename

35、,path)returns true if filename was found in either of the two possible system folders win9x only has one.path returns the full path name we need this object to find out the windows folder using ExpandEnvironmentStrings:set wshshell=CreateObject(“WScript.Shell”)we need this object to find out whether

36、 the file exists:set fs=CreateObject(“Scripting.FileSystemObject”)find out windows folder path:environment variable%WINDIR%contains the windows folder path:windir=wshshell.ExpandEnvironmentStrings(“%WINDIR%”)construct names of both file paths to check:path1=windir&“system”&filenamepath2=windir&“syst

37、em32”&filenameif fs.FileExists(path1)then file exists in path1LookFor=truepath=path1elseif fs.FileExists(path2)then file exists in path2LookFor=truepath=path2else file not found:LookFor=falsepath=“”exit functionend ifend functionfunction GetVersion(path)accepts a filename and returns file version we

38、 need this object to get access to the file version number:set fs=CreateObject(“Scripting.FileSystemObject”)90Part I:Scripting KickstartII4684-8 ch03.f.qc 3/3/00 9:31 AM Page 90 needs to turn off error handling because error will be raised if no file version info is available(fixed in newer WSH vers

39、ions)on error resume nextGetVersion=fs.GetFileVersion(path)file version available?Error raised?if not err.number=0 then clear errorerr.clear set return value to-1GetVersion=-1end ifend functionDont try to understand all the details of this script.Its there for yourconvenience only.Take one step at a

40、 time!Finding Out Where Objects Are StoredHow do you know that WScript.Shelllives inside WSHOM.OCX?You can look itup in the Windows Registry.Its easy to do,and then youll see how importantit is to know the name of a file that stores an object.Later in this chapter,youlluse this information to uncove

41、r all the undocumented commands stored in anobject.Any object name you supply to CreateObjectlike Scripting.FileSystemObjector WScript.Shellis really a ProgID,or programidentifier.You will always find a Registry key in HKEY_CLASSES_ROOTwiththe same name.This is the central store telling CreateObject

42、how to access the object.If the Registry key is missing,you will no longer be able to access the object.Lets do the first step and spy on objects!Find out the real filename ofWScript.Shell.1.Choose Run from the Start menu and launch the Registry Editor:REGEDITEnter.2.In the left pane,youll see all t

43、he keys.Keys work like folders and in factshare the same icon.They can contain subkeys and values,the real data.Values are displayed in the right pane.3.To open a key and look at whats inside,click the plus sign or double-click the key.Open the key HKEY_CLASSES_ROOT.This key stores allinformation ab

44、out file associations and ActiveXobjects.4.Now enter the beginning of the object name you are looking for.EnterWScript.The cursor jumps to the first key that starts with the charactersyou entered.Most likely,it will be WScript.Network(see Figure 3-3).Scroll down a little farther until you see WScrip

45、t.Shell.Chapter 3:Kidnapping Objects91II4684-8 ch03.f.qc 3/3/00 9:31 AM Page 91Figure 3-3:COM objects are registered as individual keys.Once you have accustomed yourself to the Registries architecture,you can“beam”yourself to the right places.Just select the Edit menu and chooseFind.Then,activate th

46、e key option only because you are looking for a key.Enter the name of the key,WScript.Shell,and start the Search.5.Open the key WScript.Shell.In the right pane,youll find the officialname of this object.Youll also discover two subkeys called CLSIDandCurVer(see Figure 3-4).The most important subkey i

47、s called CLSID.Click on it to see its contents in the right pane.The(standard)value contains a very large number,knownas the Class-ID.The reason this number is so large is because its the uniqueidentifier of your object.Its always the same,no matter in which country of the world you installed the cu

48、rrent version of the object.Its a globalnametag.Write down this number somewhereits the official name ofWScript.Shell,and you will need this number soon.The compiler that produced the run-time object generates the Class-ID.Whenever you install the object,the Class-ID is read from the object file and

49、 written to your Registry.So,its a one-way street,and you cant manuallychange the Class-ID by changing Registry values.If you did,you could nolonger access the object because the Registry Class-ID needs to match theClass-ID stored inside the object.The same is true if you update an object file.Becau

50、se the new version has a new Class-ID,you need to register the newobject.Just replacing the file would disable the object.You could no longeraccess it because the Class-IDs inside the Registry and the Class-IDs stored inthe object would be out-of-sync.Registering an object updates the Registry.Becau

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 技术资料 > 其他杂项

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

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