《Windows脚本编程核心技术精解Chapter14.pdf》由会员分享,可在线阅读,更多相关《Windows脚本编程核心技术精解Chapter14.pdf(16页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、Chapter 14Getting Access to the RegistryIn This Chapter?Find out why the Registry is so important and how to back up its contents?Find out how the Registry organizes the internal Windows settings intodifferent branches?Use script commands to read and write to the Registry,and learn how tosafely exch
2、ange the registered owner information?Store your own values into the Registry and delete Registry information youno longer need?Enumerate entire Registry branches and list all entries hidden inside a keyThe Windows Registry is the ultimate place to control Windows at a very granular level.Learn how
3、to access and manipulate the Registry by script,and use a custom COM control to add Registry methods not foundin the standard WScript.Shellobject.Getting to Know the RegistryThe Registry is an incredible source of powerits here that Windows stores all its internal settings.You can control many Regis
4、try settingsthrough system dialog boxes,but many more Windows options are hidden and available only through direct Registry access.Lets take a look at the Registrys anatomy first.Then,Ill show you how toback up your Registry.Once you know the Registry better,its safe to usescripts to manipulate Regi
5、stry entries and create your own dialog boxes for any Windows option missing in the official dialog boxes.Where does the Registry live?The Registry actually is a database.Its merely data storage,and itsorganized differently for Windows 9.x and Windows NT/2000.4684-8 ch14.f.qc 3/3/00 9:39 AM Page 407
6、Registry on Windows 9.xOn Windows 9.x systems,the Registry consists of two filesUSER.DATandSYSTEM.DAT.They are stored in the Windows folder and marked as hidden.SYSTEM.DATcontains all common settings,and USER.DATcontains user-related information.If you have set up your Windows 9.x to support multipl
7、e user profiles,theRegistry still uses the central SYSTEM.DAT.For the user information,it usesindividual USER.DATfiles stored in the profiles subfolder.Registry on Windows NT/2000Windows NT/2000 organizes the Registry differently.Here,only users with Administrator or Power User membership have acces
8、s to the files.The common machine-related information is stored in the subfolderSYSTEM32CONFIGand consists of these files:DEFAULTSAMSECURITYSOFTWARESYSTEMThe user-related information is stored in a file called NTUSER.DAT.These files are stored individually in a subfolder called PROFILES/username/.Ac
9、cessing Registry contentYou dont need to care much about the physical location of your Registrydata.All Windows versions come with a special Registry Editor.Just chooseRunfrom your Start menu and enter REGEDIT.Dont change any Registry settings yet.The Registry Editor has direct access to the Registr
10、y,and any changes will be written to your“live”Registryimmediately,without a way to undo the changes.You may easily crash yourentire system or render it useless once you restart.The Registry Editor makes the Registry data visible and uses an Explorer-liketwo-pane view.In the left column,you see the
11、Registry keys.In the right pane,you see the actual data contained in the selected key.Table 14-1 shows how the Registry splits up information into a number of mainkeys,the“handles.”These handles and their subkeys act like file system folders and share thesame icon,too.View Registry keys as informati
12、on folders,and view the datain the right pane as information files.408Part IV:Accessing the Operating SystemII4684-8 ch14.f.qc 3/3/00 9:39 AM Page 408Table 14-1Main Windows Registry KeysMain KeyDescriptionHKEY_LOCAL_MACHINEHardware information and information that applies to allusers.HKEY_CURRENT_US
13、ERUser information for the currently logged-on user.It isactually a shortcut to HKEY_USERSusername.HKEY_USERSAccess to all user information(accesses all availableNTUSER.DAT).On Windows 9.x,you only see yourown user account.defaultrepresents the defaultuser account,which is used as long as nobody has
14、logged on.HKEY_CLASSES_ROOTShortcut to HKEY_CLASSES_ROOTSoftwareClasses.Contains information about registered filetypes and COM objects.HKEY_CURRENT_CONFIGMostly a shortcut into HKEY_LOCAL_MACHINESystemCurrent Control Set.HKEY_DYN_DATADynamic performance data only available on Windows 9.x.The right
15、pane splits information up into a name and a value.The namerepresents an entry while the value represents its content.To stick to the file system analogy,view the name as filename and the value as file content.Each key has at least one name entry:(Standard).Backing up the RegistryBefore you start ex
16、perimenting with the Registry,you should make sure to create a backup.Its your only safety net.If something goes wrong or you accidentally delete the wrong item,you can always restore your backup.Without a backup,you would be lost and would most likely need to reinstallyour complete system.Backing u
17、p the Registry is generally a good idea.Many Windows problemsoccur during software-or hardware-modification.With the help of a currentRegistry backup,you can undo those errors and revitalize your system in a matter of seconds.A Registry backup,therefore,is one of the mostimportant safeguards you can
18、 take advantage of.Backing up on Windows 95On your Windows CD,youll find the folder ERD.Copy it to your hard drive,then launch ERU.EXE.It will create a complete backup of important systemfiles,including the Registry.Dont use disks to store the backupthey aretoo small and wont save the Registry.Inste
19、ad,store the backup somewhereon your hard drive.Chapter 14:Getting Access to the Registry409II4684-8 ch14.f.qc 3/3/00 9:39 AM Page 409To restore the Registry,you must start your computer in DOS mode.Holddown F8 while Windows 95 starts and choose Command Prompt Only fromthe hidden boot menu.Then,navi
20、gate to the folder in which you stored yourbackup using the CD.You cant call your backup set from outside the backup folder.You need tochange the current directory to the backup directory.In your backup folder,call ERD Enter.The backup will be restored.Backing up on Windows 98Windows 98 automaticall
21、y backs up the Registry every day and maintains the last five copies.You can find them in the SYSBCKUPfolder inside yourWindows folder.To restore a backup,start your computer in DOS mode and call SCANREG/RESTORE.Windows checks the current Registry and then offers to restoreone of the five last backu
22、p sets.The Registry will constantly grow in size because deleted entries arent really deleted.They are just marked as“bad.”To re-create your Registry from scratch and discard any unused data,start your computer in DOS mode and use SCANREG/FIX.Backing up on Windows NTOn Windows NT,you can use the RDI
23、SK.EXEutility to create a rudimentaryemergency backup disk.It doesnt contain the complete Registry and willonly restore the most important keys.To create a full Registry backup,use the backup software provided withWindows NT.Make sure to select the option Backup Local Registry to include the Registr
24、y files.You must restore a Registry on the same system that you created the backup.Restoring it on a system with different hardware wont work.The easiest way to recover from Registry problems is the Last Known Goodconfiguration.If you select this option during boot time,Windows NT willautomatically
25、use the last Registry that worked without errors.Backing up on Windows 2000Windows 2000 comes with a sophisticated backup program.It allows you to back up files,folders,and the system-relevant parts.The system backupincludes the Registry.Windows 2000 also includes a Last Known Good configuration you
26、 can use to quickly solve Registry problems.In addition,Windows 2000 sports manyother recovery options organized in its boot menu.Press F8 while Windows2000 offers its boot menu option on-screen.410Part IV:Accessing the Operating SystemII4684-8 ch14.f.qc 3/3/00 9:39 AM Page 410Exporting parts of the
27、 RegistryComplete Registry backups are necessary,but you dont need to back up the entire Registry every time you make changes.A much easier way is toexport part of the Registry.To do this,you select the branch you want tosave in the left Registry Editor pane.Then,you call Export Registry from the Re
28、gistry menu.Now,you can export the selected branch or all of the Registry to a REGfile.REGfiles are plain text filesyou can open them in any text editor to viewthe saved settings.To restore the saved branch,all you need to do is open the REGfile.Itscontent will be merged into the Registry.REGfiles c
29、an only add entries.So,if you have made a backup and then addedkeys to the Registry,merging the backup wont remove the added keys.It willonly restore the backed-up entries.You can even restore REGfiles automatically You call REGEDIT/Sregfilename,for example,by script.Re-creating a Registry from scra
30、tchOn Windows 9.x,you have another option to restore the Registry.If you have exported the entire Registry as REGfile,you can rebuild the Registryusing this file.In DOS mode,enter REGEDIT/C regfilename.Recreating a Registry only works if the REGfile really contains the entirebackup.The/Coption doesn
31、t merge information.Instead,the Registry willbe created based entirely on the information stored in the REGfile.Also,onold Windows 95 systems,due to an error in REGEDIT.EXE,the creationprocess fails.The re-creation process can take many hours.It doesnt have to be that slow,though.If you launch SMART
32、DRVbeforehand,the re-creation process onlytakes minutes.SMARTDRVactivates the old DOS-compliant hard drive cache.Without this cache,file operations in pure DOS mode are incredibly slow.Reading and Writing to the RegistryHow can you access Registry values by script?The WScript.Shellobjectoffers the m
33、ethods needed,which are RegReadand RegWrite.Reading the Registered OwnerWhen you installed Windows,the installer prompted you for your name andorganization.This information is stored inside your Registry,and if you wantto change these entries,all thats needed is a little change to your Registry.Chap
34、ter 14:Getting Access to the Registry411II4684-8 ch14.f.qc 3/3/00 9:39 AM Page 411Figure 14-1:Read the Registered Owner information.Lets first see how to retrieve the information:14-1.VBSset wshshell=CreateObject(“WScript.Shell”)key=“HKLMSoftwareMicrosoftWindowsCurrentVersion”use this key for Win NT
35、/2000 key=“HKLMSoftwareMicrosoftWindows NTCurrentVersion”owner=ReadKey(key&“RegisteredOwner”)org=ReadKey(key&“RegisteredOrganization”)msg=“Registered Owner:“&owner&vbCrmsg=msg&“Organization:“&orgMsgBox msg,vbInformationfunction ReadKey(key)on error resume nextReadKey=wshshell.RegRead(key)if not err.
36、number=0 thenMsgBox“Couldnt open key“”&key&“”:“_&err.descriptionWScript.Quitend ifend functionThe script wraps the RegReadmethod as ReadKeyfunction.Why?BecauseRegReadraises an error if the key you are trying to access is missing or notaccessible.To prevent this,the function turns off error handling
37、and checksfor errors.Windows 9.x and Windows NT/2000 use different Registries.Although theRegistries are not compatible,they have a very similar architecture.In theexample,replace Windows with Windows NT to adjust the script to WindowsNT/2000.You can also use the Windows version-checking methods fro
38、m theprevious chapters to adjust the keys automatically.Changing Registry informationNow that you know where Windows stores the registration info,how can youchange the information?Use RegWrite.412Part IV:Accessing the Operating SystemII4684-8 ch14.f.qc 3/3/00 9:39 AM Page 412 14-2.VBSset wshshell=Cr
39、eateObject(“WScript.Shell”)key=“HKLMSoftwareMicrosoftWindowsCurrentVersion”use this key for Win NT/2000 key=“HKLMSoftwareMicrosoftWindows NTCurrentVersion”ownerkey=key&“RegisteredOwner”orgkey=key&“RegisteredOrganization”owner=ReadKey(ownerkey)org=ReadKey(orgkey)newowner=InputBox(“Change owner inform
40、ation!”,owner)if newowner=vbEmpty then WScript.Quitwshshell.RegWrite ownerkey,newownerneworg=InputBox(“Change organization information!”,org)if neworg=vbEmpty then WScript.Quitwshshell.RegWrite orgkey,neworgMsgBox“Changed information”function ReadKey(key)on error resume nextReadKey=wshshell.RegRead(
41、key)if not err.number=0 thenMsgBox“Couldnt open key“”&key&“”:“_&err.descriptionWScript.Quitend ifend functionThis time,an InputBoxdialog box presents you with the current Registryvalues and allows you to change the information.Right-click My Computer onthe desktop and choose Properties to verify tha
42、t your changes really take effect.Tricks and tips around Registry editsRegReadand RegWriteare both pretty straightforward.However,there are some details you should know:IIf the key you supply ends with a,then RegReadreads the keys(Standard)value,and RegWritewrites the(Standard)value.IIf the key you
43、supply doesnt end with a,then RegReaduses the lastpart of your key as entry name.For example,HKCR.vbswould try toaccess the entry.vbs.This would fail because.vbsis a subkey.Youwould have to access it through HKCR.vbs.IIn general,its best to stick to the file system analogy.If your key endswith a,it
44、represents a“folder”(key).If it doesnt end with a,itrepresents a“file”(an entry in the right Registry Editor pane).Chapter 14:Getting Access to the Registry413II4684-8 ch14.f.qc 3/3/00 9:39 AM Page 413As a default,RegWritecreates new entries as String Value.If you want tocreate entries of different
45、type,add the desired type according to Table 14-2.Table 14-2Registry Variable TypesEntry TypeDescriptionREG_SZString ValueREG_EXPAND_SZString ValueREG_DWORDInteger ValueREG_BINARYInteger ValueTo write a DWORDentry to the Registry,use the following syntax:wshshell.RegWrite key,value,REG_DWORD”.Deleti
46、ng Registry valuesYou can even delete Registry information using RegDelete.For example,you could store your own data in the Registry and delete it on request:14-3.VBSset wshshell=CreateObject(“WScript.Shell”)mykey=“HKCUSoftwaremystoragecounter”read countercounter=ReadKey(mykey)use informationmsg=“Yo
47、u have launched this script“&counter&“times.Reset?”answer=MsgBox(msg,vbYesNo)if answer=vbYes thenwshshell.RegDelete mykeyelse increment countercounter=counter+1 updatewshshell.RegWrite mykey,counter,“REG_DWORD”end iffunction ReadKey(key)on error resume nextReadKey=wshshell.RegRead(key)if not err.num
48、ber=0 thenReadKey=0414Part IV:Accessing the Operating SystemII4684-8 ch14.f.qc 3/3/00 9:39 AM Page 414err.clearend ifend functionThis script uses the Registry as a global data store and maintains a counter.Each time you launch the script,it increments the counter and tells you howoften you have run
49、it.Once you choose to reset,it deletes the counter andstarts over again.Use the key“HKCUSoftware”as the base for your own information keys ifyou want to store them on a per-user basis.Use the key“HKLMSoftware”if you want to store common information.If you changed the script to“HKLMSoftware.”,it woul
50、d count script usage no matter which user launched the script.In all cases,you need the proper permissions to modify the Registry.Note the changes in ReadKeyif the key doesnt exist,the function returns 0,indicating that there is no counter.Note also that deleting the key doesntremove all of your ent