Previous Page
Next Page

Writing to the Registry

I don't know about you, but I've always thought that writing to the registry would be really difficult. However, using the appropriate method of the StdRegProv WMI class makes it as easy as eating pineapple on the beach in Kauai, Hawaiionce you sink your teeth into it, it's sweet. In the script WriteToRegKey.vbs, you use the SetStringValue method to write information into a key called bookReviews that is stored under the SOFTWARE\EdWilson\VBScriptBook subkey. When you execute the script, the key bookReviews does not exist. One nice aspect of SetStringValue is that it will create a key and set the value in one operation. Once you write your data, which is contained in a variable called strData, to the key, you use GetStringValue to read the information you just wrote. The syntax of SetStringValue needs several arguments: the registry tree (in this case, HKLM); the registry key path (held in strKeyPath); the registry key to modify (held in strNamedValue); and the data to write (held in strData).

To verify that your changes were made as expected, use GetStringValue to retrieve the data you just wrote to the registry. GetStringValue works much like SetStringValue except that the last argument is the variable name you want to use to hold the data returned from the registry. With SetStringValue, the fourth argument is the variable that holds the data you want to write to the registry. With GetStringValue, the fourth argument is the variable that will hold the data once you read it from the registry. Everything else about the two commands is the same.

WriteToRegKey.vbs

Option Explicit
On Error Resume Next
Dim strKeyPath 'the portion of registry
Dim strComputer 'the target computer
Dim objReg 'holds connection to registry provider
Dim subKey 'used to enumerate thought the array
Dim arrSubKeys 'holds the subkeys
Dim ParentKey
Dim strNamedValue
Dim strData
Dim strReturnValue
Const HKCR = &H80000000 'HKEY_CLASSES_ROOT
Const HKCU = &H80000001 'HKEY_CURRENT_USER
Const HKLM = &H80000002 'HKEY_LOCAL_MACHINE
Const HKU = &H80000003 'HKEY_USERS
Const HKCC = &H80000005 'HKEY_CURRENT_CONFIG

ParentKey = "SOFTWARE\EdWilson"
strKeyPath = "SOFTWARE\EdWilson\VBScriptBook"
strNamedvalue = "book reviews"
strData = "Awesome"

strComputer = "."

Set objReg = GetObject("winmgmts:\\" & _
  strComputer & "\root\default:StdRegProv")


objReg.SetStringValue HKLM, strKeyPath, strNamedValue, strData

WScript.Echo("value set")

objReg.GetStringValue HKLM, strKeyPath, strNamedValue, strReturnValue

WScript.Echo strNamedValue & " contains " & strReturnValue


Previous Page
Next Page