Interacting with the Windows Registry and Application Event Log

[ LiB ]

Interacting with the Windows Registry and Application Event Log

In addition to the Windows desktop, Start menu, Quick Launch toolbar, printers, disk drives , files, and folders, you can create JScripts that interact with and control other Windows resources. These other resources include the Windows registry and the Windows application event log.

The Windows application event log is one of a collection of log files maintained by Windows operating systems. As Windows applications run, they record event messages in the log that provide a record of their activities. In addition, applications usually record error messages in the Windows application event log. You can modify your JScripts to write information to this log as well, especially error messages.

The Windows registry is a specialized database built into Windows operating systems in which information about all computer hardware and software is stored. In addition, the registry contains information about users and Windows configuration settings. You can create JScripts that take advantage of the Windows registry by using it to store script configuration settings that you might otherwise hard code within your scripts.

Recording Messages in the Windows Application Event Log

Windows computers automatically maintain a collection of log files where messages are recorded. These log files include

  • Application log. Stores event messages recorded by Windows applications.

  • Security log. Stores security and audit event messages.

  • System log. Stores event messages generated by the Windows operating system.

NOTE

The Windows application event log is supported only on Windows NT, XP, 2000, and 2003. If you want to record log information on other Windows operating systems, you will need to create and maintain your own custom log file.

Messages generated by Windows applications are written to the application event log. You can open the Windows application event log and view its contents by right-clicking on the My Computer icon and selecting Manage. This opens the Computer Management console. To view a list of events currently stored in the application event log, expand the Event Viewer node until you see the Application node and then select it, as demonstrated in Figure 7.9.

Figure 7.9. Viewing a list of messages currently stored in the Windows application event log

graphic/07fig09.gif


As you can see, a number of different pieces of information are displayed about the event message, including its type and the time and date it was recorded. To view detailed information about an event, double-click on it.

Using the WshShell object's LogEvent() method, you can modify your JScripts so that they can record messages to the Windows application event log, thus creating a central repository for all your script message reporting. For example, the following JScript statements demonstrate how to record a message in the application log:

 var WshShell = WScript.CreateObject("WScript.Shell"); WshShell.LogEvent(0, "Script 7.X has finished executing without any errors."); 

As you can see, this example begins by instantiating the WshShell object. It then uses the LogEvent() method to record a message to the application log. The information passed to the LogEvent() method consists of two arguments. The first argument is a numeric value that indicates the type of error being recorded to the application event log. There are six different event types that you can specify when coding this argument, as outlined in Table 7.3. The second argument passed to the LogEvent() method is the text string to be recorded in the log.

Table 7.3. SUPPORTED EVENT TYPES

Value

Event Type

A successful event

1

An error event

2

A warning event

4

An informational event

8

A successful audit event

16

A failed audit event


Figure 7.10 shows how the message this example records to the Windows application event log appears when viewed on a computer running Windows XP.

Figure 7.10. The message posted to the application event log by the JScript

graphic/07fig10.gif


As you can see from this example, it does not take a lot of work to modify your JScripts to begin recorded messages to the Windows application event log.

NOTE

TIP

At a minimum, you may want to start setting up your JScripts so that they record messages to the Windows application event log indicating when they start, finish, or experience an error.

Interacting with the Windows Registry

The Windows registry provides you with a central repository where you can store and retrieve script configuration settings. All data is stored within the registry in a tree-like hierarchy. The registry is made up of five high-level root keys, as outlined in Table 7.4.

Table 7.4. ROOT LEVEL REGISTRY KEYS

Key

Abbreviation

Contents

HKEY_LOCAL_MACHINE

HKLM

Contains configuration data for settings that globally affect the computer

HKEY_CLASSES_ROOT

HKCR

Stores information regarding Windows file extension associations

HKEY_CURRENT_USER

HKCU

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

HKEY_USERS

Stores information about all users of the computer

HKEY_CURRENT_CONFIG

Stores information about current configuration settings


NOTE

Depending on which Windows operating system you are working on, other root keys may be present.

NOTE

The Windows registry stores information that is essential to the proper operation of your computer and its software and hardware. It is therefore critical that you take extra care anytime you work with it. Even a small mistake can result in disastrous effects, potentially preventing your computer from restarting.

