Chapter 8. Computer Assets

Computers must be managed as physical assets; this involves such key tasks as taking inventory of computer hardware, identifying the operating system and other software installed on a computer, and configuring such things as computer startup and recovery options. Scripting provides a single-source method that can facilitate computer management in your organization.

In This Chapter

Computer Assets Overview

In most organizations, computers represent a sizable portion of the physical assets that must be managed. Because of this, many organizations have adopted asset management techniques as a way to maintain and manage computers.

Asset management is the process of maintaining, upgrading, and operating physical assets in a cost-effective manner. Effective asset management requires a detailed, accurate report of the physical assets under your control, including:

  • The number and type of resources available.

  • The location of these resources.

  • The current status of these resources.

This data provides a clear picture of the resources available, how they have been distributed, and how they are being used. The data can then be used to create a more equitable (and less expensive) distribution of existing resources and to plan for future needs.

Unfortunately, maintaining up-to-date information about the computers in an organization can be difficult. Unlike other assets, computers often change configuration: A new hard disk might be installed, additional memory added, software upgraded or removed. In addition, computers are often moved to new locations. The number and type of changes that computers can undergo require you to inventory these items on a regular basis; inventorying computer hardware once or twice a year will probably not supply an accurate picture of the computing resources available in your organization.

On the other hand, performing a computer inventory can be very time-consuming. Although some information can be collected by a visual inspection, many components and peripherals are hidden inside the computer case. In many organizations, support technicians must physically log on to each computer to conduct an inventory. After they are logged on, they typically require a variety of third-party software tools to determine the configuration.

Scripting provides a way to inventory the required information and to ensure that the inventory is updated on a regular basis. Scripts can automatically retrieve detailed information about the computers in the enterprise, including such things as:

  • The configuration of each computer.

  • Unique identifiers, such as asset tags and serial numbers.

  • The physical hardware installed on each computer.

  • Software installed on each computer.

By using a script to conduct the inventory, you can efficiently maintain up-to-date information that enables you to manage computers as assets. Furthermore, you can do this without requiring support technicians to physically log on to each computer and without purchasing and deploying multiple tools. Instead, a single script can be used to obtain a complete inventory of every computer in the organization.

Retrieving System Information

Most computer management activities, including troubleshooting computer problems, installing new software, and applying Group Policy, require comprehensive information about how a computer has been configured. This information includes such things as the:

  • Operating system installed on a computer.

  • Amount of memory installed on a computer.

  • Amount of disk space available on a computer.

The System Information snap-in has long been the tool of choice for system administrators needing comprehensive information about a computer, the hardware installed on that computer, and the software running on that computer. The System Information snap-in and a sample of the kind of information it can return are shown in Figure 8.1.

System Information Snap-in

Figure 8.1. System Information Snap-in

Although the System Information snap-in is a useful tool, it does have limitations that make it a less than optimal choice for performing inventories. In particular, this tool:

  • Is designed to work on a single computer at a time, and it works best when run against the local computer rather than a remote computer.

  • Cannot be automated or customized.

  • Does not lend itself to enterprise-wide retrieval and storage of computer information.

  • Does not allow for exporting data directly into a database.

    Although it is possible to manually export the data from within System Information, the resulting text file uses a free-form style of formatting that makes it difficult to parse the information and save it to a database.

  • Does not allow you to customize data retrieval to meet your needs. In fact, the amount of data returned from System Information is often more than is needed for routine administrative tasks.

To overcome these limitations, system administrators have typically turned to third-party tools. Depending on your needs, however, you can save considerable cost by creating custom Windows Management Instrumentation (WMI) scripts that replicate the full functionality of the System Information snap-in. Using a WMI script provides a number of advantages over the System Information snap-in:

  • Scripts can be run against a single computer or against multiple computers.

  • Scripts can be used to automate data collection.

    For example, a script can be scheduled to run on a group of computers at a specific date and time.

  • Scripts can be customized to return only the desired data.

  • Scripts can be customized to collect data not retrieved by System Information.

    For example, although System Information can retrieve the name and version number of the operating system, it cannot retrieve more detailed information such as the set of hot fixes that have been applied to the computer.

  • Scripts can save data in a standard text file format (such as tab-delimited or comma-delimited), or directly to a database.

Table 8.1 lists the data fields found on the System Information Summary tab and the equivalent WMI classes and properties.

Table 8.1. System Information Fields and Equivalent WMI Classes and Properties

System Information Field

WMI Class and Property

OS Name

Win32_OperatingSystem.Name

OS Version

Win32_OperatingSystem.Version

Service Pack

Win32_OperatingSystem.ServicePackMajorVersion Win32_OperatingSystem.ServicePackMinorVersion

OS Manufacturer

Win32_OperatingSystem.Manufacturer

System Name

Win32_ComputerSystem.Name

System Manufacturer

Win32_ComputerSystem.Manufacturer

System Model

Win32_ComputerSystem.Model

System Type

Win32_Processor.Architecture

Processor

Win32_Processor.Description

BIOS Version

Win32_BIOS.Version

Windows Directory

Win32_OperatingSystem.WindowsDirectory

Locale

Win32_OperatingSystem.Locale

Time Zone

Win32_ComputerSystem.TimeZone

Total Physical Memory

Win32_ComputerSystem.PhsyicalMemory

Available Physical Memory

Win32_OperatingSystem.FreePhysicalMemory

Total Virtual Memory

Win32_OperatingSystem.TotalVirtualMemory

Available Virtual Memory

Win32_OperatingSystem.AvailableVirtualMemory

Page File Space

Win32_OperatingSystem.SizeStoredInPagingFiles

Scripting Steps

Listing 8.1 contains a script that retrieves the specified system information for a computer. To carry out this task, the script must perform the following steps:

  1. Create a variable to specify the computer name.

  2. Use a GetObject call to connect to the WMI namespace rootcimv2, and set the impersonation level to “impersonate.”

  3. Use the ExecQuery method to query the Win32_OperatingSystem class.

    This query returns a collection consisting of all the operating systems installed on the computer.

  4. For each item in the collection, echo the desired property values.

  5. Repeat steps 3 and 4, substituting the other desired WMI classes.

    Separate calls are required because WMI allows you to connect to only a single class at a time.

