Developing a Setup Script

In this chapter, you will learn how to read, write, and modify data that is stored in the Windows registry. You will learn about the basic design of the registry and the structure that it uses to store data. You will then apply this information by developing a VBScript that creates a new registry key. The new key will store values containing configuration information for all the VBScripts developed by Molly for execution on the Windows 2000 Professional centralized management workstation.

Working with the Windows Registry

The Windows registry is a built-in database repository for configuration information on all Microsoft operating systems. It has been available since Windows 95. Microsoft and third-party hardware and software vendors use the Windows registry to store information about virtually every aspect of the computer, including the operating system itself.

By changing the contents of the registry, you can administer many aspects of a computer's operation, as well as the operation of its hardware and software. People work with the registry all the time, usually without even knowing. Most of the changes that users make to their desktops are stored in the registry. For example, you can modify the Windows screen saver settings manually from the Windows display dialog box or by making changes directly to the registry.

  Note

To learn more about the registry keys and values involved in managing the Windows screen saver via the registry, refer to Chapter 11, "Customizing the Desktop."

The registry is highly reliable. As a result, most hardware and software developers have migrated data from their INI files into it. Likewise, you can leverage the power and convenience of the registry by using it as a central repository for all your VBScripts' configuration settings.

Examining the Registry Root Keys

The registry is organized into a hierarchical structure that closely resembles that of a file system. At the top of the hierarchy are five root or parent keys, which are also sometimes referred to as hives. Table 22.1 lists each of these root keys and provides a brief description of the types of information that they store.

Table 22.1: Registry Root Keys

Key

Short Name

Description

HKEY_CLASSES_ROOT

HKCR

Stores information regarding Windows file associations

HKEY_CURRENT_USER

HKCU

Stores information related to the user that is currently logged on to the computer

HKEY_LOCAL_MACHINE

HKLM

Stores information regarding global computer settings

HKEY_USERS

Stores information about all of the individuals that share the computer

HKEY_CURRENT_CONFIG

Stores information about the computer's current hardware configuration

Understanding How Data Is Stored

Data located in the registry is stored as values, which represent the name of an element to which data is associated. Values can be likened in many ways to files, which store data on the Windows file system. Values are organized within keys that act as a sort of folder or container. A registry key is a container that stores values or other registry keys. Data is stored in the registry using the following format:

Key : KeyType : Value

Key represents the fully qualified name of a registry key. KeyType specifies the type of data that the key stores. The registry stores a number of different types of data, as shown in Table 22.2. Value specifies the actual data that is to be stored.

Table 22.2: Registry Data Types

Data Type

Description

REG_NONE

Used to store an undefined data type

REG_BINARY

Used to store a binary value

REG_SZ

Used to store a string

REG_EXPAND_SZ

Used to store an expandable string, such as %COMPUTERNAME%

REG_MULTI_SZ

Used to store multiple strings

REG_LINK

A type reserved for use by Microsoft

REG_DWORD

Used to store a 32-bit integer

REG_DWORD_BIG_ENDIAN

Used to store a 32-bit integer in Big Endian format

REG_DWORD_LITTLE_ENDIAN

Used to store a 32-bit integer in Little Endian format

REG_QWORD

Used to store a 64-bit integer

REG_QWORD_LITTLE_ENDIAN

Used to store a 64-bit integer in Little Endian format

REG_RESOURCE_LIST

Used to store a list of device drivers

  Note

Like every file and folder managed by the Windows NTFS file system, every Windows 2000 registry key and value is protected using security permissions. In order to read or modify a registry key or value, you must have the appropriate set of security permissions.

Manually Accessing Registry Data

The data stored in the Windows registry is often modified during the normal operation of the computer, with most people completely unaware that the changes that they are making are actually being stored in the registry. In addition, many of the Windows Control Panel applets, which are used to configure a wide variety of Windows functionality, are actually just user-friendly registry interfaces. The advantages to working with the Control Panel applets are that they hide the complexities of the registry and provide data validation, thus preventing invalid data from being added to the registry.

You may also directly view the contents of the Windows registry using the Regedit utility supplied with all Windows operating systems, demonstrated in Figure 22.1. Using Regedit you can view, add, modify, and delete registry keys and values.

click to expand
Figure 22.1: Examining Windows display settings stored in the registry using the Regedit utility

Figure 22.1 shows the registry's five high-level root keys. The HKEY_CURRENT_CONFIG key has been expanded to display current Windows display settings, all of which are stored as string values (data type REG_SZ).

  Note