Within the registry, data is stored in keys and values. A key is a container that stores other keys or values. The actual data stored in the registry is stored within values . It may help you to think of registry keys as being like Windows folders and values as being like Windows files.

The registry stores all data using the following format:

 Key : KeyType : Value 

Key specifies the name of a registry key or subkey . KeyType identifies the type of data that is stored in the key. Value represents the data that is stored. The Windows registry supports the storage of many different types of data, including the following.

  • REG_SZ . Represents a text string.

  • REG_MULTI_SZ . Represents multiple strings.

  • REG_EXPAND_SZ . Represents a string that can be expanded such as %windir% .

  • REG_BINARY . Represents a binary value.

  • REG_DWORD . Represents a hexadecimal DWORD value.

Windows provides a registry editor called Regedit, shown in Figure 7.11, that you can use to view and modify the Windows registry. To start this utility, click on Start, Run and then type Regedit and click on OK.

Figure 7.11. Viewing the structure of the Windows registry using the Regedit utility

graphic/07fig11.gif


Using methods provided by the WshShell object, you can programmatically read, write, and delete data stored in the Windows registry. The registry-related methods provided by the WshShell object include:

  • RegWrite() . Provides the capability to create registry keys and values and to modify existing ones.

  • RegRead() . Provides the capability to read registry keys and values.

  • RegDelete() . Provides the capability to delete registry keys and values.

Storing Data in the Windows Registry

Using the WshShell object's RegWrite() , method you can create new registry subkeys and values. All you have to do is to pass it the complete path within the registry where you want a new key or value to be created. For example, the follow JScript statements create a new key and value under the HKEY_Current_User root key:

 var WshShell = WScript.CreateObject("WScript.Shell"); WshShell.RegWrite("HKCU\MyJScripts\Logging", "On"); 

When run, this example creates a new key and value in the Windows registry under the HKEY_CURRENT_USER root key. However, if either the key or the value already exists, it simply is overwritten.

The key that is created is named MyJScripts . The value that is stored in it is called Logging . The data assigned to the value is On . For example, you could set up your JScripts to log error messages and other information based on the data stored in the Logging value. When set equal to On , your scripts would write message to the Windows applications event log, and when set equal to Off , they would not write event messages. Figure 7.12 shows how the new registry key and value appear once created.

Figure 7.12. Verifying that the new registry subkey and value have been added under the HKEY_Current _User root key

graphic/07fig12.gif


NOTE

TIP

To help work safely within the registry, create one key within which you add other subkeys and values.That way, you will always have a consistent place within the registry where you store your data, thus reducing the possibility of accidentally overwriting data stored in another part of the registry.

Reading Date Stored in the Windows Registry

Reading data from the registry is just as easy as writing it there. For starters, you need to instantiate the WshShell object. You can then use the WshShell object's RegRead() method to read the data stored in any value, as demonstrated here:

 var WshShell = WScript.CreateObject("WScript.Shell"); logMode = WshShell.RegRead("HKCU\MyJScripts\Logging"); if (logMode == "On") {   WshShell.LogEvent(0, "Script 7.X is now executing."); } 

In this example, the value stored in HKCU\JScripts\Logging is read and, if the data stored in it is equal to On , a message is written to the Windows application event log.

Deleting Data Stored in the Windows Registry

If you no longer need to use data that you have stored in the Windows registry, it is a good idea to remove it. This can be done using the WshShell object's RegDelete() method. For example, the following JScript statements show how to delete the HKCU\MyJScripts\Logging value:

 var WshShell = WScript.CreateObject("WScript.Shell"); WshShell.RegDelete("HKCU\MyJScripts\Logging"); 

This example removes the Logging value while leaving the MyJScripts subkey still in place. This is useful in situations where you have stored other subkeys or values under the MyJScripts subkey. However, if you are completely done with the key, you can remove it and all the subkeys and values stored beneath it using the following example:

 var WshShell = WScript.CreateObject("WScript.Shell"); WshShell.RegDelete("HKCU\MyJScripts\"); 

NOTE

To delete a registry subkey using JScript, you must append the \\ character to the end of the subkey name.

Performing System Configuration Via the Windows Registry

Because Windows stores information in the registry that affects virtually every aspect of the computer's operation, you often can change the computer's behavior by modifying the registry values. As an example of what I mean, take a look at the following JScript. This script reconfigures your Windows screensaver settings when you run it.

 //************************************************************ ************* //Script Name: Script 7.3.js //Author: Jerry Ford //Created: 09/21/03 //Description: This JScript configures the Windows screensaver //************************************************************ ************* //Initialization Section   var getConfirmation;   //Instantiate the WshShell object   var wshObject = WScript.CreateObject("WScript.Shell"); //Main Processing Section   //Get confirmation before continuing   getConfirmation = wshObject.Popup("This script configure the Windows " +     "screen saver. \r\r Do you want to continue?", 10, "Please " +     "confirm", 36)    if (getConfirmation == 6) {     ChangeScreenSaver()     NotifyUser()   }   //Terminate script execution   WScript.Quit() //Procedure Section   //This subroutine changes desktop settings   function ChangeScreenSaver() {     //Turn on the Windows screen saver     wshObject.RegWrite("HKCU\Control Panel\Desktop\ScreenSaveActive", 1);     //Turn on password protection     wshObject.RegWrite("HKCU\Control Panel\Desktop\ScreenSaverIsSecure", 1);     //Set up a 20 minute delay     wshObject.RegWrite("HKCU\Control Panel\Desktop\ScreenSaveTimeOut", 1200);     //Enable the Mystify screen saver     wshObject.RegWrite("HKCU\Control Panel\Desktop\ SCRNSAVE.EXE", "C:\" +       "\Windows\System32\ssmyst.scr");    }   function NotifyUser() {     WScript.Echo("The next time you log in the changes will take effect.")   } 

This script begins by defining the getConfirmation variable and instantiating the WshShell object in the script's Initialization section. Next the WshShell object's Popup() method is used to display a pop-up dialog that prompts the user for permission to modify screensaver settings, as shown in Figure 7.13.

Figure 7.13. Prompting the user for confirmation before allowing the JScript to finish executing

graphic/07fig13.gif


If the user elects to allow the script to run, the value assigned to getConfirmation will be set to 6 , in which case the ChangeScreenSaver() and NotifyUser() functions are executed. The ChangeScreenSaver() function performs four RegWrite() operations. The first one modifies the value assigned to HKCU\Control Panel\Desktop\ScreenSaveActive by changing it to 1 . This has the effect of enabling the screensaver in the event that it is currently turned off. Next, the value of HKCU\Control Panel\Desktop\ScreenSaverIsSecure is set to 1 . This enables password protection, which will force the user to reenter his password (if he has one) in order to reauthenticate with the operating system.

Next, the value of HKCU\Control Panel\Desktop\ScreenSaveTimeOut is set equal to 1200 , which is the number of seconds the operating system should wait for no user activity to occur before starting the execution of the screensaver. Finally, the value of HKCU\Control Panel\Desktop\ SCRNSAVE.EXE is set equal to C:\Windows\System32\ssmyst.scr. ssmyst.scr is the name of the Mystify screensaver.

Once the ChangeScreenSaver() function has finished, the NotifyUser() function executes. This function displays a text message in a pop-up dialog notifying the user that the changes made by the script will take effect the next time the user logs into Windows, as shown in Figure 7.14.

Figure 7.14. The script notifies the user after the screensaver settings have been reconfigured.

graphic/07fig14.gif


NOTE

By default,Windows stores its screensavers in C:\Windows\System32 .They can be identified by their .scr file extension.To see which ones are which, just double-click on them to see them run.

You can verify the changes made by the JScript by looking at the Screen Saver property sheet on the Display Properties dialog. To open this dialog, right-click on an open area of the Windows desktop and select Properties. Figure 7.15 shows how the screensaver setting will look after the script has finished executing.

Figure 7.15. Reconfiguring Windows screensaver settings via modifications to the Windows registry

graphic/07fig15.gif


[ LiB ]


Learn JavaScript In a Weekend
Learn JavaScript In a Weekend, Second Edition
ISBN: 159200086X
EAN: 2147483647
Year: 2003
Pages: 84

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