Example 8.1. Retrieving System Information

 1 strComputer = "."
 2 Set objWMIService = GetObject("winmgmts:" _
 3     & "{impersonationLevel=impersonate}!\" & strComputer & "
ootcimv2")
 4 Set colSettings = objWMIService.ExecQuery _
 5     ("SELECT * FROM Win32_OperatingSystem")
 6 For Each objOperatingSystem in colSettings
 7     Wscript.Echo "OS Name: " & objOperatingSystem.Name
 8     Wscript.Echo "Version: " & objOperatingSystem.Version
 9     Wscript.Echo "Service Pack: " & _
10         objOperatingSystem.ServicePackMajorVersion _
11             & "." & objOperatingSystem.ServicePackMinorVersion
12     Wscript.Echo "OS Manufacturer: " & objOperatingSystem.Manufacturer
13     Wscript.Echo "Windows Directory: " & _
14         objOperatingSystem.WindowsDirectory
15     Wscript.Echo "Locale: " & objOperatingSystem.Locale
16     Wscript.Echo "Available Physical Memory: " & _
17         objOperatingSystem.FreePhysicalMemory
18     Wscript.Echo "Total Virtual Memory: " & _
19         objOperatingSystem.TotalVirtualMemorySize
20     Wscript.Echo "Available Virtual Memory: " & _
21         objOperatingSystem.FreeVirtualMemory
22     Wscript.Echo "OS Name: " & objOperatingSystem.SizeStoredInPagingFiles
23 Next
24 Set colSettings = objWMIService.ExecQuery _
25     ("SELECT * FROM Win32_ComputerSystem")
26 For Each objComputer in colSettings
27     Wscript.Echo "System Name: " & objComputer.Name
28     Wscript.Echo "System Manufacturer: " & objComputer.Manufacturer
29     Wscript.Echo "System Model: " & objComputer.Model
30     Wscript.Echo "Time Zone: " & objComputer.CurrentTimeZone
31     Wscript.Echo "Total Physical Memory: " & _
32         objComputer.TotalPhysicalMemory
33 Next
34 Set colSettings = objWMIService.ExecQuery _
35     ("SELECT * FROM Win32_Processor")
36 For Each objProcessor in colSettings
37     Wscript.Echo "System Type: " & objProcessor.Architecture
38     Wscript.Echo "Processor: " & objProcessor.Description
39 Next
40 Set colSettings = objWMIService.ExecQuery _
41     ("SELECT * FROM Win32_BIOS")
42 For Each objBIOS in colSettings
43     Wscript.Echo "BIOS Version: " & objBIOS.Version
44 Next

Retrieving BIOS Information

The BIOS provides an interface between the operating system and the computer hardware; it also contains information regarding a computer and how it has been configured. The information contained in the BIOS is important both for identifying a computer and for determining the hardware that can be installed on it. In addition, the BIOS, which is located on a computer chip, supports peripheral equipment and manages internal services such as the computer date and time.

Besides the standard BIOS required by all computers, most computers also adhere to the System Management BIOS (SMBIOS) specification. The SMBIOS specification enables computer manufacturers and BIOS and software developers to provide support for managed systems. This specification includes standardized methods for querying the BIOS to retrieve information about items such as the number of processors installed on a computer, the amount and type of memory installed on a computer, and information about the BIOS used on a computer. BIOS information such as this does not compete with the information that can be returned using a scripting technology such as WMI; instead, the two complement one another. In fact, WMI can be used to return a number of key properties about the BIOS itself.

Retrieving Information About the BIOS

Each computer has a BIOS that is used to configure basic computer settings, including fundamental properties such as whether a password is required to start the computer and how memory can be configured. The BIOS also helps determine which hardware can be installed on a computer. For example, before you can add a new CPU or a new motherboard to a computer, you must make sure the computer has the correct version of the BIOS.

BIOS manufacturers routinely issue BIOS upgrades that enable a computer to support new classes of hardware or that add features to the computer. Before installing such an upgrade, you must know which version of a BIOS has been installed on a computer. Attempting to add hardware to a computer that does not support this hardware can cause serious problems. Problems can also occur if you attempt to install a BIOS upgrade on a computer that does not use that particular BIOS to begin with.

Note

Note

The make and model of a computer are not always indicative of which BIOS has been installed on that computer. Two seemingly identical computers from the same manufacturer might use different BIOS.

You can use the Win32_BIOS class to enumerate the properties of the BIOS installed in your computer. Table 8.2 lists some of the more commonly used properties of the Win32_BIOS class, including properties related to the installed version of SMBIOS.

Table 8.2. Win32_BIOS Properties

Property

Description

BIOSCharacteristics

Array of BIOS characteristics supported by the computer as defined by the SMBIOS Reference Specification. The possible values for this property are:

  • 3— BIOS characteristics not supported

  • 4— ISA is supported

  • 6— EISA is supported

  • 7— PCI is supported

  • 8— PC Card (PCMCIA) is supported

  • 9— Plug and Play is supported

  • 10APM is supported

  • 11— BIOS is upgradable (flash)

  • 15— Boot from CD is supported

  • 16— Selectable boot is supported

  • 17— BIOS ROM is socketed

  • 18— Boot from PC card (PCMCIA) is supported

  • 32— ACPI supported

  • 34— AGP is supported

BuildNumber

Internal identifier for the BIOS.

CurrentLanguage

Name of the current BIOS language.

InstallableLanguages

Number of languages available for installation on this computer.

Manufacturer

Manufacturer of the BIOS.

Name

Name used to identify the BIOS.

PrimaryBIOS

Indicates whether this is the primary BIOS of the computer.

ReleaseDate

Release date of the BIOS. Dates are in the Universal Time Coordinate (UTC) format yyyymmddHHMMSS.xxxxxx-UUU, where:

  • yyyy represents the year

  • mm represents the month

  • dd represents the day

  • HH represents the hour (in 24-hour time format)

  • MM represents the minutes

  • SS represents the seconds

  • xxxxxx represents the milliseconds

  • UUU represents the number of minutes to be subtracted from the current time in order to calculate Greenwich Mean Time

For example, a BIOS released on October 31, 2002, at 10:45:39 A.M. Pacific time looks like this:

20021031104539.000000-480

SerialNumber

Serial number assigned to the BIOS by the manufacturer.

SMBIOSVersion

BIOS version as reported by SMBIOS.

SMBIOSMajorVersion

Major SMBIOS version number.

SMBIOSMinorVersion

Minor SMBIOS version number.

SMBIOSPresent

Indicates whether the SMBIOS is available on this computer.

Version

Version of the BIOS.

Some, but not all, of this information is also available through the System Information snap-in, as shown in Figure 8.2.

Win32_BIOS Properties and System Information

Figure 8.2. Win32_BIOS Properties and System Information

Scripting Steps

Listing 8.2 contains a script that retrieves BIOS information for a computer. To carry out this task, the script must perform the following steps:

  1. Create a variable to specify the computer name.

  2. Use a GetObject call to connect to the WMI namespace rootcimv2, and set the impersonation level to “impersonate.”

  3. Use the ExecQuery method to query the Win32_BIOS class.

    This query returns a collection consisting of a single object representing the BIOS installed on the computer.

  4. For each BIOS in the collection, echo the retrieved values.

    Because the BIOS characteristics are contained within an array, a For Each loop must be used to loop through each element in the array.

Example 8.2. Retrieving BIOS Information

 1 strComputer = "."
 2 Set objWMIService = GetObject("winmgmts:" _
 3     & "{impersonationLevel=impersonate}!\" & strComputer & "
ootcimv2")
 4 Set colBIOS = objWMIService.ExecQuery _
 5     ("SELECT * FROM Win32_BIOS")
 6 For Each objBIOS in colBIOS
 7     Wscript.Echo "Build Number: " & objBIOS.BuildNumber
 8     Wscript.Echo "Current Language: " & objBIOS.CurrentLanguage
 9     Wscript.Echo "Installable Languages: " & objBIOS.InstallableLanguages
10     Wscript.Echo "Manufacturer: " & objBIOS.Manufacturer
11     Wscript.Echo "Name: " & objBIOS.Name
12     Wscript.Echo "Primary BIOS: " & objBIOS.PrimaryBIOS
13     Wscript.Echo "Release Date: " & objBIOS.ReleaseDate
14     Wscript.Echo "Serial Number: " & objBIOS.SerialNumber
15     Wscript.Echo "SMBIOS Version: " & objBIOS.SMBIOSBIOSVersion
16     Wscript.Echo "SMBIOS Major Version: " & objBIOS.SMBIOSMajorVersion
17     Wscript.Echo "SMBIOS Minor Version: " & objBIOS.SMBIOSMinorVersion
18     Wscript.Echo "SMBIOS Present: " & objBIOS.SMBIOSPresent
19     Wscript.Echo "Status: " & objBIOS.Status
20     Wscript.Echo "Version: " & objBIOS.Version
21     For Each intCharacteristic in objBIOS.BiosCharacteristics
22         Wscript.Echo "BIOS Characteristics: " & intCharacteristic
23     Next
24 Next

Retrieving Identifying Information by Using the SMBIOS

Computers are typically identified by name. This practice provides a convenient way to distinguish one computer from another, but it is not always sufficient for uniquely identifying computers; after all, computer names are easily, and often, changed. To track individual computers, you should always use a more immutable identifier, such as the serial number or the asset tag number.

The SMBIOS specification enables manufacturers to store extended information in the BIOS, including unique identifiers such as the serial number and the asset tag number. Retrieving the serial number or the asset tag number can help identify a specific computer. For example, each computer has a unique serial number that does not change unless the BIOS is replaced. Because you are far less likely to replace a BIOS than to rename a computer, the BIOS serial number provides a good way to identify computers.

Identifying information such as serial number and asset tag can be retrieved from a computer by using the WMI Win32_SystemEnclosure class.

Note

Note

A number of third-party tools can also retrieve extended BIOS information. However, most of these tools are hardware-specific; before the SMBIOS specifications were completed, many hardware manufacturers stored the serial number and asset tag in nonstandard formats. The Win32_SystemEnclosure class can generally retrieve this information, even if it has been stored in a nonstandard way.

Table 8.3 lists the SMBIOS-related properties of the Win32_SystemEnclosure class.

Table 8.3. Win32_SystemEnclosure Properties

Property

Description

PartNumber

Part number assigned by the organization responsible for producing or manufacturing the computer.

SerialNumber

Manufacturer-allocated number used to identify the computer.

SKU

Stock-keeping unit number for the computer.

SMBIOSAssetTag

Asset tag number of the computer.

Scripting Steps

Listing 8.3 contains a script that retrieves identifying information for a computer. To carry out this task, the script must perform the following steps:

  1. Create a variable to specify the computer name.

  2. Use a GetObject call to connect to the WMI namespace rootcimv2, and set the impersonation level to “impersonate.”

  3. Use the ExecQuery method to query the Win32_SystemEnclosure class.

    This query returns a collection consisting of the physical properties of the computer and its housing.

  4. Echo the values for PartNumber, SerialNumber, and SMBIOSAssetTag.

Example 8.3. Retrieving Identifying Information

 1 strComputer = "."
 2 Set objWMIService = GetObject("winmgmts:" _
 3     & "{impersonationLevel=impersonate}!\" & strComputer & "
ootcimv2")
 4 Set colSMBIOS = objWMIService.ExecQuery _
 5     ("SELECT * FROM Win32_SystemEnclosure")
 6 For Each objSMBIOS in colSMBIOS
 7     Wscript.Echo "Part Number: " & objSMBIOS.PartNumber
 8     Wscript.Echo "Serial Number: " & objSMBIOS.SerialNumber
 9     Wscript.Echo "Asset Tag: " & objSMBIOS.SMBIOSAssetTag
10 Next

Inventorying Computer Hardware

The inventory process helps determine the number of computers in your organization and how these computers have been configured. This type of information can be very useful in a number of situations:

  • Preparing to upgrade to a new operating system or a new software package.

    The inventory helps determine which computers have hardware that is compatible with the new produc. It also helps you determine whether these computers have sufficient hardware resources to run the new product.

  • Planning the information technology budget.

    The inventory helps determine which computers have adequate hardware to last through the next budget period and which computers require hardware upgrades or need to be replaced.

  • Replacing computers in an organization.

    The inventory helps determine which hardware can be used elsewhere in the organization and which hardware cannot.

  • Taking help desk calls from users.

    The inventory helps determine the hardware configuration of a user’s computer. This kind of information is important for help desk personnel trying to remotely diagnose and resolve computer problems.

WMI contains many classes that enable you to retrieve detailed information about computer hardware. For example, Table 8.4 lists hardware categories that can be retrieved either by using the System Information snap-in or by using the equivalent WMI classes.

Table 8.4. System Information Categories and Their WMI Equivalents

System Information Category

WMI Class

CD-ROM

Win32_CDRomDrive

Sound Device

Win32_SoundDevice

Display

Win32_VideoController

Infrared

Win32_InfraredDevice

Keyboard

Win32_Keyboard

Pointing Device

Win32_PointingDevice

Modem

Win32_POTSModem

Network Adapter

Win32_NetworkAdapter

Serial Ports

Win32_SerialPort

Parallel Ports

Win32_ParallelPort

Drives

Win32_DiskDrive

SCSI

Win32_SCSIController

Printers

Win32_Printer

USB

Win32_USBController

In addition to the classes listed in Table 8.4, a number of other WMI classes are useful in taking inventory of computer hardware. WMI classes exist for almost all hardware components on a computer. (However, there are proprietary hardware devices that do not support WMI.) Some of these classes are listed in Table 8.5.

Table 8.5. Additional WMI Classes for Retrieving Hardware Information

WMI Class

Description

Win32_Baseboard

Provides information about the computer motherboard (also known as the baseboard or system board). The motherboard contains the bus, the processor and coprocessor sockets, memory sockets, keyboard controller, and other electrical components.

Win32_Bus

Provides information about the internal bus. The bus allows the computer to transfer data between the central processing unit, system memory, and peripheral buses.

Win32_DesktopMonitor

Provides information about the monitor or display device used by the computer.

Win32_Fan

Provides information about fans, including the CPU cooling device, installed in the computer.

Win32_PhysicalMemory

Provides information regarding physical memory devices installed in the computer.

Win32_PNPEntity

Provides information about all Plug and Play devices installed in the computer. Plug and Play devices are hardware devices that conform to the Plug and Play standard, allowing them to be installed on a computer without the need for manual configuration.

Win32_Processor

Provides information about each processor installed on a computer.

The information available through the various WMI classes is almost identical to the hardware information available using graphical user interface (GUI) tools. For example, Figure 8.3 compares the Win32_PointingDevice class with the data available in the System Information snap-in.

Win32_PointingDevice and System Information

Figure 8.3. Win32_PointingDevice and System Information

Taking Inventory of Computer Hardware

Although different hardware settings must be accessed through different WMI classes, the scripting approach is identical in each case:

  1. Your script connects to the WMI service on the computer to be inventoried.

  2. Your script connects to the appropriate WMI class.

    For example, if you want a list of CD-ROM drives, you should connect to the Win32_CDROMDrive class. If you want information about display adapters, you should connect to the Win32_VideoController class.

  3. For each item in the returned collection (that is, each installed CD-ROM drive or each installed display adapter), retrieve the desired properties.

One nice feature of WMI is the fact that no error condition occurs if you attempt to enumerate hardware that does not exist. For example, suppose you are trying to inventory tape drives, and no tape drive exists on a particular computer. This is not a problem; you will still receive a collection of the tape drives on that computer. The only difference is that the collection will have no items in it.

Of course, you do not receive any “official” notice that the computer does not have any tape drives; you have to infer this from the fact that no tape drive information was returned. To help verify that the computer does not have any tape drives, you can use the Count property to check the number of items in the collection. If the Count is 0, you can echo the message, No tape drives were found in this computer. If the Count is greater than 0, you can then report the property values for each tape drive.

The following code sample uses the Count property to identify zero-item collections:

If colTapeDrives.Count = 0 Then
    Wscript.Echo "No tape drives were found in this computer."
Else
    For Each objTapeDrive in colTapeDrives
        Wscript.Echo objTapeDrive.Name
    Next
End If

Scripting Steps

Listing 8.4 contains a script that retrieves the hardware inventory for a computer. In this script, information is retrieved for only a single hardware category: the pointing device. To retrieve information about additional hardware categories, the script would need to connect to each additional hardware class (for example, Win32_SoundDevice) and retrieve the appropriate property values.

To carry out this task, the script must perform the following steps:

  1. Create a variable to specify the computer name.

  2. Use a GetObject call to connect to the WMI namespace rootcimv2, and set the impersonation level to “impersonate.”

  3. Use the ExecQuery method to query the Win32_PointingDevice class.

    This query returns a collection of all the pointing devices (mice, trackballs, and similar hardware) installed on the computer.

  4. For each pointing device in the collection, echo the values for the hardware type, number of buttons, pointing device status, and Plug and Play device ID.

Note

Note

In a production script, you would probably save the inventory information from multiple computers to a database or text file rather than echoing it to the screen. For more information about saving data, see “Creating Enterprise Scripts” in this book.

Example 8.4. Inventorying Computer Hardware

 1 strComputer = "."
 2 Set objWMIService = GetObject("winmgmts:" _
 3     & "{impersonationLevel=impersonate}!\" & strComputer & "
ootcimv2")
 4 Set colMice = objWMIService.ExecQuery _
 5     ("SELECT * FROM Win32_PointingDevice")
 6 For Each objMouse in colMice
 7     Wscript.Echo "Hardware Type: " & objMouse.HardwareType
 8     Wscript.Echo "Number of Buttons: " & objMouse.NumberOfButtons
 9     Wscript.Echo "Status: " & objMouse.Status
10     Wscript.Echo "PNP Device ID: " & objMouse.PNPDeviceID
11 Next

Identifying the Chassis Type of a Computer

The chassis is the physical container that houses the components of a computer. Chassis types include the tower configuration, desktop computer, notebook computer, and handheld computer.

At first glance, it might seem that the chassis type is interesting information but of minimal use to system administrators. In truth, however, knowing the physical design of the chassis provides valuable information for system administrators. After all, the physical design is a key factor in determining the type of hardware you can install on the computer; for example, disk drives that can be installed on a desktop computer are unlikely to fit in a subnotebook computer.

Knowing the chassis type of a computer can also be important for:

  • Applying Group Policy. Group Policy is often applied differently to computers with some chassis types. For example, software is typically installed in full on notebook computers rather than simply installed on first use. This ensures that a mobile user has available all the features of the software package.

  • Planning hardware upgrades. A computer that is going to be upgraded must be able to support the intended upgrade. Hard disks and network adapters designed for desktop computers do not work on notebook computers.

  • Planning hardware moves. If space is limited, you might prefer moving a mini-tower computer to a particular area rather than a full tower computer.

Traditionally, the only way to identify the chassis type has been by visual inspection. However, the Win32_SystemEnclosure class can be used to determine the chassis type of a computer. Chassis types are stored as an array consisting of one or more of the values shown in Table 8.6.

Table 8.6. Computer Chassis Values

Value

Description

1

Other

2

Unknown

3

Desktop

4

Low Profile Desktop

5

Pizza Box

6

Mini Tower

7

Tower

8

Portable

9

Laptop

10

Notebook

11

Hand Held

12

Docking Station

13

All in One

14

Sub Notebook

15

Space-Saving

16

Lunch Box

17

Main System Chassis

18

Expansion Chassis

19

Sub Chassis

20

Bus Expansion Chassis

21

Peripheral Chassis

22

Storage Chassis

23

Rack Mount Chassis

24

Sealed-Case PC

Scripting Steps

Listing 8.5 contains a script that identifies computer chassis type. To carry out this task, the script must perform the following steps:

  1. Create a variable to specify the computer name.

  2. Use a GetObject call to connect to the WMI namespace rootcimv2, and set the impersonation level to “impersonate.”

  3. Use the ExecQuery method to query the Win32_SystemEnclosure class.

    This query returns a collection consisting of the physical properties of the computer and its housing.

  4. For each set of physical properties in the collection, echo the chassis type.

    To do this, you must set up a For-Next loop to echo the values for the chassis type. The For-Next loop is required because the chassis type is stored as an array.

Example 8.5. Identifying Computer Chassis Type

 1 strComputer = "."
 2 Set objWMIService = GetObject("winmgmts:" _
 3     & "{impersonationLevel=impersonate}!\" & strComputer & "
ootcimv2")
 4 Set colChassis = objWMIService.ExecQuery _
 5     ("SELECT * FROM Win32_SystemEnclosure")
 6 For Each objChassis in colChassis
 7     For Each intType in objChassis.ChassisTypes
 8         Wscript.Echo intType
 9     Next
10 Next

When the script in Listing 8.5 runs, the chassis type is reported as an integer. For example, if the computer has a mini-tower configuration, the value 6 is echoed to the screen. In a production script, a Select Case statement should be used to echo back string values as shown in the following code sample:

Case 6
Wscript.Echo "This computer is configured as a mini-tower."

Managing Operating Systems

Many management activities require you to know which version of the Windows operating system is installed on a computer. Among other things, this knowledge helps you ensure that:

  • Service packs, hot fixes, and other operating system upgrades are applied to all computers requiring these updates.

  • Software installations and upgrades are targeted only toward computers with operating systems that support the software.

  • Support personnel can better answer questions and respond to problems.

Scripts can identify the operating system installed on a computer and can provide additional details about that operating system, including such things as build number and language. Scripts can also identify service packs, hot fixes, and other operating system upgrades that have been installed since the operating system was first configured.

Identifying the Name and Version Number of the Operating System

Operating systems vary in the capabilities they support; newer operating systems typically support more features and have more capabilities than older operating systems. For example, scripts that run on a Windows 2000 operating system might not run on an earlier version of Windows. This is because many new WMI classes were introduced in Windows 2000.

You can use the WMI Win32_OperatingSystem class to return both the name and the version number of the operating system running on a computer. For example, the following information is returned from a computer running Windows 2000 Professional:

Microsoft Windows 2000 Professional 5.0.2600

The kind of information you need to collect can affect whether you need to retrieve both the name and the version number. To distinguish between products with different names, you can retrieve either the product name or the version number. To distinguish between products with the same version number, you must retrieve the name.

Table 8.7 lists the names and version numbers for a selected subset of Windows operating systems.

Table 8.7. Windows Operating System Names and Version Numbers

Name

Version Number

Microsoft Windows 2000 Professional

5.0.2195

Microsoft Windows 2000 Server

5.0.2195

Microsoft® Windows® XP Home Edition

5.1.2600

Microsoft® Windows® XP Professional

5.1.2600

The properties of the WMI Win32_OperatingSystem class used to retrieve the operating system name and version number of each operating system installed on a computer are listed in Table 8.8.

Table 8.8. Win32_OperatingSystem Properties

Property

Description

Caption

Name of the operating system.

Version

Version number of the operating system.

Scripting Steps

Listing 8.6 contains a script that identifies the name and version number of the operating system installed on a computer. To carry out this task, the script must perform the following steps:

  1. Create a variable to specify the computer name.

  2. Use a GetObject call to connect to the WMI namespace rootcimv2, and set the impersonation level to “impersonate.”

  3. Use the ExecQuery method to query the Win32_OperatingSystem class.

    This query returns a collection consisting of all the operating systems installed on the computer.

  4. For each operating system in the collection, echo the name and version number.

Example 8.6. Identifying the Name and Version Number of the Operating System

1 strComputer = "."
2 Set objWMIService = GetObject("winmgmts:" _
3     & "{impersonationLevel=impersonate}!\" & strComputer & "
ootcimv2")
4 Set colOperatingSystems = objWMIService.ExecQuery _
5     ("SELECT * FROM Win32_OperatingSystem")
6 For Each objOperatingSystem in colOperatingSystems
7     Wscript.Echo objOperatingSystem.Caption, objOperatingSystem.Version
8 Next

Retrieving the Properties of the Operating System

Even though the operating systems on two different computers might have the same name and version number, those two operating systems can still differ. They might be configured with different language settings, support different encryption levels, or have different client licensing requirements.

Many differences between similar computers are reflected in the detailed property settings of their operating systems. These property settings can greatly affect the way each computer should be managed. For example, you might send a different technician to work on a computer running a Japanese version of a Windows 2000 operating system than you would send to work on a computer running a French version.

The WMI Win32_OperatingSystem class can be used to retrieve details of the operating system installed on a computer.

Important

Important

Unfortunately, WMI can retrieve information only about the operating system currently being used by a computer. For example, suppose you have a dual-boot computer with Windows XP and Windows 2000 installed, and the computer is currently running under Windows XP. If you run a script to return information about the operating system, only information for Windows XP will be returned.

Some of the more commonly used properties from this class are listed in Table 8.9.

Table 8.9. Win32_OperatingSystem Properties

Property

Description

BootDevice

Name of the disk drive from which the Win32 operating system boots.

BuildNumber

Build number of the operating system. The build number can be used for more precise versioning information than product release version numbers.

For example, 2195 is the build number for the released version of Windows 2000.

BuildType

Type of build used for the operating system. The two primary build types are retail (the build purchased through a software vendor), and checked (test versions of the operating system that include special code to aid in debugging).

Caption

Name of the operating system.

CodeSet

Code page value used by the operating system.

A code page contains a character table used by the operating system to translate strings for different languages. The American National Standards Institute (ANSI) lists values that represent defined code pages. If the operating system does not use an ANSI code page, this member will be set to 0. The CodeSet string can use up to six characters to define the code page value. For example, the code page value for US English is 1252.

CountryCode

Code for the country/region used by the operating system.

Values are based on international phone dialing prefixes (also referred to as IBM country/region codes). The property can use up to six characters to define the country/region code value. For example, the country code for the United States is 1.

Debug

Operating system is a checked (debugged) build.

Checked builds provide error checking, argument verification, and system debugging code. Additional code in a checked binary generates a kernel debugger error message and breaks into the debugger. This helps to immediately determine the cause and location of the error. Performance suffers in the checked build because of the additional code that must be executed. In general, checked builds should be used on test computers, not production computers.

InstallDate

Date the operating system was installed, in UTC format.

NumberOfLicensedUsers

Number of user licenses for the operating system. If unlimited, this is returned as 0. If unknown, this is usually returned as –1.

Organization

Company name of the registered user of the operating system.

OSProductSuite

Installed and licensed system product additions to the operating system. Values include the following:

  • 1— Small Business Server

  • 2— Enterprise Server

  • 4— Back Office Server

  • 8— Communication Server

  • 16— Terminal Server

  • 32— Small Business Server (restricted)

  • 64— Embedded NT

  • 128— Data Center

OSType

Type of operating system. The most common values include:

  • 16 = WIN95

  • 17 = WIN98

  • 18 = WINNT

  • 19 = WINCE

The value 18 (WINNT) is returned as the OsType for Windows 2000 and Windows XP.

Primary

Boolean value that indicates whether this is the primary operating system. This property is meaningful only on multiple-boot computers that have more than one operating system installed.

RegisteredUser

Name of the registered user of the operating system.

SerialNumber

Serial identification number of the operating system.

Version

Version number of the operating system (for example, 4.0).

Scripting Steps

Listing 8.7 contains a script that retrieves the properties of the operating system currently in use on a computer. To carry out this task, the script must perform the following steps:

  1. Create a variable to specify the computer name.

  2. Use a GetObject call to connect to the WMI namespace rootcimv2, and set the impersonation level to “impersonate.”

  3. Use the ExecQuery method to query the Win32_OperatingSystem class.

    This query returns a collection consisting of the operating system currently in use on the computer.

  4. For the only operating system in the collection, echo the values for the specified properties.

Example 8.7. Retrieving the Properties of the Operating System

 1 strComputer = "."
 2 Set objWMIService = GetObject("winmgmts:" _
 3     & "{impersonationLevel=impersonate}!\" & strComputer & "
ootcimv2")
 4 Set colOperatingSystems = objWMIService.ExecQuery _
 5     ("SELECT * FROM Win32_OperatingSystem")
 6 For Each objOperatingSystem in colOperatingSystems
 7     Wscript.Echo "Boot Device: " & objOperatingSystem.BootDevice
 8     Wscript.Echo "Build Number: " & objOperatingSystem.BuildNumber
 9     Wscript.Echo "Build Type: " & objOperatingSystem.BuildType
10     Wscript.Echo "Caption: " & objOperatingSystem.Caption
11     Wscript.Echo "Code Set: " & objOperatingSystem.CodeSet
12     Wscript.Echo "Country Code: " & objOperatingSystem.CountryCode
13     Wscript.Echo "Debug: " & objOperatingSystem.Debug
14     Wscript.Echo "Install Date: " & objOperatingSystem.InstallDate
15     Wscript.Echo "Licensed Users: " & _
16         objOperatingSystem.NumberOfLicensedUsers
17     Wscript.Echo "Organization: " & objOperatingSystem.Organization
18     Wscript.Echo "OS Language: " & objOperatingSystem.OSLanguage
19     Wscript.Echo "OS Product Suite: " & objOperatingSystem.OSProductSuite
20     Wscript.Echo "OS Type: " & objOperatingSystem.OSType
21     Wscript.Echo "Primary: " & objOperatingSystem.Primary
22     Wscript.Echo "Registered User: " & objOperatingSystem.RegisteredUser
23     Wscript.Echo "Serial Number: " & objOperatingSystem.SerialNumber
24     Wscript.Echo "Version: " & objOperatingSystem.Version
25 Next

Identifying the Latest Installed Service Pack

Service packs represent changes that have been made to the base operating system since the time the operating system was first released. These changes can include fixes to known problems, updates to device drivers, new tools, and enhanced functionality.

Knowing which service packs have been installed on a computer is important for several reasons. For example:

  • Many hot fixes or software updates cannot be installed unless a particular service pack has previously been installed on a computer.

    Hot fixes (code fixes released to address specific problems in the operating system) are generally tied to a service pack, meaning the service pack must be installed before the hot fix can be applied. Before you can apply hot fixes or other software updates, you might need to know whether a particular service pack has been installed on a computer.

  • Technical support personnel (including those from Microsoft Product Support Service) need to know which service packs have been installed when troubleshooting problems.

Service packs are released on an as-needed basis and are cumulative. For example, when Service Pack 3 for a version of Windows is released, it contains all the updates that were included in Service Packs 1 and 2. Installing Service Pack 3 provides all the benefits of the new service pack as well as those of the first two service packs.

The version number of the latest service pack installed on a computer can be retrieved using the Win32_OperatingSystem class. The Win32_OperatingSystem class cannot retrieve the version number of previously installed service packs. However, because all the fixes and functionality found in previous service packs are included in the latest service pack, you will be able to determine the actual code base of the operating system. The code base consists of the operating system (for example, Windows 2000 Professional 5.0.2195) plus any service packs that have been used to upgrade that operating system.

Note

Note

If it is important for auditing purposes to know whether previous service packs were installed, you can use WMI to query the System Event Log for all instances of event 4359. An event with this event code is written to the System Event Log each time a service pack or hot fix is installed.

Two service pack–related properties are available through the Win32_OperatingSystem class. These two properties are shown in Table 8.10.

Table 8.10. Win32_OperatingSystem Service Pack Properties

Property

Description

ServicePackMajorVersion

Major version of the latest service pack installed on the computer.

If the latest service pack is 4 or 4a, the major version is 4. If no service pack has been installed, this value is 0.

ServicePackMinorVersion

Minor version of the latest service pack installed on the computer.

If the latest service pack is 4a, the minor version is a. If the latest service pack is 4, there is no minor version. To ensure that you identify the proper service pack, you must check both the major version and the minor version.

Scripting Steps

Listing 8.8 contains a script that identifies the latest service pack installed on a computer. To carry out this task, the script must perform the following steps:

  1. Create a variable to specify the computer name.

  2. Use a GetObject call to connect to the WMI namespace rootcimv2, and set the impersonation level to “impersonate.”

  3. Use the ExecQuery method to query the Win32_OperatingSystem class.

    This query returns a collection consisting of the operating system currently in use on the computer.

  4. Echo the values of the service pack major version and the service pack minor version.

Example 8.8. Identifying the Latest Installed Service Pack

1 strComputer = "."
2 Set objWMIService = GetObject("winmgmts:" _
3     & "{impersonationLevel=impersonate}!\" & strComputer & "
ootcimv2")
4 Set colOperatingSystems = objWMIService.ExecQuery _
5     ("SELECT * FROM Win32_OperatingSystem")
6 For Each objOperatingSystem in colOperatingSystems
7     Wscript.Echo objOperatingSystem.ServicePackMajorVersion _
8         & "." & objOperatingSystem.ServicePackMinorVersion
9 Next

Enumerating Installed Hot Fixes

A hot fix is a temporary operating system patch produced by the Quick Fix Engineering group at Microsoft. Like service packs, hot fixes represent changes that have been made to a version of Windows after the operating system has been released.

Unlike service packs, hot fixes are not intended for blanket installation on all computers. Instead, they are developed to address very specific problems, often for specific computer configurations. For example, the hot fix Q278438 should be installed only on computers running the Japanese version of Windows 2000 and Adobe PageMaker 6.53 and using a PostScript printer.

In addition, hot fixes represent independent installations that do not depend on other released hot fixes. For example, a hypothetical hot fix 4 would not include the bug fixes and functionality included in hot fixes 1, 2, and 3. In most cases, there would also be no requirement that you install hot fixes 1, 2, and 3 before installing hot fix 4. This makes enumeration of individual hot fixes an important administrative task: to know the exact configuration of a computer, you need to know not only which service packs have been installed but also which individual hot fixes have been installed.

The Win32_QuickFixEngineering class enables you to enumerate all the hot fixes that have been installed on a computer. Table 8.11 lists some of the hot fix properties that can be returned using the Win32_QuickFixEngineering class.

Table 8.11. Win32_QuickFixEngineering Properties

Property

Description

CSName

Local name of the computer system.

Description

Description of the hot fix.

HotFixID

Unique identifier associated with a particular hot fix.

InstallDate

Date the hot fix was installed.

InstalledBy

Person who installed the update.

Scripting Steps

Listing 8.9 contains a script that enumerates the installed hot fixes on a computer. To carry out this task, the script must perform the following steps:

  1. Create a variable to specify the computer name.

  2. Use a GetObject call to connect to the WMI namespace rootcimv2, and set the impersonation level to “impersonate.”

  3. Use the ExecQuery method to query the Win32_QuickFixEngineering class.

    This query returns a collection consisting of all the hot fixes installed on the computer.

  4. For each hot fix installed on the computer, echo the values for properties such as hot fix description, hot fix ID, and the date the hot fix was installed.

Example 8.9. Enumerating Installed Hot Fixes

 1 strComputer = "."
 2 Set objWMIService = GetObject("winmgmts:" _
 3     & "{impersonationLevel=impersonate}!\" & strComputer & "
ootcimv2")
 4 Set colQuickFixes = objWMIService.ExecQuery _
 5     ("SELECT * FROM Win32_QuickFixEngineering")
 6 For Each objQuickFix in colQuickFixes
 7     Wscript.Echo "Computer: " & objQuickFix.CSName
 8     Wscript.Echo "Description: " & objQuickFix.Description
 9     Wscript.Echo "Hot Fix ID: " & objQuickFix.HotFixID
10     Wscript.Echo "Installation Date: " & objQuickFix.InstallDate
11     Wscript.Echo "Installed By: " & objQuickFix.InstalledBy
12 Next

Managing WMI Settings

WMI is an example of a self-instrumented service. This simply means that you can use WMI scripts to monitor, configure, and control the WMI service. In fact, WMI scripts can be used to enumerate and configure the following items:

  • Logging level, file size, and logging folder for the WMI service

  • Backup interval for the WMI repository

  • WMI time-out values

  • Default WMI namespace

The WMI service exposes many of its properties through the Win32_WMISetting class. You can write scripts to return information regarding the configuration of WMI on a computer, such as the error logging level, the location of the WMI repository, or a list of .mof files that will automatically be reinstalled if the repository becomes corrupted.

Table 8.12 includes some of the more commonly used properties found in the Win32_WMISetting class.

Table 8.12. Win32_WMISetting Properties

Property

Description

ASPScriptDefaultNamespace

Default script namespace. Contains the namespace used by calls from the WMI Scripting API if one is not specified by the caller. On most computers, the default namespace is rootcimV2.

AutoRecoverMOFs

List of fully qualified Managed Object Format (MOF) file names used to initialize or recover the WMI repository. The list determines the order in which MOF files are compiled.

BackupInterval

Length of time that will elapse between backups of the WMI database.

BackupLastTime

Time that the last backup of the WMI repository was performed.

BuildVersion

Version information for the currently installed WMI service. For Windows 2000, the build version is 1085.0005.

DatabaseDirectory

Directory path for the WMI repository.

EnableEvents

Indicates whether or not the WMI event subsystem is enabled.

HighThresholdOnClientObjects

Maximum rate at which provider-created objects can be delivered to clients.

To accommodate speed differentials between providers and clients, WMI holds objects in queues before delivering them to consumers. WMI slows down the addition of new objects into the queue when the low threshold is reached. If this does not help, and high threshold (specified by this property) is reached, WMI accepts no more objects from providers and returns an out-of-memory error to the clients.

HighThresholdOnEvents

Maximum rate at which events are to be delivered to clients.

To accommodate speed differentials between providers and clients, WMI queues events before delivering them to consumers. WMI slows down the addition of new events into the queue when the low threshold is reached. If this does not help, and high threshold (specified by this property) is reached, WMI accepts no more events from providers and returns an out-of-memory error to the clients.

LoggingDirectory

Directory path to the WMI system log files.

LoggingLevel

Indicates whether event logging is enabled and the level of logging used. Values include:

  • 0— No logging

  • 1— Error logging

  • 2— Verbose error logging

LowThresholdOnClientObjects

Rate at which WMI starts to slow the creation of new objects created for clients.

To accommodate speed differentials between providers and clients, WMI holds objects in queues before delivering them to consumers. If the rate of requests for objects grows out of control, WMI gradually slows down the creation of new objects to match the rate used by the client. This slowdown starts when the rate at which objects are being created exceeds the value of this property. The slowdown continues until equilibrium is achieved or the high threshold is reached.

LowThresholdOnEvents

Rate at which WMI starts to slow the delivery of new events.

To accommodate speed differentials between providers and clients, WMI queues events before delivering them to consumers. If the queue grows out of control, WMI slows down the delivery of events gradually to get them in line with the rate used by the client. This slowdown starts when the rate at which events are generated exceeds the value of this property. The slowdown continues until either the equilibrium is achieved or the high threshold is reached.

MaxLogFileSize

Maximum size of the log files produced by the WMI service.

MaxWaitOnClientObjects

Amount of time a newly created object waits to be used by the client before it is discarded and an error value is returned.

MaxWaitOnEvents

Amount of time for which an event sent to a client is queued before being discarded.

MOFSelfInstallDirectory

Directory path for applications that install MOF files to the WMI repository.

WMI automatically compiles any MOF files placed in this directory and, depending on its success, moves the MOF to a subdirectory labeled good or bad.

Enumerating WMI Settings

Knowing how WMI is configured on a computer can be very useful when you are debugging scripts or troubleshooting problems with the WMI service itself. For example, many WMI scripts are written under the assumption that rootcimv2 is the default namespace on the target computer. As a result, script writers who need to access a class in rootcimv2 often fail to include the namespace in the GetObject moniker, as shown in the following code sample:

Set colServices = GetObject("winmgmts:").ExecQuery _
    ("SELECT * FROM Win32_Service")

If rootcimv2 is not the default namespace on the target computer, this script will fail. To prevent this from happening, the namespace rootcimv2 must be included in the moniker, as shown in the following code sample:

Set colServices = GetObject("winmgmts:rootcimv2"). ExecQuery _
    ("SELECT * FROM Win32_Service")

If the default namespace on the target computer is different from the namespace assumed by a script, the script will fail. On top of that, the user will be presented with the somewhat misleading error message “Invalid class.” In truth, the failure is not because the class is invalid but because the class cannot be found in the default namespace. This is a difficult problem to troubleshoot, because you are likely to investigate possible problems with the class rather than problems with the namespace that was (or, in this case, was not) specified.

You can use the Win32_WMISetting class to determine how WMI has been configured on a computer. Configuration details such as the default namespace or the WMI build number can be useful in troubleshooting script problems. These settings also provide important administrative information such as how, or even whether, WMI errors are logged on a computer and which WMI providers will automatically be reloaded if you need to rebuild the WMI repository.

Scripting Steps

Listing 8.10 contains a script that enumerates WMI settings on a computer. To carry out this task, the script must perform the following steps:

  1. Create a variable to specify the computer name.

  2. Use a GetObject call to connect to the WMI namespace rootcimv2, and set the impersonation level to “impersonate.”

  3. Use the ExecQuery method to query the Win32_WMISetting class.

    This query returns a collection consisting of the WMI configuration settings for the computer.

  4. For each group of WMI settings in the collection, echo the value of the specified property.

    Because the autorecover MOFs are stored in an array, a For Each loop must be used to enumerate each MOF.

Example 8.10. Enumerating WMI Settings

 1 strComputer = "."
 2 Set objWMIService = GetObject("winmgmts:" _
 3     & "{impersonationLevel=impersonate}!\" & strComputer & "
ootcimv2")
 4 Set colWMISettings = objWMIService.ExecQuery _
 5     ("SELECT * FROM Win32_WMISetting")
 6 For Each objWMISetting in colWMISettings
 7     Wscript.Echo "Default namespace: " & _
 8         objWMISetting.ASPScriptDefaultNamespace
 9     Wscript.Echo "Backup interval: " & objWMISetting.BackupInterval
10     Wscript.Echo "Last backup: " & objWMISetting.BackupLastTime
11     Wscript.Echo "Build version: " & objWMISetting.BuildVersion
12     Wscript.Echo "Repository directory: " & _
13         objWMISetting.DatabaseDirectory
14     Wscript.Echo "Enable events: " & objWMISetting.EnableEvents
15     Wscript.Echo "High threshold on client objects: " & _
16         objWMISetting.HighThresholdOnClientObjects
17     Wscript.Echo "High threshold on events: " & _
18         objWMISetting.HighThresholdOnEvents
19     Wscript.Echo "Installation folder: " & _
20         objWMISetting.InstallationDirectory
21     Wscript.Echo "Logging folder: " & objWMISetting.LoggingDirectory
22     Wscript.Echo "Logging level: " & objWMISetting.LoggingLevel
23     Wscript.Echo "Low threshold on client objects: " & _
24         objWMISetting.LowThresholdOnClientObjects
25     Wscript.Echo "Low threshold on events: " & _
26         objWMISetting.LowThresholdOnEvents
27     Wscript.Echo "Maximum log file size: " & objWMISetting.MaxLogFileSize
28     Wscript.Echo "Maximum wait time on client objects: " & _
29         objWMISetting.MaxWaitOnClientObjects
30     Wscript.Echo "Maximum wait time on events: " & _
31         objWMISetting.MaxWaitOnEvents
32     Wscript.Echo "MOF Self-install folder: " & _
33         objWMISetting.MofSelfInstallDirectory
34     For Each strMOF in objWMISetting.AutorecoverMofs
35         Wscript.Echo "Autorecover MOF: " & strMOF
36     Next
37 Next

Configuring WMI Settings

The default WMI settings are adequate for most computers and most purposes. Under special circumstances, however, you might want to modify the WMI settings on a computer or a group of computers.

For example, a developer might want to configure WMI to log all errors for the purpose of collecting information that could help in debugging applications that use WMI. A system administrator might want to change the default namespace on the company’s DNS servers from rootcimv2 to rootMicrosoftDNS. Using a script to change settings such as these is much faster than visiting each computer and manually reconfiguring the WMI service.

You can use the Win32_WMISetting class to reconfigure many of the WMI properties on a computer. Several of the configurable WMI settings are shown in Table 8.13.

Table 8.13. Configurable WMI Settings in the Win32_WMISetting Class

Property

Description

ASPScriptDefaultNamespace

Default script namespace. The default is rootcimv2. You must specify the entire namespace path, including root.

BackupInterval

Length of time that will elapse between backups of the WMI database. The default is 30 minutes.

EnableEvents

Boolean value indicating whether the WMI event subsystem is enabled. By default, EnableEvents is set to True.

HighThresholdOnClientObjects

Maximum rate at which provider-created objects can be delivered to clients. The default value is 20,000,000 objects per second.

HighThresholdOnEvents

Maximum rate at which events are to be delivered to clients. The default value is 2,000,000 event objects per second.

LoggingDirectory

Directory path to the WMI system log files. The default is systemrootWBEMLogs.

LoggingLevel

Indicates whether event logging is enabled and the verbosity level of logging used. By default, logging is disabled (set to 0). Values include:

  • 0— No logging

  • 1— Error logging

  • 2— Verbose error logging

LowThresholdOnClientObjects

Rate at which WMI starts to slow the creation of new objects created for clients. The default value is 10,000,000 objects per second.

LowThresholdOnEvents

Rate at which WMI starts to slow the delivery of new events. The default value is 1,000,000 event objects per second.

MaxLogFileSize

Maximum size of the log files produced by the WMI service. The default value is 65536 KB.

MaxWaitOnClientObjects

Amount of time a newly created object waits to be used by the client before it is discarded and an error value is returned. The default value is 60,000 milliseconds (60 seconds).

MaxWaitOnEvents

Amount of time for which an event sent to a client is queued before being discarded. The default value is 2,000 milliseconds (2 seconds).

Scripting Steps

Listing 8.11 contains a script that configures WMI settings on a computer. To carry out this task the script must perform the following steps:

  1. Create a variable to specify the computer name.

  2. Use a GetObject call to connect to the WMI namespace rootcimv2 and set the impersonation level to “impersonate.”

  3. Use a GetObject call to connect to the Win32_WMISetting class.

  4. Set the BackupInterval property to 60 minutes.

  5. Set the LoggingLevel to 2 (verbose).

  6. Use the Put_ method to apply the changes.

Example 8.11. Configuring WMI Settings

 1 strComputer = "."
 2 Set objWMIService = GetObject("winmgmts:" _
 3     & "{impersonationLevel=impersonate}!\" & strComputer & "
ootcimv2")
 4 Set colWMISettings = objWMIService.ExecQuery _
 5     ("SELECT * FROM Win32_WMISetting")
 6 For Each objWMISetting in colWMISettings
 7     objWMISetting.BackupInterval = 60
 8     objWMISetting.LoggingLevel = 2
 9     objWMISetting.Put_
10 Next

Managing Software

The software life cycle provides an administrative framework for managing software within your organization. In the software life cycle, software is:

  • Installed

  • Maintained

  • Upgraded

  • Removed

WMI scripts can be used to install, upgrade, or remove software. Although the Software Installation and Maintenance component of Group Policy remains the preferred method for carrying out these activities, there are occasions when a scripted deployment offers advantages over Group Policy. For example, software deployment changes made by using Software Installation and Maintenance take effect only when a computer is restarted or when a user logs on, not as part of the regular Group Policy refresh. This is done to prevent loss of data; for example, any number of problems could arise if a user were in the middle of editing a document with Microsoft Word at the very moment that a new Group Policy object began to remove Word from the computer.

Note

Note

A WMI script can also attempt to remove an application while that application is currently in use, which can lead to similar problems. Because of this, you might want to use the Win32_Process class to determine which applications are running before you install, upgrade, or remove software using WMI. For more information about the Win32_Process class, see “Processes” in this book.

A computer that is never restarted will never have this new Group Policy applied, and the software will never be installed, upgraded, or removed. WMI, by contrast, allows you to install, upgrade, or remove software without requiring a computer to be restarted or requiring a user to log off and then log back on.

WMI scripts can also carry out tasks such as taking inventory of all the software installed on a computer. Because Software Installation and Maintenance is not designed to perform tasks such as these, administrators have had to purchase and use third-party software to do such things as software inventory.

In addition, WMI enables you to monitor and manage the use of software in your organization, provided the software was installed by using the Windows Installer. Windows Installer, introduced in Windows 2000, represents a new and improved way to install software by using .msi files known as packages. These packages contain all the information necessary to set up an application in every conceivable situation. In addition, Windows Installer maintains a database on each computer detailing the software and software features that have been installed on that computer. WMI has the ability to access this database and report back on the software and software features present on a computer.

Enumerating Software

Taking inventory of the software installed on a computer is as important as taking inventory of the hardware installed on a computer. A software inventory helps you:

  • Understand how computers are being used in your organization.

  • Prevent problems associated with users running unauthorized software or software that is incompatible with other software used in your organization.

  • Ensure compliance with software licensing agreements.

In the past, administrators taking software inventories had to purchase third-party tools or use a brute force approach to taking inventory. With the brute force approach, all the .exe and .com files on a computer (any files that potentially represent executable files for software programs) are retrieved. In most cases, this is far more information than you can use. For example, on a typical Windows 2000 Professional–based computer running Microsoft Office and several other software applications, the brute force approach returns 1,742 .exe files. The amount of data returned, and the fact that the only information returned is the file name, can make it hard to determine the actual (and perhaps most meaningful) software products that have been installed on the computer. Among the problems you face when trying to analyze this data are the following:

  • Applications such as Microsoft Word are difficult to distinguish from self-extracting archive files or system files that might also have the .exe extension. In fact, the vast majority of the file names returned are operating system files that are essentially meaningless in an inventory. Very rarely will you be concerned with knowing whether or not Calc.exe or Attrib.exe is installed on all your computers.

    In addition, having an executable file on your computer does not mean that the application has been installed. You could have a file named Winword.exe yet not have Microsoft Word installed.

  • File names might not provide enough information to identify a software program. Many executable file names have no obvious relationship to the name of the software. For example, is it a good thing or a bad thing that the files Qwinsta.exe and W32mkde.exe were found on your file server?

  • Although a list of 1,742 files might be manageable when working with a single computer, when working with multiple computers the brute force method can result in a huge amount of data.

The WMI Win32_Product and Win32_SoftwareFeature classes allow you to enumerate the software and software features that have been installed on a computer using Windows Installer. Limiting enumeration to software installed by Windows Installer does not provide a complete inventory of the applications installed on a computer. However, this approach does offer several advantages over the brute force method:

  • Data retrieval is held to a minimum.

    On the same Windows 2000–based test computer, a script listing only items that were installed using .msi files returned 77 records instead of the 1,742 items returned using the brute force approach.

  • Data retrieval is limited to manageable software (software installed using Windows Installer).

  • Data retrieval can include important details such as the software version number and a more meaningful description of the software (for example, Microsoft® Visual Studio® instead of Mse.exe).

  • Data retrieval can include other items (such as scripts, templates, and help files) that were installed using Windows Installer but that do not have executable files. This can be extremely useful in organizations that have adopted the Windows Installer format and Group Policy as a way to push documents to user workstations.

Enumerating Installed Software

Knowing the software packages that have been installed on a computer is useful for many reasons. Among other things, this knowledge helps you:

  • Gain insight into what the computer is used for. A computer that does not have a word processor installed is probably not used for writing memos or other documents.

  • Ensuring that only licensed software, and only approved software, is in use in your organization. If your organization has decided to standardize on Microsoft Excel, it is very useful, for both support and legal reasons, to know whether anyone has installed a different spreadsheet program on a computer.

  • Tracking the progress of software deployment projects (for example, the number of people who have installed this new application and the number of people who have not).

  • Planning for future software needs.

These activities cannot be carried out using Group Policy because the Software Installation and Maintenance component does not provide information on the software installed on a computer; it only makes that software available for installation. For example, although the Software Installation and Maintenance component can publish a software package, it provides no way to track which users install that package. This makes it difficult to analyze actual software use or to make projections for future software needs.

The WMI Win32_Product class enables you to enumerate the software installed on a computer, provided the software was installed by using the Windows Installer. Selected properties available through the Win32_Product class are shown in Table 8.14.

Table 8.14. Win32_Product Properties

Property

Description

Caption

Short description of the object.

Description

Object description.

IdentifyingNumber

Product identification, such as a serial number on software.

InstallLocation

Location of the installed product.

InstallState

Installed state of the product. Values include:

  • –6— Bad configuration

  • –2— Invalid argument

  • –1— Unknown package

  •   1— Advertised

  •   2— Absent

  •   6— Installed

Name

Commonly used product name.

PackageCache

Location of the locally cached package for this product.

SKUNumber

Product SKU (stock-keeping unit) information.

Vendor

Name of the product’s supplier.

Version

Product version information.

Scripting Steps

Listing 8.12 contains a script that enumerates the software installed on a computer and then saves the information to a text file. To carry out this task, the script must perform the following steps:

  1. Create an instance of the FileSystem Object.

    This object will be used to write the retrieved software information to a text file.

  2. Create the text file C:ScriptsSoftware.tsv.

  3. Write the field headers to the text file in tab-separated-values format.

    The VBScript constant VbTab is used to insert a tab character between each field header. The tab-separated-values format is used because software property values sometimes contain commas. If they do, these extra commas can make it difficult to parse a text file saved in comma-separated-values format.

  4. Create a variable to specify the computer name.

  5. Use a GetObject call to connect to the WMI namespace rootcimv2, and set the impersonation level to “impersonate.”

  6. Use the ExecQuery method to query the Win32_Product class.

    This query returns a collection consisting of all the software products installed on the computer.

  7. For each software product installed on the computer, retrieve the property values for the application and write those values to the text file, separating each value using a tab character.

  8. Close the text file.

Example 8.12. Enumerating Installed Software

 1 Set objFSO = CreateObject("Scripting.FileSystemObject")
 2 Set objTextFile = objFSO.CreateTextFile("c:scriptssoftware.tsv", True)
 3 strComputer = "."
 4 Set objWMIService = GetObject("winmgmts:" _
 5     & "{impersonationLevel=impersonate}!\" & strComputer & "
ootcimv2")
 6 Set colSoftware = objWMIService.ExecQuery _
 7     ("SELECT * FROM Win32_Product")
 8 objTextFile.WriteLine "Caption" & vbtab & _
 9     "Description" & vbtab & "Identifying Number" & vbtab & _
10     "Install Date" & vbtab & "Install Location" & vbtab & _
11     "Install State" & vbtab & "Name" & vbtab & _
12     "Package Cache" & vbtab & "SKU Number" & vbtab & "Vendor" & vbtab _
13         & "Version"
14 For Each objSoftware in colSoftware
15     objTextFile.WriteLine objSoftware.Caption & vbtab & _
16     objSoftware.Description & vbtab & _
17     objSoftware.IdentifyingNumber & vbtab & _
18     objSoftware.InstallLocation & vbtab & _
19     objSoftware.InstallState & vbtab & _
20     objSoftware.Name & vbtab & _
21     objSoftware.PackageCache & vbtab & _
22     objSoftware.SKUNumber & vbtab & _
23     objSoftware.Vendor & vbtab & _
24     objSoftware.Version
25 Next
26 objTextFile.Close

Enumerating Installed Software Features

Because much of the software developed today allows the user to choose which features to install, enumerating only the software packages might not provide a complete picture of the software installed on that computer. To obtain more detailed information about the software installed on a computer, you might need to enumerate the installed features of each software package, including such things as a dictionary, clip art, and design templates.

You can retrieve a list of software features by using the Win32_SoftwareFeature class. Some of the primary properties of this class are listed in Table 8.15.

Table 8.15. Win32_SoftwareFeature Properties

Property

Description

Accesses

Number of times the software feature has been used.

Attributes

Feature execution option. Values include:

  • 0— Install components locally if possible.

  • 1— Install components to run from the source CD/server if possible.

  • 2— Follow the remote execution option of the parent feature.

Caption

Short textual description of the object.

Description

Textual description of the object. In practice, this will often return the same value as Caption.

IdentifyingNumber

Product identification, such as a serial number.

InstallDate

Date the feature was installed.

InstallState

Installed state of the product. Values include:

  • –6— Bad configuration

  • –2— Invalid argument

  • –1— Unknown package

  •   1— Advertised

  •   2— Absent

  •   3— Local

  •   4— Source

LastUse

Date and time the software feature was last used. If the application has never been used, this date will typically be January 1, 1980.

Name

Label by which the object is known.

ProductName

Commonly used product name.

Vendor

Name of the product’s supplier.

Version

Product version information.

Scripting Steps

Listing 8.13 contains a script that enumerates the software features installed on a computer. To carry out this task, the script must perform the following steps:

  1. Create a variable to specify the computer name.

  2. Use a GetObject call to connect to the WMI namespace rootcimv2, and set the impersonation level to “impersonate.”

  3. Use the ExecQuery method to query the Win32_SoftwareFeature class.

    This query returns a collection consisting of all the software features for all the software products installed on the computer.

  4. For each feature in the collection, echo the appropriate properties.

Example 8.13. Enumerating Installed Software Features

 1 strComputer = "."
 2 Set objWMIService = GetObject("winmgmts:" _
 3     & "{impersonationLevel=impersonate}!\" & strComputer & "
ootcimv2")
 4 Set colFeatures = objWMIService.ExecQuery _
 5     ("SELECT * FROM Win32_SoftwareFeature")
 6 For each objFeature in colFeatures
 7     Wscript.Echo "Accesses: " & objFeature.Accesses
 8     Wscript.Echo "Attributes: " & objFeature.Attributes
 9     Wscript.Echo "Caption: " & objFeature.Caption
10     Wscript.Echo "Description: " & objFeature.Description
11     Wscript.Echo "Identifying Number: " & objFeature.IdentifyingNumber
12     Wscript.Echo "Install Date: " & objFeature.InstallDate
13     Wscript.Echo "Install State: " & objFeature.InstallState
14     Wscript.Echo "Last Use: " & objFeature.LastUse
15     Wscript.Echo "Name: " & objFeature.Name
16     Wscript.Echo "Product Name: " & objFeature.ProductName
17     Wscript.Echo "Vendor: " & objFeature.Vendor
18     Wscript.Echo "Version: " & objFeature.Version
19 Next

Installing, Upgrading, and Removing Software

As part of the software life cycle, software must be installed, upgraded, and removed. These activities can be carried out using Software Installation and Maintenance. Sometimes, however, you might need to perform these actions without using Group Policy. For example, you might want to install, upgrade, or remove software:

  • Without restarting the computer or without logging the user off and back on.

    The Software Installation and Maintenance component policies are refreshed only when a computer restarts or a user logs on. These policies are not affected by the automatic Group Policy refresh rate. If they were, you could encounter a scenario in which Group Policy attempts to remove an application while it is being used.

  • On only one or two computers.

    Creating a Group Policy object (GPO) to manage software installation and maintenance on a single computer involves more administrative overhead than performing the activity directly on the computer. Applying Group Policy to a single computer would require you to:

    1. Create the Group Policy object.

    2. Create a security group.

    3. Add the computer as the sole member of the security group.

    4. Create a filter to ensure that the GPO is applied only to the new security group.

    5. Apply the GPO.

WMI provides the Win32_Product Install, Uninstall, and Upgrade methods to perform these tasks without using Group Policy and without restarting the computers.

Installing Software on the Local Computer

The ability to install software without using Group Policy can be an enormous boon to administrators; this allows you to install software without requiring user interaction and without requiring the user to log off and log on or the computer to restart. In addition, a WMI script can help ensure a successful installation by doing such things as checking for available memory or available disk space before beginning the installation process. If there is not enough memory or disk space on the target computer, your script can terminate without installing the software. This prevents any problems that can occur from attempting to install software on computers not capable of running that software.

The Win32_Product class includes an Install method that can be used to install software on the local computer. (In other words, the script physically resides on the computer where the software will be installed.) Software can also be installed on remote computers; however, because remote installation might require some additional configuration, the remote installation process is discussed in the next section of this chapter.

Regardless of whether the software is installed locally or remotely, the Install method requires three parameters:

  • PackageLocation. Path to the Installer package, which is relative to the computer on which the software is being installed and which can be referenced using a Universal Naming Convention (UNC) path.

  • Options. Command-line options required for installing the software. If no options are required, this parameter should be left blank.

  • AllUsers. Boolean value that indicates whether the software should be available to all the users on a computer or just the currently logged-on user.

    • If set to True, the software will be installed under the All Users profile.

    • If set to False, the software will be installed under the profile of the user whose credentials are being used to run the script. For example, if the script is running under the Administrator account, the software will be installed under the Administrator profile and thus will not be accessible to other users.

Scripting Steps

Listing 8.14 contains a script that installs software for all users on a computer. To carry out this task, the script must perform the following steps:

  1. Create a constant ALL_USERS and assign it the value True. This constant is used to install the software in the All Users profile.

  2. Use a GetObject call to connect to the WMI service.

  3. Retrieve an instance of the Win32_Product class.

  4. Use the Install method to install the Windows Installer package. This method requires the following three parameters:

    • C:ScriptsDatabase.msi —The location of the software package being installed

    • Null —Indicates that no command-line options are required to install the product

    • ALL_USERS —Constant (with the value True) that installs the software under the All Users profile

Example 8.14. Installing Software

 1 Const ALL_USERS = True
 2 Set objService = GetObject("winmgmts:")
 3 Set objSoftware = objService.Get("Win32_Product")
 4 errReturn = objSoftware.Install("c:scriptsdatabase.msi", , ALL_USERS)

Installing Software on a Remote Computer

Installing software remotely frees technical support personnel for other duties (such as installing new hardware) that cannot be carried out remotely. Remote software installation also enables you to install software from a central site, without having to copy the scripts and the Installer packages to each computer. Although you can use WMI to install software on remote computers, you must be aware of the potential security issues involved in performing these remote installations.

When you use the Win32_Product class to install software on a remote computer, you might receive an Access denied error message, even though you have full administrative rights to the remote computer. This can occur in a scenario with three computers involved, as follows:

  • You are running a script from your computer (Computer A).

  • The script is designed to install software on a second computer (Computer B).

  • The Windows Installer package for the software to be installed is stored on a third computer (Computer C).

The Access Denied error message occurs because of the way distributed security works in Windows 2000. When your script (running on Computer A) begins the software installation process, it connects to Computer B by using your user credentials. Assuming you are an administrator, you can perform any operation you want on Computer B. This is known as single-hop security because the security credentials used to start the script from your computer are being used on one remote computer (a single hop from your computer to the remote computer). If the installation process requires no more than two computers, then the software can be installed on a remote computer using the same procedure used to install software on the local computer.

However, suppose the Windows Installer package is located on a third computer, Computer C. To access the package, the WMI service on Computer B must connect to Computer C. This involves multihop security:

  1. Computer A passes the script credentials to Computer B.

  2. Computer B must then present security credentials to Computer C in order to access the Windows Installer package.

The problem occurs in step 2, when you might expect the script to present your security credentials. (This is multihop security because the credentials must pass through several points.) By default, multihop security is not supported in WMI scripting. This means that Computer B does not pass your security credentials on to Computer C. Instead, the WMI service makes this network connection using the LocalSystem account of Computer B. Because a LocalSystem account has no network credentials, it is denied access to the computer storing the Windows Installer package (Computer C). Because the package cannot be retrieved, the script fails.

By default, you can use your security credentials to connect to a remote computer. However, without additional configuration, that remote computer cannot use your security credentials to connect to a third computer. Default security is limited to a single hop.

There are several ways to work around this problem:

  • Run the script using delegation, which allows remote Computer B to pass your user credentials to Computer C.

  • Copy the Windows Installer package to the remote computer, and then install the software, referencing the local path. The script copies the Windows Installer package from Computer A to Computer B, installs the software, and then deletes the package. Security is then limited to a single hop.

    This method works, but it creates additional network traffic as the Windows Installer package is copied between computers.

  • Allow the computer hosting the Windows Installer share to accept Null sessions.

    This method is not recommended because allowing a computer to accept Null sessions is a potential security risk: It opens the door for anyone on the network to connect to a computer.

Trusting Users and Computers for Delegation

To implement multihop security, you must do the following:

  • Make sure that all the computers involved in the procedure have been trusted for delegation. This is a property of the Active Directory® directory service computer account.

  • Make sure the user account that will be employed in the operation is also configured for delegation.

You can use Active Directory Users and Computers to trust both users and computers for delegation.

Scripting Steps

Listing 8.15 contains a script that installs software on a remote computer. Because this script installs software that is stored locally (and not on a third computer), delegation is not required.

To carry out this task, the script must perform the following steps:

  1. Create a variable to specify the name of the remote computer (atl-dc-02).

  2. Use a GetObject call to connect to the WMI namespace rootcimv2, and set the impersonation level to “impersonate.”

  3. Retrieve an instance of the Win32_Product class on the remote computer.

  4. Install the software, referencing the local path where the Windows Installer package is stored.

  5. Echo the success or failure of the installation.

Example 8.15. Installing Software on a Remote Computer

1 strComputer = "atl-dc-02"
2 Set objWMIService = GetObject("winmgmts:" _
3     & "{impersonationLevel=impersonate}!\" & strComputer & "
ootcimv2")
4 Set objSoftware = objWMIService.Get("Win32_Product")
5 errReturn = objSoftware.Install("c:scriptsdatabase.msi",,True)
6 Wscript.Echo errReturn

Upgrading Software

As new versions of a software package are released, you might need to upgrade existing copies of that software. These upgrades can be carried out using the Win32_Product Upgrade method.

The Upgrade method works only under the following conditions:

  • It is used only with a software upgrade package.

    Upgrade packages are .msi files specifically designed to upgrade a previous version of the software. If you attempt to use a standard Windows Installer package with the Upgrade method, you will receive an error message 1636:

    This patch package could not be opened. Contact the application vendor to
    verify that this is a valid Windows Installer patch package.
    
  • A previous version of the product is already installed.

    The Upgrade method will fail if a previous version of the software is not found. For example, to upgrade a computer from version 1 to version 2 of an application, version 1 must first be installed on that computer. If it is not, the upgrade will fail, and version 2 will not be installed.

In turn, the Upgrade method requires two parameters:

  • PackageLocation. Path to the Windows Installer upgrade package, relative to the computer on which the software is being installed. The path can be referenced using UNC paths or mapped network drives.

  • Options. Command-line options required for installing the software. If no options are required, this parameter should be left blank.

Scripting Steps

Listing 8.16 contains a script that upgrades an application called Personnel Database on a computer. To carry out this task, the script must perform the following steps:

  1. Create a variable to specify the computer name.

  2. Use a GetObject call to connect to the WMI namespace rootcimv2, and set the impersonation level to “impersonate.”

  3. Use the ExecQuery method to query the Win32_Product class.

    Because the upgrade is targeted toward a particular piece of software, include a WHERE clause to limit data retrieval to installed applications with the name Personnel Database. Without this clause, the Upgrade method would be applied (unsuccessfully) to each application installed on the computer.

  4. For each instance of Personnel Database in the collection, call the Upgrade method, specifying the path to the Installer file. This path must be relative to the computer on which the upgrade will take place.

Note

Note

If you are upgrading software on a remote computer and the Installer file is located on a third computer, you need to reference the UNC path to the file and use delegation to allow the computer being upgraded to connect over the network and retrieve that file. For information about using delegation, see “Installing Software on a Remote Computer” earlier in this chapter.

Example 8.16. Upgrading Software

1 strComputer = "."
2 Set objWMIService = GetObject("winmgmts:" _
3     & "{impersonationLevel=impersonate}!\" & strComputer & "
ootcimv2")
4 Set colSoftware = objWMIService.ExecQuery _
5     ("SELECT * FROM Win32 Product WHERE Name = 'Personnel Database'")
6 For Each objSoftware in colSoftware
7     errReturn = objSoftware.Upgrade("c:scriptsdatabase2.msi")
8 Next

Removing Software

Software installation is rarely permanent; instead, software is typically removed at some point in time, and for any number of reasons:

  • The functionality supplied by the software is no longer needed.

  • The software is being replaced by a competing software package.

  • The software is installed on the wrong computer.

  • The software is not licensed for use in the organization.

The Win32_Product Uninstall method can be used to remove software from a computer. The Uninstall method can be used either on the local computer or on a remote computer, and without delegation. This is because no multihop security operations are involved. Instead, the software is simply removed from the computer.

Although the Uninstall method can remove software from a computer, it does not override Group Policy. For example, if Microsoft Excel has been installed on a computer, you can use the Uninstall method to remove it. However, if Microsoft Excel is available to the user through Group Policy, the user will be able to reinstall the application.

Scripting Steps

Listing 8.17 contains a script that deletes software on a computer. To carry out this task, the script must perform the following steps:

  1. Create a variable to specify the computer name.

  2. Use a GetObject call to connect to the WMI namespace rootcimv2, and set the impersonation level to “impersonate.”

  3. Use the ExecQuery method to query the Win32_Product class.

    Because only one software package is to be deleted, include a WHERE clause to limit data retrieval to installed applications with the name Personnel Database. Otherwise, the script would remove all the software installed on the computer.

  4. For each instance of Personnel Database in the collection, call the Uninstall method to remove the software.

Example 8.17. Removing Software

1 strComputer = "."
2 Set objWMIService = GetObject("winmgmts:" _
3     & "{impersonationLevel=impersonate}!\" & strComputer & "
ootcimv2")
4 Set colSoftware = objWMIService.ExecQuery _
5     ("SELECT * FROM Win32_Product WHERE Name = 'Personnel database'")
6 For Each objSoftware in colSoftware
7     objSoftware.Uninstall()
8 Next

Managing Computer States

Computers are dynamic entities. The exact configuration and set of resources available on a system are constantly changing. Software is installed and then removed; files are created and deleted; memory is allocated and then released.

Many of these dynamic changes, such as the creation and deletion of temporary files, are of little interest to administrators. Others, however, are of considerable interest. For example, administrators need to know when computers are shut down and restarted. After all, if a server shuts down unexpectedly, the resources provided by that server will be unavailable until it has been restarted.

Likewise, administrators need to know when computers switch from regular power sources to backup power sources. A computer that switches to battery power will be operational only as long as the battery lasts. Steps must be taken to correct the problem before the battery runs out and the computer shuts down.

In addition, administrators typically configure computers so that specific actions are carried out in specific situations. If the power fails, you might want to ensure that a multiple-boot computer is restarted by using a specific operating system. If a server encounters an unrecoverable error, you might want to ensure that a detailed record is made of what the computer was doing at the time the error occurred.

WMI provides a number of classes, properties, and methods that enable administrators to monitor, configure, and, in some cases, trigger changes in computer state. In particular, you can:

  • Manage and configure computer startup settings.

  • Manage and configure computer recovery settings.

  • Monitor computer shutdowns, and remotely shut down or restart a computer.

  • Monitor changes in computer power status (for example, a computer that switches from its primary power source to battery power).

Managing Computer Startups

Multiple operating systems can be installed on a single computer. Although servers are rarely configured in this way, workstations occasionally have multiple operating systems installed. For example, developers often do work on multi-boot computers for convenience in testing applications on different platforms. Workstations might need multiple operating systems if users need an application that runs only under a previous version of Windows. In addition, workstations are likely to have both the Windows operating system and the Windows Recovery Console installed.

As a system administrator, it is important to know:

  • Which operating systems have been installed on a computer.

  • Which operating system is loaded by default each time the computer is started.

  • Whether users are given enough time to load an alternate operating system during startup.

This information enables you to know what will happen to a computer anytime it is restarted.

The Windows Startup Process

When you start a Windows-based computer, it loads the operating system by using the following process:

  1. The computer runs a power-on self test (POST) that determines the amount of real memory installed on the computer and verifies the presence of required hardware components such as the keyboard.

  2. NTLDR, the bootstrap loader for the operating system, reads the file Boot.ini and displays the bootstrap loader screen, which is based on information found in Boot.ini.

    The screen display looks similar to the following:

    Please select the operating system to start:
    Windows 2000 Professional
    Windows 2000 Professional Recovery Console
    Use ↓ and  ↑ to move the highlight to your choice.
    Press ENTER to choose.
    Seconds until highlighted choice will be started automatically: 29
    For troubleshooting and advanced startup options for Windows 2000, press F8.
    
  3. NTLDR counts down the seconds. (By default, a user has 30 seconds in which to choose an operating system.)

  4. If the user does not select an entry before the counter reaches 0, NTLDR loads the default operating system specified in Boot.ini.

Enumerating Computer Startup Options

The computer startup options include such key items as:

  • The default operating system to be loaded by a computer.

  • Alternate operating systems installed on a computer.

  • The time-out period during which a user can select an alternate operating system.

The Win32_ComputerSystem class can be used to enumerate the startup properties for a computer. The properties available through this class are shown in Table 8.16.

Table 8.16. Win32_ComputerSystem Properties for Enumerating Startup Options

Property

Description

AutomaticResetBootOption

Boolean value indicating whether the automatic restart option is enabled.

AutomaticResetCapability

Boolean value indicating whether the computer is capable of automatic restart.

BootupState

Value indicating the current startup mode of the computer. Fail-safe boot (also called SafeBoot) bypasses the user’s startup files. This property must have a value.

Values are:

  • Normal boot

  • Safe mode

  • Safe mode with network support

SystemStartupDelay

Time to delay (in seconds) before starting the operating system.

SystemStartupOptions

Array containing the options for starting up the Win32® computer system. On a multiple-boot computer with both Windows XP and Windows 2000 Advanced Server installed, the SystemStartupOptions might look like this:

""Microsoft Windows XP Professional"
/fastdetect",""Microsoft Windows 2000 Advanced
Server" /fastdetect"

SystemStartupSetting

Index of the default operating system, as determined by the Boot.ini file. This value is calculated so that it usually returns 0 because during startup the selected operating system is physically moved to the top of the list. (This is how the computer determines which value is the default.)

Scripting Steps

Listing 8.18 contains a script that enumerates the startup options on a computer. To carry out this task, the script must perform the following steps:

  1. Create a variable to specify the computer name.

  2. Use a GetObject call to connect to the WMI namespace rootcimv2, and set the impersonation level to “impersonate.”

  3. Use the ExecQuery method to query the Win32_ComputerSystem class.

  4. Echo the value of each startup option in the collection.

Example 8.18. Enumerating Startup Options

 1 strComputer = "."
 2 Set objWMIService = GetObject("winmgmts:" _
 3     & "{impersonationLevel=impersonate}!\" & strComputer & "
ootcimv2")
 4 Set colStartupCommands = objWMIService.ExecQuery _
 5     ("SELECT * FROM Win32_ComputerSystem")
 6 For Each objStartupCommand in colStartupCommands
 7     Wscript.Echo "Reset Boot Enabled: " & _
 8         objStartupCommand.AutomaticResetBootOption
 9     Wscript.Echo "Reset Boot Possible: " & _
10         objStartupCommand.AutomaticResetCapability
11     Wscript.Echo "Boot State: " & objStartupCommand.BootupState
12     Wscript.Echo "Startup Delay: " & objStartupCommand.SystemStartupDelay
13     For Each strOption in objStartupCommand.SystemStartupOptions
14         Wscript.Echo "Startup Options: " & strOption
15     Next
16     Wscript.Echo "Startup Setting: " & _
17         objStartupCommand.SystemStartupSetting
18 Next

Configuring Computer Startup Options

Administrators can control both the default operating system loaded by a computer and the amount of time that users are given to choose an alternate operating system when the computer starts. This allows administrators to:

  • Specify the default operating system on computers that have multiple operating systems installed.

  • Minimize (or maximize) the amount of time it takes for a computer to start.

    If the operating system wait time is set to 0 seconds, the computer automatically loads the default operating system without giving the user an opportunity to choose an alternate system. This can help prevent users from choosing a valid but typically inappropriate operating system such as the Windows 2000 Recovery Console. It also helps the computer start faster because the computer does not have to wait for 30 seconds before it begins to load the operating system.

The selection of the operating system to be loaded when a computer starts is based on the information stored in the Boot.ini file. The Boot.ini file includes two sections:

  • Boot loader. Specifies the default operating system and the number of seconds NTLDR will wait before loading the default system.

    On a typical Windows-based computer, the Boot loader section looks similar to the following:

    [boot loader]
    timeout=30
    default=multi(0)disk(0)rdisk(0)partition(1)WINNT
    
  • Operating systems. Specifies the operating systems that can be loaded.

    On a server running Windows 2000, the Operating systems section might look similar to the following:

    [operating systems]
    multi(0)disk(0)rdisk(0)partition(1)WINNT="Microsoft Windows 2000 Server"
    /fastdetect
    

The Win32_ComputerSystem class allows you to programmatically configure the time-out value or the default operating system by setting the properties shown in Table 8.17.

Table 8.17. Win32_ComputerSystem Properties for Configuring Startup Options

Property

Description

SystemStartupDelay

Specifies the number of seconds to wait before NTLDR loads the default operating system.

SystemStartupSetting

Specifies the index value of the operating system to be set as the default. The first operating system listed is item 0, with additional operating systems numbered consecutively.

For example, in the following Boot.ini, there are two operating systems: Microsoft Windows XP Professional (with the index value 0), and Microsoft Windows 2000 Professional (with the index value 1).

[operating systems]
multi(0)disk(0)rdisk(0)partition(1)WINDOWS="Microsoft
Windows XP Professional" /fastdetect
C:WINNT="Microsoft Windows 2000 Professional"

If you specify an incorrect value (for example, if you specify index 4 when only two operating systems are included), the script will fail with an out-of-range error.

The relationship between the Win32_ComputerSystem properties and the Windows graphical user interface are shown in Figure 8.4.

Startup Options and the Startup and Recovery Page

Figure 8.4. Startup Options and the Startup and Recovery Page

Note

Note

You cannot use WMI to add or remove items to or from the Operating Systems portion of Boot.ini. This must be done by directly editing Boot.ini.

Scripting Steps

Listing 8.19 contains a script that configures the system startup delay on a computer. To carry out this task, the script must perform the following steps:

  1. Create a variable to specify the computer name.

  2. Use a GetObject call to connect to the WMI namespace rootcimv2, and set the impersonation level to “impersonate.”

  3. Use the ExecQuery method to query the Win32_ComputerSystem class.

  4. For each computer in the collection, set the SystemStartupDelay to 10 seconds.

  5. Use the Put_ method to apply the changes.

Example 8.19. Configuring the System Startup Delay

1 strComputer = "."
2 Set objWMIService = GetObject("winmgmts:" _
3     & "{impersonationLevel=impersonate}!\" & strComputer & "
ootcimv2")
4 Set colStartupCommands = objWMIService.ExecQuery _
5     ("SELECT * FROM Win32 ComputerSystem")
6 For Each objStartupCommand in colStartupCommands
7     objStartupCommand.SystemStartupDelay = 10
8     objStartupCommand.Put_
9 Next

After running this script, the Boot.ini will look similar to the following:

[boot loader]
timeout=10
default=multi(0)disk(0)rdisk(0)partition(1)WINNT

Enumerating Computer Startup Commands

Computer startup does not end after the operating system has been loaded. Instead, the Windows operating system can be configured so that startup commands are run each time Windows starts. Startup commands are stored in the registry or as part of the user profile and are used to automatically start specified scripts or applications each time Windows is loaded.

In most cases, autostart programs are useful; they ensure that certain applications, such as antivirus tools, are automatically started and run each time Windows is loaded. However, autostart programs also can be responsible for problems such as:

  • Computers that take an exceptionally long time to start. This might be the result of a large number of applications that must be started each time Windows starts.

  • Applications that are represented in the Taskbar or in Task Manager, even though the user did not start them. Although these applications do not necessarily cause problems, they can result in help desk calls from users who are confused as to where these programs came from and why they are running.

  • Computers experiencing problems even when they seem idle. These problems are often traced to startup commands that are running when no one is aware that they are running.

Identifying the applications and scripts that automatically run at startup is an important but difficult administrative task, because startup commands can be stored in many different locations:

  • HKLMSoftwareMicrosoftWindowsCurrentVersionRun

  • HKLMSoftwareMicrosoftWindowsCurrentVersionRunOnce

  • HKCUSoftwareMicrosoftWindowsCurrentVersionRun

  • HKCUSoftwareMicrosoftWindowsCurrentVersionRunOnce

  • HKUProgIDSoftwareMicrosoftWindowsCurrentVersionRun

  • systemdriveDocuments and SettingsAll UsersStart MenuProgramsStartup

  • systemdriveDocuments and SettingsusernameStart MenuProgramsStartup

You can use the WMI Win32_StartupCommand class to enumerate autostart programs regardless of where the information is stored. A partial set of properties available through the Win32_StartupCommand class is shown in Table 8.18.

Table 8.18. Win32_StartupCommand Properties

Property

Description

Command

Command run by the startup command. For example, “c:windows otepad.exe myfile.txt”.

Description

Description of the startup command.

Location

Path to where the startup command resides in the file system or the registry. For example:

HKLMSOFTWAREMicrosoftWindowsCurrentVersionRun

Name

File name of the startup command.

User

User profile under which this startup command will run.

Scripting Steps

Listing 8.20 contains a script that enumerates the startup commands on a computer. To carry out this task, the script must perform the following steps:

  1. Create a variable to specify the computer name.

  2. Use a GetObject call to connect to the WMI namespace rootcimv2, and set the impersonation level to “impersonate.”

  3. Use the ExecQuery method to query the Win32_StartupCommand class.

    This query returns a collection consisting of all the startup commands on the computer.

  4. For each startup command in the collection, echo the property values.

Example 8.20. Enumerating Computer Startup Commands

 1 strComputer = "."
 2 Set objWMIService = GetObject("winmgmts:"
 3     & "{impersonationLevel=impersonate}!\" & strComputer & "
ootcimv2")
 4 Set colStartupCommands = objWMIService.ExecQuery
 5     ("SELECT * FROM Win32_StartupCommand")
 6 For Each objStartupCommand in colStartupCommands
 7     Wscript.Echo "Command: " & objStartupCommand.Command
 8     Wscript.Echo "Description: " & objStartupCommand.Description
 9     Wscript.Echo "Location: " & objStartupCommand.Location
10     Wscript.Echo "Name: " & objStartupCommand.Name
11     Wscript.Echo "SettingID: " & objStartupCommand.SettingID
12     Wscript.Echo "User: " & objStartupCommand.User
13 Next

Managing Computer Recovery Options

Occasionally a computer encounters an error condition from which it cannot recover. This condition is called a stop event because the computer stops processing when the error occurs. In addition to halting all processing, the computer displays a special kind of error message known as a stop message.

A stop message is often called a stop error or blue screen. The blue screen refers to the fact that the stop message changes the display to a solid blue character-mode background that contains the error message. The message itself consists of the following items:

  • Unique identifier.

  • Series of four hexadecimal numbers that identify error parameters.

  • Symbolic name for the error condition.

  • Additional information related to the problem.

For example, a stop message header might look similar to the following:

           DSR CTS
*** STOP: 0x0000000A  (0x00000000, 0x0000001a, 0x00000000, 0x00000000)
IRQL_NOT_LESS_OR_EQUAL
P4-0300 irql:lf  SYSVER: 0xf000030e
Dll Base DateStmp - Name             Dll Base DateStmp - Name
80100000 2e53fe55 - ntoskrnl.exe     80400000 2e53eba6 - hal.dll

Besides displaying this message, a computer can be configured to take additional actions after a stop event. For example, you can configure a computer to automatically restart after a stop event, or to save a memory dump, a file containing the complete contents of the system memory at the time the stop event occurred. This file can be extremely useful to Microsoft support personnel helping you troubleshoot and resolve the problem.

The WMI Win32_OSRecoveryConfiguration class allows you to both retrieve and configure the recovery options for a computer. A subset of properties available through the Win32_OSRecoveryConfiguration class is shown in Table 8.19. Unless otherwise noted, each of these properties can be modified programmatically.

Table 8.19. Win32_OSRecoveryConfiguration Properties

Property

Description

AutoReboot

Boolean value that indicates whether the system will automatically reboot during a recovery operation.

DebugPathFile

Full path to the debug file. A debug file is created with the memory state of the computer after a computer failure. For example: “C:WindowsMemory.dmp”.

KernelOnlyDump

Specifies that only kernel debug information will be written to the debug log file. If True, only the state of the kernel is written to a file in the event of a system failure. If False, the system will try to log the state of the memory and any devices that can provide information about the system when it failed.

MiniDumpDirectory

Folder where small memory dump files will be recorded and accumulated. For example, “%systemroot%MiniDump”.

Name

Name of the operating system, along with information regarding the file path and disk drive where the operating system has been installed.

For example, a Windows 2000 Professional computer might have a name similar to this:

“Microsoft Windows 2000 Professional|C:WINNT|DeviceHarddisk0Partition1”

This property is read-only.

OverWriteExistingDebugFile

New log file will overwrite an existing one. If this property is False, each new log file will be saved under a unique file name.

SendAdminAlert

Alert message will be sent to the system administrator in the event of an operating system failure.

WriteDebugInfo

Debugging information is to be written to a log file.

WriteToSystemLog

Events will be written to a system log.

The relationship between the Win32_OSRecoveryConfiguration properties and the Windows graphical user interface is shown in Figure 8.5.

Win32_OSRecoveryConfiguration and the Startup and Recovery Page

Figure 8.5. Win32_OSRecoveryConfiguration and the Startup and Recovery Page

Enumerating Computer Recovery Options

Although system administrators often overlook the recovery options, this information can be extremely useful when developing a computer management plan for your organization. For example, the recovery options let you know which troubleshooting aids (such as a debug file) will be available if the computer encounters a stop error. Likewise, these options tell you whether a computer will automatically restart during a recovery operation; if it does not, you will have to manually restart it if problems occur. Knowing how these options are configured can also help you estimate how long the recovery process takes and give you a better idea of how long it will be before a given computer will be available if it encounters an unrecoverable error.

Note

Note

The actual time required to create a memory dump file depends on several factors, including the amount of memory installed on a computer and the type of dump file being created. At least, however, you know that it will take much longer to write a complete memory dump file than it will to write a small memory dump file.

You can use the Win32_OSRecoveryConfiguration class to enumerate the recovery options for a computer.

Scripting Steps

Listing 8.21 contains a script that enumerates the recovery configuration options for a computer. To carry out this task, the script must perform the following steps:

  1. Create a variable to specify the computer name.

  2. Use a GetObject call to connect to the WMI namespace rootcimv2, and set the impersonation level to “impersonate.”

  3. Use the ExecQuery method to query the Win32_OSRecoveryConfiguration class.

    This query returns a collection consisting of the operating system recovery operation settings for the computer.

  4. For each set of recovery options in the collection, echo the specified property value.

Example 8.21. Enumerating the Recovery Configuration Options for a Computer

 1 strComputer = "."
 2 Set objWMIService = GetObject("winmgmts:" _
 3     & "{impersonationLevel=impersonate}!\" & strComputer & "
ootcimv2")
 4 Set colRecoveryOptions = objWMIService.ExecQuery _
 5     ("SELECT * FROM Win32_OSRecoveryConfiguration")
 6 For Each objOption in colRecoveryOptions
 7     Wscript.Echo "Auto reboot: " & objOption.AutoReboot
 8     Wscript.Echo "Debug File Path: " & objOption.DebugFilePath
 9     Wscript.Echo "Kernel Dump Only: " & objOption.KernelDumpOnly
10     Wscript.Echo "Name: " & objOption.Name
11     Wscript.Echo "Overwrite Existing Debug File: " & _
12         objOption.OverwriteExistingDebugFile
13     Wscript.Echo "Send Administrative Alert: " & objOption.SendAdminAlert
14     Wscript.Echo "Write Debug Information: " & objOption.WriteDebugInfo
15     Wscript.Echo "Write to System Log: " & objOption.WriteToSystemLog
16 Next

Configuring Computer Recovery Options

You can configure a computer to take specific actions if it encounters an unrecoverable error condition. The actions you specify affect how long it takes to restart a computer and how much information will be available for diagnosing the cause of the error condition. This enables you to balance the need for recording information about the error condition (which can take a considerable amount of time, depending on how much memory is installed on the computer) with the need to have the computer operational as soon as possible.

You can control the amount of time required to restore a computer to full functionality by configuring the type of memory dump file that is written when the computer encounters an unrecoverable error condition. The different memory dump types vary greatly in the size of the file they generate; in turn, this affects the time it takes to write the file and the time it takes to restart the computer. (File sizes are also affected by the amount of memory installed on a computer.) Table 8.20 shows the relative sizes of the memory dump files on a Windows 2000–based computer with 512 MB of RAM.

Table 8.20. Relative Sizes of Memory Dump Files

Recovery Option

Size of Dump File

Complete memory dump

512 MB

Kernel memory dump

244 MB

Small memory dump

64 KB

In addition to specifying the type of memory dump file to be generated, you can control other recovery options such as:

  • The folder in which memory dump files are stored.

  • Whether error condition events are saved in the System Event log.

  • Whether each new memory dump file is given a unique file name or whether new files overwrite existing memory dump files.

The Win32_OSRecoveryConfiguration class can be used to configure the recovery options for a computer. The properties available through this class are shown in Table 8.19.

Scripting Steps

Listing 8.22 contains a script that modifies the recovery configuration on a computer. To carry out this task, the script must perform the following steps:

  1. Create a variable to specify the computer name.

  2. Use a GetObject call to connect to the WMI namespace rootcimv2, and set the impersonation level to “impersonate.”

  3. Use the ExecQuery method to query the Win32_OSRecoveryConfiguration class.

    This query returns a collection consisting of all the operating system recovery settings for the computer.

  4. For each set of recovery options in the collection, set the DebugFilePath to C:ScriptsMemory.dmp.

  5. For each set of recovery options in the collection, configure the OverWriteExistingDebugFile property to False.

    If a debug file is found, it will not be overwritten.

  6. Use the Put_ method to apply the changes.

Example 8.22. Modifying the Recovery Configuration on a Computer

 1 strComputer = "."
 2 Set objWMIService = GetObject("winmgmts:" _
 3     & "{impersonationLevel=impersonate}!\" & strComputer & "
ootcimv2")
 4 Set colRecoveryOptions = objWMIService.ExecQuery _
 5     ("SELECT * FROM Win32_OSREcoveryConfiguration")
 6 For Each objOption in colRecoveryOptions
 7     objOption.DebugFilePath = "c:scriptsmemory.dmp"
 8     objOption.OverWriteExistingDebugFile = False
 9     objOption.Put_
10 Next

Querying the Event Log for Stop Events

Tracking stop events and the details about those stop events can help you determine whether a particular problem is endemic to one computer or if it is occurring on other computers in your organization. Because stop events are recorded in the System Event log, you can create a script that periodically queries the System Event log on a computer or set of computers and checks to see whether any stop events have occurred.

Each time a stop event occurs, a record is saved with the following parameters:

  • EventType = Information

  • EventCode = 1001

  • SourceName = Save Dump

The event description will look similar to the following:

The computer has rebooted from a bugcheck. The bugcheck was: 0x000000e2
(0x00000000, 0x00000000, 0x00000000, 0x00000000). Microsoft Windows 2000
[v15.2195]. A dump was saved in: C:WINNTMEMORY.DMP.

You can use the Win32_NTLogEvent class to periodically query the System Event Log and retrieve the details of each stop event.

Scripting Steps

Listing 8.23 contains a script that queries the System Event Log for all stop events. To carry out this task, the script must perform the following steps:

  1. Create a variable to specify the computer name.

  2. Use a GetObject call to connect to the WMI namespace rootcimv2, and set the impersonation level to “impersonate.”

  3. Use the ExecQuery method to query the Win32_NTEventLog class.

    Include a WHERE clause to limit the records retrieved only to those events found in the System Event Log that have the source name Save Dump.

  4. For each record in the collection, echo the time the event occurred and the event message.

Example 8.23. Querying the System Event Log for Stop Events

 1 strComputer = "."
 2 Set objWMIService = GetObject("winmgmts:" _
 3     & "{impersonationLevel=impersonate}!\" & strComputer & "
ootcimv2")
 4 Set colLoggedEvents = objWMIService.ExecQuery _
 5     ("SELECT * FROM Win32_NTLogEvent WHERE Logfile = 'System'" _
 6         & " AND SourceName = 'SaveDump'")
 7 For Each objEvent in colLoggedEvents
 8     Wscript.Echo "Event date: " & objEvent.TimeGenerated
 9     Wscript.Echo "Description: " & objEvent.Message
10 Next

Generating a Stop Event

Before you configure recovery options on a production computer, it is helpful to know the actual impact of these options. In particular, you will want to know the size of the dump file that will be generated and how much time it takes the computer to create the dump file and restart. To see what happens to a particular computer if a stop event occurs, you can add an entry to the registry and manually generate a stop event.

Caution

Caution

Changing the registry with a script can easily propagate errors. The scripting tools bypass safeguards, allowing settings that can damage your system, or even require you to reinstall Windows. Before scripting changes to the registry, test your script thoroughly and back up the registry on every computer on which you will make changes. For more information about scripting changes to the registry, see the Registry Reference on the Microsoft Windows 2000 Server Resource Kit companion CD or at http://www.microsoft.com/reskit.

CautionTo add an entry to the registry

  1. Start Regedit.exe.

  2. Navigate to the subkey HKLMSystemCurrentControlSetServicesi8024prtParameters.

  3. Select the Parameters subkey, and then click Add Value from the Edit menu.

  4. In the Add Value dialog box, in the Value Name box type CrashOnCtrlScroll, in the Data Type box select Reg_DWORD, and then click OK.

  5. Double-click the CrashOnCtrlScroll entry. In the DWORD Editor dialog box, type 1 in the Data box and then click OK.

  6. Close Regedit.exe, and restart your computer.

After the computer has restarted, you can generate a stop event.

CautionTo manually generate a stop event

  • Press and hold the right Ctrl key (the left Ctrl key will not allow you to generate a stop event), and then press the Scroll Lock key twice.

    A stop event will occur, and a stop error will be displayed with the following message:

    *** STOP: 0x000000E2 (0x00000000, 0x00000000, 0x00000000, 0x00000000)
    The end-user manually generated the crashdump.
    

After generating a stop event, the computer will be inoperable until it has been restarted. After the restart, complete functionality will be restored.

Shutting Down Computers and Logging Off Users

For more efficient management of computers in an organization, administrators need the ability to remotely shut down or restart a computer, or to remotely log off a user. The ability to carry out these tasks allows administrators to install software, reconfigure computer settings, remove computers from the network, and perform other tasks without having to manually shut down or restart each computer.

For example, to perform a network upgrade, you might need to shut down all the computers running on a particular network segment. To force a Group Policy upgrade, you need to log users off their computers. If a computer virus is present anywhere in your organization, you might want to shut down as many computers as possible, before the virus has an opportunity to spread. The ability to shut down and restart computers and to log off users programmatically instead of manually can be an enormous time-saver.

Shutdowns, restarts, and logoffs can be performed using the Win32Shutdown method of the Win32_OperatingSystem class along with one of the parameters shown in Table 8.21.

Table 8.21. Win32Shutdown Method Parameters

Value

Description

0

Logoff. Logs the user off the computer. Logging off stops all processes associated with the security context of the process that called the exit function, logs the current user off the system, and displays the logon dialog box.

1

Shutdown. Shuts down the computer to a point where it is safe to turn off the power. (All file buffers are flushed to disk, and all running processes are stopped.) Users see the message, It is now safe to turn off your computer.

During shutdown the system sends a message to each running application. The applications perform any cleanup while processing the message and return True to indicate that they can be terminated.

2

Reboot. Shuts down and then restarts the computer.

4

Forced logoff. Logs the user off the computer immediately and does not notify applications that the logon session is ending. This can result in a loss of data.

5

Forced shutdown. Shuts down the computer to a point where it is safe to turn off the power. (All file buffers are flushed to disk, and all running processes are stopped.) Users see the message, It is now safe to turn off your computer.

When the forced shutdown approach is used, all services, including WMI, are shut down immediately. Because of this, you will not be able to receive a return value if you are running the script against a remote computer.

6

Forced reboot. Shuts down and then restarts the computer.

When the forced reboot approach is used, all services, including WMI, are shut down immediately. Because of this, you will not be able to receive a return value if you are running the script against a remote computer.

8

Power off. Shuts down the computer and turns off the power (if supported by the computer in question).

12

Forced power off. Shuts down the computer and turns off the power (if supported by the computer in question).

When the forced power off approach is used, all services, including WMI, are shut down immediately. Because of this, you will not be able to receive a return value if you are running the script against a remote computer.

Note

Note

The Win32Shutdown method does not have a parameter for locking a workstation, leaving the user logged on. However, workstations can be locked from the command line by using the following command:

%windir%System32
undll32.exe user32.dll,LockWorkStation

To shut down a computer, your script must include the Shutdown privilege. For more information about including privileges within a WMI script, see “WMI Scripting Primer” in this book.

Shutting Down a Computer

Computers occasionally need to be removed from the network, perhaps for scheduled maintenance, because the computer is not functioning correctly, or to complete a configuration process. For example, if a DHCP server is handing out erroneous IP addresses, you might want to shut the computer down until a service technician can be dispatched to fix the problem. If you suspect that a security breach has occurred, you might need to shut down certain servers to ensure that they cannot be accessed until the security issue has been resolved. Some configuration operations (such as changing a computer name) require you to restart the computer before the change takes effect.

A computer can be shut down using the Win32Shutdown method, specifying 1 as the parameter value. Passing 1 as a parameter indicates that the computer should be shut down. Other parameters specify different actions, such as restarting the computer or logging off the user. For a complete list of parameter values, see Table 8.21.

For computers that support the ability to be programmatically powered off, you can specify 8 as the parameter value. Passing 8 as the parameter shuts down the computer and also turns off the power.

Scripting Steps

Listing 8.24 contains a script that shuts down a computer. To carry out this task, the script must perform the following steps:

  1. Create a constant named SHUTDOWN and set the value to 1.

    This constant specifies that the computer should be shut down.

  2. Create a variable to specify the computer name.

    In Listing 8.24, the computer name is set to “.” which will result in the local computer being shut down. To shut down a remote computer, simply set the variable to the appropriate computer name.

  3. Use a GetObject call to connect to the WMI namespace rootcimv2, and set the impersonation level to “impersonate.”

  4. Use to the ExecQuery method to return a collection consisting of all instances of the Win32_OperatingSystem class.

    The Shutdown privilege must be specified as part of the GetObject moniker. If it is not, the script will fail and the computer will not be shut down. The Shutdown privilege is required to shut down a computer by using WMI. However, including the privilege within the moniker does not ensure that the script will succeed. In addition to inclusion of the privilege within the moniker, the user under whose credentials the script is running must also have permission to shut down the computer.

  5. For each operating system in the collection, use the Win32Shutdown method, specifying the constant SHUTDOWN (with the value 1) for the method parameter.

To shut down, but not power off, the computer, use the value 1 as the method parameter. Other values will result in other actions. For example, the value 0 will log the user off but will not shut down the computer.

Example 8.24. Shutting Down a Computer

1 Const SHUTDOWN = 1
2 strComputer = "."
3 Set objWMIService = GetObject("winmgmts: {(Shutdown)}" _
4     & "{impersonationLevel=impersonate}!\" & strComputer & "
ootcimv2")
5 Set colOperatingSystems = objWMIService.ExecQuery _
6     ("SELECT * FROM Win32_OperatingSystem")
7 For Each objOperatingSystem in colOperatingSystems
8     ObjOperatingSystem.Win32Shutdown(SHUTDOWN)
9 Next

When the script in Listing 8.24 runs, the computer is shut down, the user is logged off, all processes are stopped, and the screen displays the message:

"It is now safe to shut down your computer."

However, the computer remains powered on unless manually turned off.

Restarting a Computer

The ability to programmatically restart a computer allows administrators to perform many computer management tasks remotely. For example, if you create a script to install software or make a configuration change that requires restarting a computer, you can include the restart command in the script and perform the entire operation remotely.

The Win32_OperatingSystem class includes a Reboot method that can be used to restart a computer. Like the Win32Shutdown method, the Reboot method requires the user whose security credentials are being used by the script to possess the Shutdown privilege. In addition, the Shutdown privilege must be explicitly included in the script moniker.

Scripting Steps

Listing 8.25 contains a script that restarts a computer. To carry out this task, the script must perform the following steps:

  1. Use a GetObject call to connect to the Win32_OperatingSystem class. This call returns a collection consisting of the operating system currently in use on the computer.

    Because restarting a computer requires the Shutdown privilege, this privilege must be included as part of the moniker.

  2. For each operating system in the collection, use the Reboot method to restart the computer.

Example 8.25. Restarting a Computer

1 strComputer = "."
2 Set objWMIService = GetObject("winmgmts:" _
3     & "{impersonationLevel=impersonate,(Shutdown)}!\" & _
4         strComputer & "
ootcimv2")
5 Set colOperatingSystems = objWMIService.ExecQuery _
6     ("SELECT * FROM Win32_OperatingSystem")
7 For Each objOperatingSystem in colOperatingSystems
8     objOperatingSystem.Reboot()
9 Next

Monitoring Changes in Computer Power Status

Changes in power status often indicate that a problem has occurred with a computer or with another managed device. If a server suddenly switches from AC power to an uninterruptible power supply, this change can indicate that an electrical problem of some kind has occurred, either with the computer itself or with the electrical system in the room in which the computer is kept.

Administrators need to monitor these changes in power status and be notified of such changes immediately. This enables them to take action before the device loses power entirely. (Uninterruptible power supply systems, for example, might run for only 15 minutes or so before shutting down.)

The Win32_PowerManagementEvent class can be used to monitor changes in power status on a computer. These changes can include a switch from one power source to another as well as a change in computer power state (for example, entering or exiting Suspend mode).

The Win32_PowerManagementEvent class has only two properties: EventType, used to indicate the type of power change event that occurred, and OEMEventType, which is used by some original equipment manufacturers to define additional power change events. The values for the EventType property are shown in Table 8.22.

Table 8.22. Win32_PowerManagementEvent Event Types

EventType Value

Description

4

Entering Suspend. Indicates that the computer is about to enter the suspended state.

While suspended, the computer appears to be off; however, it can be “awakened” in response to various events, including user input (such as moving the mouse or pressing a key on the keyboard). While the computer is suspended, power consumption is reduced to one of several levels depending on how the system is to be used. The lower the level of power consumption, the more time it takes the system to return to the working state.

When the computer enters the suspend state, the desktop is locked, and you must press CTRL+ALT+DELETE and provide a valid user name and password to resume operations.

7

Resume from Suspend. Indicates that a ResumeSuspend message has been sent, enabling the computer to return to its regular power state.

10

Power Status Change. Indicates a change in the power status of the computer, such as a switch from battery power to AC, or from AC to an uninterruptible power supply. The system also broadcasts this event when remaining battery power slips below the threshold specified by the user or if the battery power changes by a specified percentage.

11

OEM Event. Indicates that an Advanced Power Management (APM) BIOS has sent an OEM event.

The value of the event will be captured in the OEMEventCode property. Because some APM BIOS implementations do not provide OEM event notifications, this event might never be broadcast on some computers.

APM is the legacy power management scheme that was first widely supported in Windows 95. Although still supported in Windows 2000 and Windows XP, APM has been largely superseded by ACPI (Advanced Configuration and Power Interface).

18

Resume Automatic. Indicates that the computer has awakened in response to an event. If the system detects user activity (such as a mouse click), the ResumeSuspend message will be broadcast, letting applications know that they can resume full interactivity with the user.

Scripting Steps

Listing 8.26 contains a script that monitors changes in power status on a computer. To carry out this task, the script must perform the following steps:

  1. Use a GetObject call and an ExecNotification query to monitor for changes in power status.

    This query looks for new instances of the Win32_PowerManagementEvent class.

  2. When a power change event occurs, echo the event type.

Example 8.26. Monitoring Changes in Power Status

1 Set colMonitoredEvents = GetObject("winmgmts:")._
2     ExecNotificationQuery("SELECT * FROM Win32_PowerManagementEvent")
3 Do
4     Set strLatestEvent = colMonitoredEvents.NextEvent
5     Wscript.Echo strLatestEvent.EventType
6 Loop
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset