9.3 Accessing the Registry from Scripts

The following code is used to write, read, and delete information in the Registry. Include the following three routines in your script:

Sub RegistryWrite(KeyName, ValueName, ValueData, ValueType)   ValueType = UCase(ValueType)   If ValueType <> "REG_DWORD" and ValueType <> "REG_BINARY" Then _                                                    ValueType = "REG_SZ"   Set WshShell = WScript.CreateObject("WScript.Shell")   WshShell.RegWrite KeyName & "\" & ValueName, ValueData, ValueType End Sub Function RegistryRead(KeyName, ValueName)   Set WshShell = WScript.CreateObject("WScript.Shell")   RegistryRead = WSHShell.RegRead(KeyName & "\" & ValueName) End Function Sub RegistryDelete(KeyName, ValueName)   Set WshShell = WScript.CreateObject("WScript.Shell")   WshShell.RegWrite KeyName & "\" & ValueName, ""   WshShell.RegDelete KeyName & "\" & ValueName End Sub

Using these three routines, you can accomplish nearly all Registry tasks. To create a Registry key, type this (note that all HKEY... roots must appear in uppercase):

Call RegistryWrite("HKEY_LOCAL_MACHINE\Software\My Key", "", "", "")

To assign data to a Registry value:

Call RegistryWrite("HKEY_LOCAL_MACHINE\Software\My Key", "My Value", _                                                     "Some Data", "")

Leave "My Value" blank to set the (default) value. To read the data stored in a given value:

Variable = RegistryRead("HKEY_LOCAL_MACHINE\Software\My Key", "My Value")

Leave "My Value" blank to read the (default) value. To delete a key:

Call RegistryDelete("HKEY_LOCAL_MACHINE\Software\My Key", "")

To delete a value:

Call RegistryDelete("HKEY_LOCAL_MACHINE\Software\My Key", "My Value")

To delete the (default) value in a key, we just set the value to nothing:

Call RegistryWrite("HKEY_LOCAL_MACHINE\Software\My Key", "", "", "")

You'll notice that, in the RegistryDelete subroutine, there's a RegWrite statement. This is necessary to ensure that the key or value that you're trying to delete actually exists. If you don't include this statement and try to delete a nonexistent key or value from the Registry, the Windows Script Host will give an error to the effect that "The system cannot find the file specified." (A helpful Microsoft error message, as always.) This way, the subroutine will create the key or value entry to be deleted if it doesn't already exist.

 

As part of a security/safety feature present in Windows XP (and Windows 2000), you won't be able to delete a key that contains subkeys (this is not true of Windows 9x/Me) using the RegistryDelete routine. See Section 3.2.1 in Chapter 3 for a workaround using Registry patch files.

See Chapter 3 for more information on Registry keys and values.

 



Windows XP Annoyances
Fixing Windows XP Annoyances
ISBN: 0596100531
EAN: 2147483647
Year: 2005
Pages: 78
Authors: David A. Karp

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net