If you are using Windows NT, 2000, or XP, then you also have the option of editing the registry using the Regedt32 utility.

  Note

Be extremely careful when directly editing the Windows registry using Regedit or Regedt32. Neither of these utilities provides an undo feature. Accidentally making a mistake when modifying the Windows registry can have potentially catastrophic effects on a computer, even rendering it inoperable. If you are not absolutely sure of the effects of making a particular change to the registry, then do not make it.


Using VBScript and the WSH to Programmatically Modify the Registry

The WSH provides access to the Windows registry via the WshShell object. Using methods belonging to this object, you can create VBScripts that can create, modify, and delete registry keys and values. The registry manipulation methods provided by the WshShell object are listed below.

  • RegWrite(). Creates new registry keys and values or modifies existing registry keys and values
  • RegRead(). Retrieves data stored in registry keys and values
  • RegDelete(). Deletes data stored in registry keys and values
  Note

Note that unlike methods belonging to many WSH objects that support remote resource administration over a network connection, the registry manipulation methods associated with the WshShell object do not provide the ability to administer the Windows registry on remote computers.

Using the RegWrite() Method

In order to work with any of the WshShell object's registry manipulation methods, you must first instantiate the WshShell object within your scripts. Once this is done you may use the RegWrite() method. This method provides the ability to write to the Windows registry. Specifically, it provides the ability to:

  • Create a new registry key
  • Add a value to a registry key and assign data to it
  • Modify an existing value assignment

The RegWrite() method has the following syntax.

ObjectReference.RegWrite(Name, Value [, Type])

ObjectReference is the variable representing an instance of the WshShell object. Name specifies the key or value that is to be created or modified. Value specifies either the name of a new key, the name of a value to be added to an existing key, or the data to be assigned to an existing value. Type is an optional parameter that specifies a string value specifying the data type associated with a value.

When specifying a registry key, the value of Name must end with a backslash character. When specifying a registry value, the backslash character is omitted.

The RegWrite() method will automatically convert the Value parameter to a string or integer. When specified, the Type parameter identifies the data type to be used to store the data. Although the Windows registry is capable of storing numerous types of data, as shown in Table 22.2, the RegWrite() method only supports a subset of these methods, as listed below.

  • REG_SZ
  • REG_EXPAND_SZ
  • REG_DWORD
  • REG_BINARY
  Note

The REG_MULTI_SZ data type is not supported by the RegWrite() method but is supported by the RegRead() method.

In order to use the RegWrite() method, all that you have to do is provide it with the name of a new registry key or value and specify its fully qualified location under one of the registry's five root keys.

  Tip

Every registry key contains one default value, which by default has a data type of REG_NONE. If you wish you may change the data type and data assigned to the default value.

The following example demonstrates how to create a new registry key and value.

Set WshShl = WScript.CreateObject("WScript.Shell")
WshShl.RegWrite "HKCUTestKeyEventLogging", "Enabled"

When executed, this example creates the key HKCUTestKey and adds a new value called EventLogging, which is then assigned the string "Enabled", as shown in Figure 22.2.

click to expand
Figure 22.2: Examining the new registry key and value

You can use the RegWrite() method to modify an existing registry key or value, as demonstrated below.

Set WshShl = WScript.CreateObject("WScript.Shell")
WshShl.RegWrite "HKCUTestKeyEventLogging", "Disabled"

In this example, the data assigned to the EventLogging value is set equal to Disabled. You can also change a key's default value, as demonstrated below.

Set WshShl = WScript.CreateObject("WScript.Shell")
WshShl.RegWrite "HKCUTestKey", "Author: Jerry Ford", "REG_SZ"

Note that in this example, no value name was supplied. As a result, the method assigned "Author: Jerry Ford" to the key's default value. The example also explicitly defined the value's data type as REG_SZ.

You may store any number of registry values under a single registry key. For example, the following VBScript statements can be used to store two additional values under the HKCUTestKey.

Set WshShl = WScript.CreateObject("WScript.Shell")
WshShl.RegWrite "HKCUTestKeyDebugMode", "Disabled"
WshShl.RegWrite "HKCUTestKeyNetworkNotification", "Enabled"

Figure 22.3 shows the status of the TestKey key and its associated values after running the previous example.

click to expand
Figure 22.3: Examining the new values assigned to the registry key

Using the RegRead() Method

Once you have added new registry keys and values, you can programmatically retrieve them using the WshShell object's RegRead() method. This method has the following syntax:

ObjectReference.RegRead(Name)

ObjectReference is the variable representing an instance of the WshShell object. Name specifies the key or value that is to be retrieved.

The RegRead() method can be used to retrieve any of the following data types from the Windows registry:

  • REG_BINARY
  • REG_DWORD
  • REG_EXPAND_SZ
  • REG_MULTI_SZ
  • REG_SZ

The following example demonstrates how to retrieve and display one of the registry values created by the previous examples.

Set WshShl = WScript.CreateObject("WScript.Shell")
strResult = WshShl.RegRead("HKCUTestKeyEventLogging")
MsgBox strResult

Figure 22.4 shows the output displayed by this example.

click to expand
Figure 22.4: Using RegRead() to retrieve the data from the registry

If you perform a RegRead() operation and specify the name of a registry key instead of a value, then the method will return the default value assigned to the registry key, as demonstrated below.

Set WshShl = WScript.CreateObject("WScript.Shell")
strResult = WshShl.RegRead("HKCUTestKey")
MsgBox strResult

Using the RegDelete() Method

To delete a registry key or value, you will need to learn how to use the RegDelete() method. This method has the following syntax:

ObjectReference.RegDelete(Name)

ObjectReference is the variable representing an instance of the WshShell object. Name specifies the key or value that is to be deleted. If you specify a registry value, then that value is deleted. However, if you specify a key, the key and all values or subkeys stored underneath it are deleted.

The following example demonstrates how to delete a registry value.

Set WshShl = WScript.CreateObject("WScript.Shell")
WshShl.RegDelete "HKCUTestKeyEventLogging"

Similarly, you can delete an entire key (along with all its subkeys and values) by specifying the fully qualified key name followed by the backslash character, as demonstrated below.

Set WshShl = WScript.CreateObject("WScript.Shell")
WshShl.RegDelete "HKCUTestKey"

Guarding against Registry Errors

If you specify a registry key or value that does not exist when using the RegRead() method, an error will occur, as demonstrated in Figure 22.5.

click to expand
Figure 22.5: An example of an error generated when a VBScript attempts to read a value that does not exist

To prevent an error from terminating your script's execution, you can use the On Error Resume Next statement and then add logic to recover from the error.

For example, the following procedure demonstrates how to use the Err object to determine whether the execution of the RegRead() method was successful.

On Error Resume Next

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

strResult = WshShl.RegRead("HKCUTestKeyEventLogging")

If Err <> 0 Then
 MsgBox "Add logic to proceed with a default setting and to log an event " & _
 "log message."
End If

If the RegRead() method is executed successfully, the example will silently end. However, if an error occurs (for example, the value does not exist), an error message is displayed.

  Note

For more information on how to work with the On Error Resume Next statement and the Err object, refer to Chapter 6, "Data Collection, Notification, and Error Reporting."

The next example expands on the previous one. It demonstrates how to create a function in a VBScript that can be used to verify that a registry key or value exists before your script attempts to access its contents.

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

strRegKey = "HKCUTestKeyEventLogging"

If RegKeyExists(strRegKey) = True Then
 strEvtLogStatus = WshShl.RegRead(strRegKey)
Else
 strEvtLogStatus = "Disabled"
 WshShl.LogEvent 4, "HKCUTestKeyEventLogging not found - proceeding with " & _
 "default setting."
End If

Function RegKeyExists(RegKey)

 Dim strKeyToTest
 RegKeyExists = True

 On Error Resume Next

 strKeyToTest = WshShl.RegRead(RegKey)

 If Err <> 0 Then
 RegKeyExists = False
 End If

End Function

This example begins by instantiating the WshShell object. Then a variable named strRegKey is set equal to HKCUTestKeyEventLogging. Next an If statement executes a function called RegKeyExists() and passes it the value of strRegKey. This function determines whether the registry key exists. If it does exist, a value of True is returned from the function and the value of a variable called strEvtLogStatus is set equal to the registry value by executing the RegRead() method. If the function does not return a value of True, then the value of strEvtLogStatus is set equal to a default setting. This allows the script to continue executing. An informational message is also written to the Windows application event log, as demonstrated in Figure 22.6.

click to expand
Figure 22.6: Examining the format of the message written to the Windows application event log when an error occurs in the script

The RegKeyExist() function accepts a single argument, the name of a registry key or value. It begins by defining a variable called strKeyToTest. Next it assigns a variable, named after the function, a default value of True.

  Note

Functions return a result to their calling statements by assigning the value to be returned to a variable that has the same name as the function.

Next the On Error Resume Next statement is executed. By placing this statement inside the function, its scope is limited to the function. The next statement takes the strKeyToTest variable and assigns it the value returned by the RegRead() method. Then the default property of the Err object property is checked to determine whether an error occurred (whether the key or value exists). If an error did occur, then the value of RegKeyExists is set equal to False. If an error did not occur, then the value of RegKeyExists will remain True as set at the beginning of the function.


Creating the Setup Script

Molly is now ready to begin work on writing the first script for her new project. This VBScript setup script will be responsible for the one-time setup of registry entries to be used by the other scripts in her project. Specifically, this script will create a new registry key called HKLMSoftwareIntuitVBScriptsMstSumRpts. In addition, it will create eight registry values located under that key. These values, as well as a description of their purpose and their initial settings, are listed in Table 22.3.

Table 22.3: VBScript Project Registry Keys and Values

Key

Description

Value

EventLogging

A flag indicating whether events should be written to the Windows application event log

Enabled

DebugMode

A flag indicating whether intermediate results should be displayed in pop-up dialog boxes during script execution

Disabled

NetworkNotification

A flag indicating whether network pop-up messages should be sent

Enabled

NtkNotifyList ASCK001

A list of user accounts to whom network pop-up messages should be sent

MJLF001

Win2000Svrs SERV0002

Names of the Windows 2000 servers where the order/inventory application is deployed

SERV0001

SharedFolder

The name assigned to the shared folder on the Windows 2000 servers where the summary reports are stored

SumReports

RptArchive

The name of the folder on the Windows 2000 Professional workstation where the consolidated summary reports are to be stored

d:Order_InventoryLogFiles

RptFormat

A value of either Text or Word, indicating the file type of the consolidated summary report

Text

  Tip

Molly can also use this script to reinitialize the registry values used by this project to their initial settings. In addition, by changing data that is associated with each setting in the script, she can reuse the script to later modify these values, thus saving herself the trouble of manually editing the registry.

The Initialization Section

The script's Initialization Section, shown below, consists of just three statements. The first statement turns on the strict enforcement of variable naming. The second statement defines a variable for the WshShell object and a second variable that will be used in the Main Processing Section to determine if the script has permission to run. The last statement in this section initializes the WshShell object.

Option Explicit

Dim WshShl, IntResponse

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

The Main Processing Section

The Main Processing Section, shown below, begins by calling the GetPermissionToRun() function. It then uses an If statement to interrogate the value returned by this function to determine whether it is equal to 6 (that is, Molly clicked on Yes when prompted to allow the script to continue its execution).

If permission is given to execute, the script next calls the CreateRegistryEntries() subroutine eight times, passing it the name of a registry value and the data assigned to it. Since the HKLMSoftwareIntuitVBScriptsMstSumRpts key will not exist on the first call to the CreateRegistryEntries() subroutine, both the key and the stated value will be created. The remaining function calls will then store additional values under that key. Once all of the keys have been created, the script terminates its execution using the WScript object's Quit() method.

intResponse = GetPermissionToRun()

If intResponse = 6 Then
 CreateRegistryEntries
 "HKLMSoftwareIntuitVBScriptsMstSumRptsEventLogging", "Enabled"
 CreateRegistryEntries
 "HKLMSoftwareIntuitVBScriptsMstSumRptsDebugMode", "Disabled"
 CreateRegistryEntries
 "HKLMSoftwareIntuitVBScriptsMstSumRptsNetworkNotification", "Enabled"
 CreateRegistryEntries
 "HKLMSoftwareIntuitVBScriptsMstSumRptsNtkNotifiyList", "MJLF001
 ASCK001"
 CreateRegistryEntries
 "HKLMSoftwareIntuitVBScriptsMstSumRptsWin2000Svrs",
 "SERV0001 SERV0002"
 CreateRegistryEntries
 "HKLMSoftwareIntuitVBScriptsMstSumRptsSharedFolder", "SumReports"
 CreateRegistryEntries
 "HKLMSoftwareIntuitVBScriptsMstSumRptsRptArchive",
 "d:Order_InventoryLogFiles"
 CreateRegistryEntries
 "HKLMSoftwareIntuitVBScriptsMstSumRptsRptFormat", "Text"
End If

WScript.Quit()

The GetPermissionToRun() Function

The GetPermissionToRun() function uses the built-in VBScript MsgBox() function to display a prompt that gets confirmation before allowing the script to proceed further. If the Yes button is clicked, a value of 6 is returned to the calling statement. If the No button is clicked, a value of 7 is returned instead.

Function GetPermissionToRun()
 GetPermissionToRun = MsgBox("This script creates registry keys and " &_
 "values for the VBScripts that run on the Windows 2000 " & _
 "Professional centralized management workstation." & vbCrLf & vbCrLf & _
 "Do you wish to continue?", 4)

End Function

The CreateRegistryEntries() Subroutine

The CreateRegistryEntries() subroutine, shown below, accepts two input arguments. Key_Value stores the name of the registry key or value to be created and Data contains the actual data to be assigned. The On Error Resume Next statement is the first statement in the subroutine. It was added to allow the subroutine to continue executing if an error occurs when creating an individual registry key or value. Next the WshShell object's RegWrite() method is used to create the new key or value. Then the Err object's default property (the Err.Number) is checked to see if the write operation was successful. The MsgBox() function is used to display a confirmation stating whether the key was created or an error occurred.

Sub CreateRegistryEntries(Key_Value, Data)

 On Error Resume Next

 WshShl.RegWrite Key_Value, Data

 If Err <> 0 Then
 MsgBox "Error occurred writing " & Key_Value
 Else
 MsgBox Key_Value & " Created successfully."
 End If

End Sub

The Fully Assembled Script

The fully assembled VBScript is shown below. Once executed, it will create registry entries for the rest of the scripts that Molly needs to develop for this new project.

'*************************************************************************
'Script Name: Script 22.1.vbs
'Author: Jerry Ford
'Created: 04/05/03
'Description: This is the setup script for the Windows 2000 Professional
'centralized management workstation. It creates a registry key and assigns
'it a number of values which will be used by the VBScripts that run
'this computer.
'*************************************************************************

'Initialization Section

Option Explicit

Dim WshShl, IntResponse

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


'Main Processing Section

intResponse = GetPermissionToRun()

If intResponse = 6 Then
 CreateRegistryEntries
 "HKLMSoftwareIntuitVBScriptsMstSumRptsEventLogging", "Enabled"
 CreateRegistryEntries
 "HKLMSoftwareIntuitVBScriptsMstSumRptsDebugMode", "Disabled"
 CreateRegistryEntries
 "HKLMSoftwareIntuitVBScriptsMstSumRptsNetworkNotification", "Enabled"
 CreateRegistryEntries
 "HKLMSoftwareIntuitVBScriptsMstSumRptsNtkNotifiyList", "MJLF001
 ASCK001"
 CreateRegistryEntries
 "HKLMSoftwareIntuitVBScriptsMstSumRptsWin2000Svrs",
 "SERV0001 SERV0002"
 CreateRegistryEntries
 "HKLMSoftwareIntuitVBScriptsMstSumRptsSharedFolder", "SumReports"
 CreateRegistryEntries
 "HKLMSoftwareIntuitVBScriptsMstSumRptsRptArchive",
 "d:Order_InventoryLogFiles"
 CreateRegistryEntries
 "HKLMSoftwareIntuitVBScriptsMstSumRptsRptFormat", "Text"
 End If

WScript.Quit()


'Procedure Section

Function GetPermissionToRun()

 GetPermissionToRun = MsgBox("This script creates registry keys and " & _
 "values for the VBScripts that run on the Windows 2000 Professional " & _
 "centralized management workstation." & vbCrLf & vbCrLf & _
 "Do you wish to continue?", 4)

End Function

Sub CreateRegistryEntries(Key_Value, Data)

 On Error Resume Next

 WshShl.RegWrite Key_Value, Data

 If Err <> 0 Then
 MsgBox "Error occurred writing " & Key_Value
 Else
 MsgBox Key_Value & " Created successfully."
 End If

End Sub

Figure 22.7 shows how the new HKLMSoftwareIntuitVBScriptsMstRumRpts key and its assigned values appear when viewed using the Regedit utility.

click to expand
Figure 22.7: Examining the registry key and values created by the setup script


Summary

In this chapter, you learned how to work with the WshShell object's RegRead(), RegWrite(), and RegDelete() methods. You also learned about the registry's basic design and the types of data that it stores. You observed as Molly developed a VBScript that automated the setup of a registry key that stored multiple values. The values were then assigned data representing configuration settings that will be used by the VBScripts executing on the Windows 2000 Professional centralized management workstation.






Microsoft VBScript Professional Projects
Microsoft VBScript Professional Projects
ISBN: 1592000568
EAN: 2147483647
Year: 2005
Pages: 366
Simiral book on Amazon

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