Working with the Windows Registry in WSH - Putting it Together
(Page 2 of 4 )
Let’s put all of this to some real world use. We’re going to build a script that reads some information from the registry, displays it to us, then deletes the value and writes it back. Of course, we wouldn’t perform all of these actions together in a real script. This is just to demonstrate the functionality.
Let’s use our script to read the currently installed product ID. This information can be found in the ProductID value under the following registry key:
HKEY_LOCAL_MACHINE\Software\Windows\CurrentVersion\
We start our script by establishing some variables and creating a call to the Shell object. Then we use our RegRead method to get this information. Our code begins as follows:
strRegValue = “HKLM\Software\Microsoft\Windows\CurrentVersion\
ProductID”
Set WshShell = WScript.CreateObject("WScript.Shell")
strPID = WshShell.RegRead (strRegValue)
Wscript.Echo strPID
Okay, here’s what we’ve done so far. We’ve assigned our registry value to the strRegValue variable. Then we use the CreateObject method to create an instance of the Shell object and assign it to the WshShell variable. Our next line uses the RegRead method to pull the information from the registry and assign it to the strPID variable. As documented, you should be able to use this line without the parenthesis, however, since it returns a value it technically is a function and requires the use of parenthesis. We finish by using the Echo method to return the contents of strPID to the user. Now for our next piece of code.
WshShell.RegDelete strRegValue
Wscript.Echo “The registry value has been deleted.”
This piece of code is simpler. It just deletes our registry value and then tells the user what we’ve done. Next, we have to write it back.
WshShell.RegWrite strRegValue, strPID
Wscript.Echo “The registry value has been written back.”
This part of the code uses the RegWrite method to write our value back into the registry and then uses the Echo method to tell the user when it has been written. The complete code for this example looks like this:
strRegValue = "HKLM\Software\Microsoft\Windows\CurrentVersion\ProductID"
Set WshShell = WScript.CreateObject("WScript.Shell")
strPID = WshShell.RegRead strRegValue
Wscript.Echo strPID
WshShell.RegDelete strRegValue
Wscript.Echo "The registry value has been deleted."
WshShell.RegWrite strRegValue, strPID
Wscript.Echo "The registry value has been written back."
Well, that’s the WSH way, but why stop there? I want to demonstrate all of the ways that WSH can work with the registry. The next way uses WMI, or Windows Management Instrumentation. In short, WMI is a set of features that is used to manage Windows.
Next: The WMI Way >>
More Windows Scripting Articles
More By Nilpo