Windows Script Host Object Model

As everything in modern Microsoft operating systems, WSH is object-oriented. The Windows Script Host object model consists of 14 objects. The root object is the WScript object.

The Windows Script Host object model provides a logical, systematic way to perform many administrative tasks. The set of COM interfaces it provides can be placed into two main categories:

  • Script Execution and Troubleshooting. This set of interfaces allows scripts to perform basic manipulation of the Windows Script Host, output messages to the screen, and perform basic COM functions such as CreateObject and GetObject.

  • Helper Functions. Helper functions are properties and methods for performing actions such as mapping network drives, connecting to printers, retrieving and modifying environment variables, and manipulating registry keys. Administrators can also use the Windows Script Host helper functions to create simple logon scripts.

Note 

For purposes of accessing the registry, the most important object is WshShell, which will be discussed in the next section.

WshShell Object

Provides access to the native Windows shell. The WshShell object is a child object of the WScript object—you must use the WScript method CreateScript to create a WshShell object (i.e., WScript.CreateObject ("WScript.Shell")). You create a WshShell object whenever you want to run a program locally, manipulate the contents of the registry, create a shortcut, or access a system folder. The WshShell object provides the Environment collection. This collection allows you to handle environmental variables (such as WINDIR, PATH, or PROMPT).

RegRead Method

The RegRead method returns the value of a key or value name from the registry. This method uses the following syntax:

 Object.RegRead (strName) 

where:

ObjectWshShell object

strName—string value indicating the key or value-name whose value you want

The RegRead method can return the values of the following data types: REG_SZ, REG_DWORD, REG_BINARY, REG_EXPAND_SZ, and REG_MULTI_SZ.

You can specify a key name by ending strName with a final backslash. Do not include a final backslash to specify a value name. A value entry has three parts: its name, its data type, and its value. When you specify a key name (as opposed to a value name), RegRead returns the default value. To read a key's default value, specify the name of the key itself. Fully qualified key names and value names begin with a root key. You must use abbreviated versions of root key names with the RegRead method. The five possible root keys are listed in Table 14.2.

Table 14.2: Abbreviations for the Registry Root Key Names

Root Key Name

Abbreviation


HKEY_CURRENT_USER

HKCU

HKEY_LOCAL_MACHINE

HKLM

HKEY_CLASSES_ROOT

HKCR

HKEY_USERS

HKEY_USERS

HKEY_CURRENT_CONFIG

HKEY_CURRENT_CONFIG

RegWrite Method

The RegWrite Method creates a new key, adds another value to an existing key (and assigns it a value), or changes the value of an existing value name. This method uses the following syntax:

 Object.RegWrite (strName, anyValue [,strType]) 

where:

ObjectWshShell object

strName—string value indicating the key name, value name, or value you want to create, add, or change

anyValue—the name of the new key you want to create, the name of the value you want to add to an existing key, or the new value you want to assign to an existing value name

strType—optional. String value indicating the value's data type

Specify a key name by ending strName with a final backslash. Do not include a final backslash to specify a value name. The RegWrite method automatically converts the parameter anyValue to either a string or an integer. The value of strType determines its data type (either a string or an integer). The options for strType are listed in Table 14.3.

Table 14.3: Acceptable Values of the strType Argument for the RegWrite Method

Converted to

strType


string

REG_SZ

string

REG_EXPAND_SZ

integer

REG_DWORD

string

REG_BINARY

Note 

The REG_MULTI_SZ type is not supported for the RegWrite method.

Fully qualified key names and value names are prefixed with a root key. You must use abbreviated versions of root key names (if one exists) with the RegWrite method. Abbreviated names of the registry root keys used by the RegWrite method are the same as those for the RegRead method.

RegDelete Method

The RegDelete method is used to delete a registry key or one of its values from the registry. This method uses the following syntax:

 Object.RegDelete (strName) 

where:

ObjectWshShell object

strName—string value indicating the name of the registry key or key value you want to delete

Specify a key-name by ending strName with a final backslash; leave it off to specify a value name. Fully qualified key names and value names are prefixed with a root key. You must use abbreviated versions of root key names (if one exists) with the RegDelete method. There are five possible root keys you can use; they are the same as for the RegRead and RegWrite methods.

JScript Example

A simple example written in JavaScript (JScript in Microsoft's implementation), illustrating the usage of these methods is provided in Listing 1. This code creates a registry key HKEY_CURRENT_USER\Software\MyCoolSoftware, sets its Default value (REG_BINARY data type) to 1, then creates just another REG_SZ value entry under this key and assigns it the "This is a test!" string value.

Listing 14.1. JScript Example Illustrating Registry Access

start example
    // The simplest example illustrating registry access using JScript    // Use this module at your own risk // Setting variables var vbOKCancel = 1; var vbInformation = 64; var vbCancel = 2; var result; // Creating wshShell object var WshShell = WScript.CreateObject ("WScript.Shell"); { // prompting the user    result = WshShell.Popup ("Do you want to create a new registry setting?",                               0,                             "Registry Access using JScript",                             vbOKCancel + vbInformation);    if (result != vbCancel)    {    WshShell.RegWrite ("HKCU\\Software\\MyCoolSoftware\\", 1, "REG_BINARY");    WshShell.RegWrite ("HKCU\\Software\\MyCoolSoftware\\MySuperProgram",                       "This is a test!", "REG_SZ");    var bKey = WshShell.RegRead ("HKCU\\Software\\MyCoolSoftware\\");    WScript.Echo (WshShell.RegRead ("HKCU\\Software\\MyCoolSoftware\\MySuperProgram"));    } //prompting the user result = WshShell.Popup ("Do you want to delete newly created settings?",                          0,                          "Registry Access using JScript",                          vbOKCancel + vbInformation);     if (result != vbCancel)    {    WshShell.RegDelete ("HKCU\\Software\\MyCoolSoftware\\MySuperProgram");    WshShell.RegDelete ("HKCU\\Software\\MyCoolSoftware\\");    } } 
end example

To test this script, enter the code provided in this listing using any text editor (for example, Notepad.exe), and save the file with the JS filename extension. If you double-click this file WSH server will start and execute the script. Notice that this script prompts the user to confirm adding new registry entries (Fig. 14.2), displays the contents of the newly created registry entry (Fig. 14.3) and then asks the user if the newly created registry key and value entry contained within it should be deleted (Fig. 14.4).

click to expand
Fig. 14.2: The dialog prompting the user to confirm creating of a new registry setting


Fig. 14.3: Displaying the contents of the newly created registry entry

click to expand
Fig. 14.4: The dialog prompting the user to confirm deletion of the newly created registry setting(s)

These dialog boxes allow the user to check modifications introduced to the registry at each step, using, for example, Registry Editor (Fig. 14.5).

click to expand
Fig. 14.5: You can use Registry Editor to check modifications introduced to the registry at each step of the script

VBScript Examples

If you prefer VBScript, you can also use the above-described methods for accessing the registry (notice the difference in the syntax of JScript and VBScript).

Enabling and Disabling Changes to the Start Menu

A small example is provided below, developed using VBScript, which, in contrast to the previous one, does something useful—it enables or disables changes to the Start Menu.

In the previous chapter, we discussed the values that control the Start menu. One such value is the NoChangeStartMenu under HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer. When this value is set to 1, one cannot make changes, and when this value is set to 0, changes are allowed. Our small VBScript example reads the NoChangeStartMenu value from the registry, displays the Start menu status, and prompts the user if he wants to enable (Fig. 14.6) or disable (Fig. 14.7) changes to the Start menu.

click to expand
Fig. 14.6: Prompt for the user to unlock Start menu

click to expand
Fig. 14.7: Prompt for the user to lock Start menu

The source code for this example is provided in listing 14.2.

Listing 14.2. Source Code for the VBScript Example that Enables or Disables Changes to the Start Menu

start example
 ' Code for enabling and disabling Start menu changes Option Explicit Dim WSHShell, RegKey, NoChangeStartMenu, Result Set WSHShell = CreateObject ("WScript.Shell") RegKey = "HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\" NoChangeStartMenu = WSHShell.RegRead (regkey & "NoChangeStartMenu") If NoChangeStartMenu = 1 Then 'Changes in Start Menu are prohibited    Result = MsgBox ("Your Start Menu is currently locked." & _         vbNewLine & "Would you like to unlock?", 36)    If Result = 6 Then 'clicked yes       WSHShell.RegWrite regkey & "NoChangeStartMenu", 0    End If Else 'Start Menu can be changed   Result = MsgBox ("You can change start menu." & _        vbNewLine & "Would you like to prohibit changes?", 36)   If Result = 6 Then 'clicked yes      WSHShell.RegWrite regkey & "NoChangeStartMenu", 1   End If End If 'End code 
end example

Enabling and Disabling System Restore

The example presented in this section illustrates how you can use Windows Management Instrumentation to automate your work with the System Restore feature.

Before we proceed any further, let us provide a brief description of WMI scripting capabilities utilization. WMI scripting is a library of automation interfaces. COM-Compliant scripting languages use these automation interfaces to access WMI infrastructure. All WMI automation objects, methods and properties are implemented by the Wbemdisp.dll file.

Note 

To run WMI, you must have administrator privileges.

To access WMI through WMI scripting library, you need to perform three basic steps, which are common to most WMI scripts:

  1. Connect to the Windows Management service.

  2. Retrieve instances of WMI managed objects.

  3. Call a method or access a managed object's property.

Note 

To learn more about powerful WMI scripting capabilities, see the Microsoft Windows 2000 Professional Resource Kit or Microsoft Windows 2000 Server Resource Kit, where you can find more than 50 WMI-based scripts, enabling you to manage everything on the target computer, from boot configuration to user accounts.

The example in Listing 14.3 automates the task of enabling or disabling System Restore on the specified drive. When it is begun, this code creates WshShell object, then requests user input, prompting the user if it is required to enable or disable System Restore (Fig. 14.8). To proceed further, the user must enter an appropriate text string (enable or disable) into the text field at the bottom of this dialog and click OK.

click to expand
Fig. 14.8: Dialog box prompting the user to specify whether System Restore must be enabled or disabled

Listing 14.3. VBScript Code for Enabling/Disabling System Restore on the Specified Drive

start example
 ' Begin code for enabling or disabling System Restore Option Explicit Dim WSHShell, onoff, drive, SRP, eSRP, Result 'Creating WSHShell object Set WSHShell = CreateObject ("WScript.Shell") 'Requesting user input onoff = inputbox ("Do you want to enable or disable System Restore?", "System Restore") Drive = inputbox ("Which Drive would you like to take action on? Must type in format 'c:\"', "Drive to enable/disable") 'using WMI moniker and SystemRestore class to access WMI set SRP = GetObject ("winmgmts:\\.\root\default:SystemRestore") If onoff ="enable" then eSRP = SRP.enable (drive) Result = MsgBox ("System Restore is currently" & _         vbNewLine & "enabled on the following drive: " & Drive, 64) end if If onoff = "disable" then eSRP = SRP.disable (drive) Result = MsgBox ("System Restore is currently" & _          vbNewLine & "disabled on the following drive: " & Drive, 64) end if ' End code 
end example

Next, the script prompts the user to specify the drive, on which it is necessary to take the specified action (Fig. 14.9). Specify the drive using the following format: <drive_letter>:\, for example, C:\.

click to expand
Fig. 14.9: Dialog box prompting the user to specify the drive on which the specified action must be taken

The script runs and performs the specified action on the specified drive. After it is done, it displays a message box, informing the user of the result (Fig. 14.10). To make sure that the specified action was performed successfully, start the System applet in the Control Panel, go to the System Restore tab, and check if System Restore is actually turned off for the specified drive (Fig. 14.11).

click to expand
Fig. 14.10: The message box informing the user of the result of the operation

click to expand
Fig. 14.11: Use the System Restore UI to check if System Restore is actually turned off for the drive you have specified when running the script

Now let us consider the code that implements this series of actions (Listing 14.3).

As was already mentioned, to use WMI scripting the code must connect to the Windows Management service, retrieve instances of the WMI-managed objects, and then call a method or access a managed object's property. In the example presented below, we connect to WMI using the WMI's moniker named Winmgmts and SystemRestore class.

Note 

A moniker is a standard COM mechanism for binding to a COM object. Detailed information on the WMI moniker syntax can be found at the following address: http://msdn.microsoft.com/library/psdk/wmisdk/scintro_6tpv.htm.

Creating Restore Point Automatically

What else can we do with WMI and System Restore? Well, let us try to create a restore point automatically. Now, since we have already created several scripts, this is an easy task. Let us decide what our script must do. First, it must ask the user whether he or she wants to create a new restore point (Fig. 14.12).

click to expand
Fig. 14.12: Dialog prompting the user to create a restore point

Next, if the user clicks Yes, we must provide the user with the capability to enter the resource point description (Fig. 14.13).

click to expand
Fig. 14.13: The dialog prompting the user to provide a description for the restore point to be created

After the user provides a restore point description, we use WMI moniker and SystemRestore class to access WMI, and then create a new restore point using the description provided by the user. A very simple code performing these tasks is provided in Listing 14.4.

Listing 14.4. Automatic Creation of the Restore Point

start example
 Option Explicit Dim WSHShell, SRP, CSRP, description, Result Set WSHShell = CreateObject ("Wscript.Shell") Result = MsgBox ("Do you want to create a Restore Point?", 36)      If Result = 6 Then 'clicked yes      description = inputbox ("Enter the Restore Point Description:", "Restore point to be created")      'use WMI moniker and SystemRestore class       set SRP = getobject ("winmgmts:\\.\root\default:Systemrestore")       CSRP = SRP.createrestorepoint (description, 0, 100) end if ' End code 
end example

After running this script, start System Restore and check if the restore point was actually created. The screenshot shown in Fig. 14.14 shows four test restore points, which I created automatically in the process of testing this script.

click to expand
Fig. 14.14: The System Restore window displaying automatically created restore points

Now, after carefully testing the script and making sure that it works, let us consider what practical use we can make of it. For example, wouldn't it be nice, if after each successful logon, the user (especially those who experiment with the registry) were prompted to create a restore point? As you remember, Windows XP is successfully loaded only after at least one user logs onto the system, and at that point the Clone control set is copied to the LastKnownGood configuration. Well, in my opinion, it makes sense if you also create a restore point at that time, just to be on the safe side. This small script can serve this purpose if you assign it as a logon script.

To do so, just copy the script file to the %SystemRoot%\System32\GroupPolicy\User\Scripts\Logon directory, then start the Group Policy editor, and expand the console tree as shown in Fig. 14.15 (User Configuration/Windows Setting | Scripts). Double-click the Logon policy to open the Logon Properties window (Fig. 14.16), click the Add button and add our script to the list of logon scripts for the local computer.

click to expand
Fig. 14.15: The Group Policy window

click to expand
Fig. 14.16: The Logon Properties window

Now, each time the user logs onto the local computer, he or she will be prompted to create a restore point.



Windows XP Registry
Linux Enterprise Cluster: Build a Highly Available Cluster with Commodity Hardware and Free Software
ISBN: N/A
EAN: 2147483647
Year: 2000
Pages: 144
Authors: Karl Kopper

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