Working with the Windows Registry in WSH

One of the most used procedures in Windows Scripting is reading from and writing to the Windows registry. Today we’re going to learn how WSH makes this a very simple task. I’m going to show you ways to do this natively in WSH by using COM objects and I’m also going to show you how to do this by implementing WMI. So hang on, and let’s see how powerful WSH can be.

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 15
August 29, 2006
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

Introduction

Whether you’re using WSH for system automation or to roll out security policies on several machines, editing the registry will inevitably come up. WSH provides several methods for doing this. We’re going to look in depth at the RegRead, RegWrite, and RegDelete methods and see how to properly implement them in your scripts.

The RegRead, RegWrite, and RegDelete methods belong to the Wscript Shell object. The Shell object is used primarily for reading system information, working with environmental variables, editing the registry, and managing shortcuts. So our first task is to use our script to connect to the Shell object.

Learning the Methods

We create an instance of the shell object by using Wscript’s CreateObject() method. So our first line looks like this:

      Set WshShell = WScript.CreateObject("WScript.Shell")

This creates an instance of the Shell object and assigns it to the WshShell variable.  ext, let’s learn a little about the methods we discussed earlier.

The RegRead method is used to read values stored in the Windows registry. We provide the registry key and value and the RegRead method returns the data assigned to that value. Here is the syntax for the RegRead method:

            object.RegRead Name

Object refers to the variable we’ve assigned to reference the Shell object. In our case, that's WshShell. Name refers to the key, value pair that we are looking for in the registry. When naming registry keys and values in WSH we refer to their hierarchy using the same conventions that we would use to name Windows directory structures. Each of the registry roots can be expressed in full or by using their abbreviated names as shown in the table below.

            Table 1:  Registry Root Naming Conventions

            Abbreviation                 Root Name

            HKCR                         HKEY_CLASSES_ROOT

            HKCU                         HKEY_CURRENT_USER

            HKLM                         HKEY_LOCAL_MACHINE

            HKU                            HKEY_USERS

            HKCC                         HKEY_CURRENT_CONFIG

The RegWrite method is used to write data to a registry value or to create a registry key.  Its syntax is similar to the RegRead method.

            object.RegWrite Name, Value [, Type]

Again, object refers to the variable that we’ve assigned to the Wscript Shell object. Name also refers to the registry key or value that we want to work with.  Now we have a few added parameters. Value refers to the data that we wish to write in to the specified key or value. The type attribute is optional and is used to define the type of value we wish to create or edit. If you do not specify, the default REG_SZ type is used. Valid options are REG_SZ, REG_EXPAND_SZ, REG_DWORD and REG_BINARY. Value is automatically converted to a string for REG_SZ and REG_EXPAND_SZ and to an integer for REG_DWORD or REG_BINARY.

You can differentiate between registry keys and registry values by including the trailing forward slash (\) for key names.

The RegDelete method is used to remove keys or values from the registry. Its syntax is much simpler than RegWrite.  You simply have to specify the key or value to be removed.

object.RegDelete Name \

The syntax for RegDelete is identical to that of RegRead.  Now that we have the tools to do the job, let’s see some examples.

Putting it Together

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.

The WMI Way

So you’re probably wondering about now why we would bother learning another method for working with the registry if WSH provides us with one natively. Well, to put it simply, WMI is much more powerful. You can easily process more than one value at a time, for one, and WMI also let’s us do things that WSH won’t. For instance, try to create a key name “C:\mykey” using the WSH method. You can’t because the WSH method won’t allow you to use the forward slash (\) in a key name. WMI will.

To begin we’ll create an instance of the WMI object and then we will query it.  We’ll need to return to WSH’s CreateObject() method in order to do that.  You’ll notice the use of underscores (_) throughout this code. VBscript allows us to span single lines of code along multiple lines by ending each section with an underscore. I’ve done it here mostly to keep the code neat. You may do the same or leave the entire line intact.

You should also note that WMI values are returned in different ways depending on the value type. In order to be thorough, I will be demonstrating each of these to you so I’ll be jumping around a bit with our example project. Just bear with me and you’ll have no problem following along.

      Const HKEY_LOCAL_MACHINE = &H80000002
      strComputer = "."

We begin our code by assigning a few constants.  We assign the HKEY_LOCAL_MACHINE variable with its WMI hex equivalent. The table below shows those values. We’ve also assigned the variable strComputer to point to the local machine. Just as in DOS, Windows lets us use the period (.) to point to local objects. Any valid computer name would allow this script to run on any remote machine in your network.

Table 2: Hex Codes for Registry Roots in WMI

            Hex Value           Registry Root

            &H80000000     HKEY_CLASSES_ROOT
            &H80000001     HKEY_CURRENT_USER
            &H80000002     HKEY_LOCAL_MACHINE
            &H80000003     HKEY_USERS
            &H80000005     HKEY_CURRENT_CONFIG

In WMI, each of the registry roots are named using a predefined hex value. You can see the complete list of hex values in Table 2.

Set objReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" _
        & strComputer & "\root\default:StdRegProv")

This next piece of code creates an object to reference our WMI connection. This time we use Wscript’s GetOject() method to connect to WMI. In order to do this we have to construct a query. The first piece of our query statement points to Windows Management and set the impersonation level. This is beyond the scope of this article and will be the same in nearly every script you write. The second part of our query states the machine that we wish to send our query to. In our case, strComputer points to the local machine. The final piece of our query tells WMI what information to return. It has two parts separated by a colon (:). The first part is the WMI Root and the second is the WMI Provider.

      strKeyPath = "Software\Microsoft\Windows\CurrentVersion"
      strValue = "ProductID"
      objReg.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValue,strPID
      Wscript.Echo strPID

The final section of code is simple. The strKeyPath and strValue variables are assigned the registry path and value names that we want to find respectively.  Then we use the GetStringValue method to return our WMI query. We finish by using the Echo method to display our results as we did in our first example. The syntax for the GetStringValue method is quite simple.

object.GetStringValue Root, Path, Value, Variable

Root is a variable that contains the hex value for our registry hive. Path is a string value that refers to the registry path where the registry value is located. Value is a string variable that names the value in question. And variable is a string value to which the results will be assigned.

      objReg.DeleteValue HKEY_LOCAL_MACHINE,strKeyPath,strValue
      Wscript.Echo “The registry value has been deleted.”

In order to delete the value, we use the DeleteValue method. Then we use the Echo method to notify the user that the value has been deleted. The DeleteValue method syntax is very similar to the GetStringValue method.

object.DeleteValue Root, Path, Value

Root again refers to the root registry hive. Path refers to the key’s path, and Value refers to the value to be deleted. To delete an entire key we would use the DeleteKey method.

object.DeleteKey Root, Path

object.CreateKey Root, Path

The only required attributes for the DeleteKey method are the Root and Path.  The same syntax is used for the CreateKey method which is used to create new keys in the registry. Next, we’ll learn how to write our value back to the registry.

      objReg.SetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValue,strPID
      Wscript.Echo “The registry value has been written back.”

To write the value back we use the SetStringValue method.  We finish this piece of code by using the Echo method to notify the user that the value has been written back.

object.SetStringValue Root, Path, Value, Variable

The syntax for the SetStringValue is identical to the syntax for the GetStringValue method. You now have all to tools you need for working with String values in WMI. We’ll take a look and our complete code example before learning how to deal with other registry value types.

Const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."
Set objReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" _
        & strComputer & "\root\default:StdRegProv")
strKeyPath = "Software\Microsoft\Windows\CurrentVersion"
strValue = "ProductID"
objReg.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValue,strPID
Wscript.Echo strPID
objReg.DeleteValue HKEY_LOCAL_MACHINE,strKeyPath,strValue
Wscript.Echo "The registry value has been deleted."
objReg.SetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValue,strPID
Wscript.Echo "The registry value has been written back."

Other Value Types

As I’ve mentioned, each registry value type has its own read (Get) and write (Set) method. I’ll show you each of those methods now.  Let’s take a look at their syntax.

object.GetExpandedStringValue Root, Path, Value, Variable

object.SetExpandedStringValue Root, Path, Value, Variable

object.GetMultiStringStringValue Root, Path, Value, Array

object.SetMultiStringValue Root, Path, Value, Array

object.GetDWORDStringValue Root, Path, Value, Integer

object.SetDWORDStringValue Root, Path, Value, Integer

The attributes are the same as we’ve been using except for the following: Array is the variable that refers to an array containing each of the multiple strings in order, and Integer is the variable containing an integer.

Conclusion

You can now read, write, and delete from the registry using either the WSH method or the WMI method depending on your needs. No matter what type of scripts you write, being able to work with the Windows Registry can come in pretty handy at times.

These methods may seem a little tough in the beginning, but try using them a little and you’ll pick up on them in no time at all. I use these methods quite frequently in most of my scripts. These are great techniques when creating scripts for multiple systems. The registry can be used to determine all kinds of useful information such as user names and install directories that may be different from one computer to the next.

So have fun with these techniques. Build your scripts with better compatibility and more power. Until next time, keep coding!

blog comments powered by Disqus
WINDOWS SCRIPTING ARTICLES

- More Windows Scripting Workarounds from Nilpo
- Overloading Methods and More in VBScript
- Improving MFC for Windows Vista
- Regular Expressions in VBScript
- Working with Dates in WMI
- Completing Calendars with VBScript Date Func...
- Building Calendars with VBScript Date Functi...
- Working With Dates and Times in VBScript
- Designing WCF DataContract Classes Using the...
- Understanding Dates and Times in VBScript
- Working With Arrays in VBScript
- Compressed Folders in WSH
- Using .NET Interops in VBScript
- Nilpo`s Scripting Secrets, Vol I
- Database operations using Silverlight 2.0 WC...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 11 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials