Components of a Class

Microsoft® Windows® 2000 Scripting Guide

microsoft windows 2000 scripting guide

« Previous | Next »   

Every hardware and software resource that is manageable through WMI is defined by a class. A class is a blueprint (or template) for a discrete WMI-managed resource, and all instances of the resource use the blueprint. These means, for example, that all services (which are instances of the Win32_Service class) will have the same properties. This does not mean that they will have the same property values; for example, Alerter has the Name Alerter, while the WMI service has the Name Winmgmt. However, all services have a Name property.

Note

  • This is true even if no value has been configured for a property. For example, all services have the Description property, although there is no requirement that all services actually have a description. If a property is valid but has not been configured, WMI will return the value Null. This prevents a script from crashing should it encounter a property with no configured value.

Classes represent the things computers have. Because computers have disks, event logs, files, folders, memory, printers, processes, processors, services, and so on, WMI has classes for disks, event logs, files, folders, memory, printers, processes, processors, services, and so on. Although there are exceptions (such as __Event abstract system classes), most classes that are used in scripting can be directly tied to real things.

These blueprints consist of properties, methods, and qualifiers. Before examining properties, methods, and qualifiers, it is useful to learn where managed resource class definitions originate.

Suppose Microsoft decides to create a new WMI provider that system administrators can use to manage and monitor Microsoft DNS servers. At a minimum, the DNS provider development team would need to create two files: a provider and something called a Managed Object Format (MOF) file.

The provider is the dynamic-link library (DLL) that acts as the intermediary between the WMI infrastructure and the underlying managed resource the Microsoft DNS server in this case. The provider services WMI requests by calling the native APIs of the managed resource.

The MOF file contains the class definitions that describe the capabilities provided by the DNS provider. The MOF file describes the capabilities of the DNS provider, using classes that model resources commonly associated with a DNS server. DNS servers have such things as zones and resource records; thus, you might expect to see classes such as MicrosoftDNS_Zone and MicrosoftDNS_ResourceRecord defined in the MOF file. Each class defined in the DNS MOF file defines the data (properties) associated with a specific DNS-related resource and the actions (methods) you can perform on that resource. For example, a resource record has a time-to-live (TTL) property. Therefore, you might expect the MicrosoftDNS_ResourceRecord class to have a property such as TTL.

When the DNS provider is installed, the DNS provider DLL is registered with the operating system and WMI, and the DNS MOF file undergoes a compilation process. This loads the DNS provider class definitions into the CIM repository. At this point, the DNS provider can be used by any WMI-enabled consumer, including scripts.

As it turns out, this story is true: Microsoft developed a new DNS provider that can be downloaded for Windows 2000. However, the story is not as important as the fact that managed resource class definitions originate in MOF files. MOF files are to WMI what MIB files are to SNMP.

MOF files are text files based on the MOF language created and maintained by the DMTF. The class definition of every managed resource follows a well-defined structure and syntax, as illustrated in Figure 6.3.

Figure 6.3   Structure of a Managed Resource Class Definition

Structure of a Managed Resource Class Definition

Every managed resource class definition consists of properties, methods, and qualifiers. This definition is applied to all instances of a class and determines what can and cannot be done to an instance. For example, with services you can specify actions that will be taken should the service fail (restart the service, restart the computer, run a program, or take no action). These recovery options are not specified anywhere with the class definition. That means that they cannot be managed by using a script.

Properties

Properties are like nouns that describe a managed resource. Classes use properties to describe things such as the identity, configuration, and state of a managed resource. Services, for example, have a name, display name, description, startup type, and status. The Win32_Service class has the same properties.

Each property has a name, a type, and optional property qualifiers. You use the property name in combination with the WMI scripting library SWbemObject to access a property, as demonstrated in Listing 6.1. For example, assuming that objService represents an instance of an installed service, these lines of code echo the service name and the description:

Wscript.Echo objService.Name Wscript.Echo objService.Description 

In the MOF file itself, a property definition looks similar to this, with the name, data type, and qualifier (in this case, the Read qualifier) indicated in boldface:

[read : ToSubclass,MappingStrings{"Win32API|Service Structures|SERVICE_STATUS|dwControlsAccepted|SERVICE_ACCEPT_PAUSE_CONTINUE"} : ToSubclass] boolean AcceptPause; 

Methods

Methods are like verbs that perform an action on a managed resource. Think of the methods of the Win32_Service class in these terms: What can you do with services? You can start services, stop services, pause services, and resume services. As it turns out, there are methods that allow you to start, stop, pause, and resume services.

Each method has a name, a return type, optional parameters, and optional method qualifiers. As with properties, you use the method name in combination with SWbemObject to call a method. For example, this line of code stops the service represented by objService. The error code of the operation will be stored in the variable errReturn and then echoed to the screen (in general, the value 0 means that an operation succeeded, and anything else means the script failed):

errReturn = obService.StopService() Wscript.Echo errReturn 

Not all classes define methods. In Windows 2000, you will find methods implemented in classes such as Win32_Service, Win32_NTEventLogFile, and Win32_Process. In Windows XP, methods are implemented in a number of additional classes, including both new (Win32_DiskQuota) and existing (Win32_Printer) classes.

In the MOF file, a method definition looks similar to this one. The boldface items indicate the fact that the method is implemented (meaning it can be used in scripts), the return codes (ValueMap) used by the method, and the name of the method.

[Implemented,ValueMap{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", ".."} : ToSubclass,MappingStrings{"Win32API|Service Functions|ControlService|dwControl|SERVICE_CONTROL_CONTINUE"} : ToSubclass] uint32 ResumeService();

Qualifiers

Qualifiers are like adjectives that provide additional information about the class, property, or method to which they apply. For example, the Dynamic qualifier answers the question, "What type of class is Win32_Service?" As you begin to write WMI scripts that do more than simply retrieve information (such as modify properties or call methods), qualifiers become increasingly important. This is because they define the operational characteristics of the property you are updating or the method you are calling.

So what kind of information do qualifiers provide? As it turns out, there are three types of qualifiers, providing three types of information.

Class qualifiers

Class qualifiers provide operational information about a class:

  • The Abstract, Dynamic, and Association qualifiers tell you the class type.
  • The Provider qualifier tells you the provider that services the class. For example, the Provider qualifier for the Win32_Service class tells you that the class uses the CIMWin32 provider (cimwin32.dll). On the other hand, the Win32_NTLogEvent class uses the MS_NT_EVENTLOG_PROVIDER provider (ntevt.dll) as indicated by the Win32_NTLogEvent class Provider qualifier.
  • The EnumPrivileges qualifier informs you of special privileges required to use the class. For example, the Win32_NTLogEvent class EnumPrivileges qualifier tells you that SeSecurityPrivilege must be enabled before the Win32_NTLogEvent class can be used to manage the Security log. If this privilege is not specified in the script, the script will not be able to manage the Security event log.

The definition for the Win32_NTLogEvent class in ntevt.mof shows the class type (dynamic), the provider name, and required privileges, all shown in boldface:

[Dynamic,Provider( MS_NT_EVENTLOG_PROVIDER ) : ToInstance,EnumPrivileges{ SeSecurityPrivilege } : ToSubclass,Locale(1033) : ToInstance,UUID("{8502C57C-5FBB-11D2-AAC1-006008C78BC7}") : ToInstance] class Win32_NTLogEvent 

Property qualifiers

Property qualifiers provide information about each property. For example:

  • The CIMType qualifier tells you the property data type. WMI supports a number of data types, including strings, integers, dates and times, arrays, and Boolean values.

    Does it really matter which data type a property is? In the simple examples presented thus far in this chapter, no. However, suppose you connect to the Win32_Printer class and retrieve the value of the Capabilities property. This property stores values as an array; consequently, simply echoing the property value (like this) results in a "Type mismatch" error:

    Wscript.Echo objPrinter.Capabilities 

    Instead, you have to loop through the individual elements in the array, like this:

    For Each intCapability in objPrinter.Capabilities     Wscript.Echo intCapability Next 
  • The Read qualifier indicates whether the property is readable.
  • The Write qualifier indicates whether you can modify the property value. For example, the Win32_WMISetting ASPScriptDefaultNamespace property modified in Listing 6.9 is marked as writable. This means that you can change the value of the property. On the other hand, all of the Win32_Service properties shown in previous scripts are defined as read-only; that is, they do not define the Write qualifier. In general, this means that these properties cannot be configured using a script. (The only exceptions are those properties where the class provides a method that can configure the values. For example, you can use the ChangeStartMode method to change the start mode for a service, even though the StartMode property is read-only.)
  • The Key qualifier indicates that the property is the class key and is used to identify unique instances of a managed resource in a collection of identical resources. DeviceID is a key property in the Win32_LogicalDisk class. Why? Because device IDs must be unique; a computer can have no more than one C drive. Size is not a key property, because there is no reason why a single computer cannot have multiple drives all the same size.

Method qualifiers

Method qualifiers provide information about each method. For example:

  • The Implemented qualifier indicates that the method has an implementation supplied by a provider. This is important because WMI classes often include methods that are valid but do not actually work (because they have not been implemented). For example, a number of hardware classes include a method named SetPowerState that is a valid method but has not been implemented. Therefore, it cannot actually be used to set the power state of an object.
  • The ValueMap qualifier defines a set of permissible values for a method parameter or return type.
  • The Privileges qualifier informs you of special privileges required to call the method.

Note

  • There are many more qualifiers than those mentioned here. For a complete list, see the WMI Qualifiers topic in the WMI SDK. For information about how to download the WMI SDK, see the Microsoft Windows Management Instrumentation (WMI) SDK link on the Web Resources page at http://www.microsoft.com/windows/reskits/webresources.

Comparing Classes with Managed Resources

Classes determine what you can and cannot do with WMI. If you have a class for services, you can manage services; if you do not have a class for services, you cannot. Consequently, it is important to know which classes are available on a given computer.

Properties and methods are important because the versions of WMI differ among operating systems; the Win32_ComputerSystem class in Windows XP has many new properties and methods not supported by the Win32_ComputerSystem class in Windows 2000. You have to know these details because, unlike Active Directory Service Interfaces (ADSI), the WMI properties and methods must be available on the target computer in order for a script to work.

Note

  • ADSI works as long as ADSI is installed on your computer. The target computer does not have to have the same version of ADSI as you do; in fact, it does not have to have ADSI at all. With WMI, however, this is different. You cannot retrieve information from a remote computer unless both your computer and the remote computer have WMI installed. Similarly, the methods and properties defined in a managed resource s class definition must exist on the remote computer for a script to work. For example, the Win32_Printer class in Windows XP has a method named CancelAllJobs that can purge a print queue. However, this method cannot be used against a Windows 2000-based computer because the Win32_Printer class in Windows 2000 does not support CancelAllJobs. The method must be present on the target computer.

How do you determine whether a property or a method is supported on a remote Windows-based computer? You examine the class definition.

Retrieving Class Definitions

You can use the WMI scripting library to retrieve managed resource class definitions in two different ways:

  • You can use the SWbemObject Qualifiers_, Properties_, and Methods_ properties to retrieve class information.
  • You can use the SWbemObject GetObjectText_ method to retrieve the class definition formatted in MOF syntax.

Using the SWbemObject Properties_, Methods_, and Qualifiers_ properties

Listing 6.14, Listing 6.15, and Listing 6.16 demonstrate how to use the Properties_, Methods_, and Qualifiers_ properties of SWbemObject to retrieve information about the Win32_Service class. All three scripts employ the same basic approach, although there are some differences.

Listing 6.14 begins by initializing three variables: strComputer, strNameSpace, and strClass. The value assigned to strComputer is the target computer. The value assigned to strNameSpace is the namespace to connect to, and the value assigned to strClass is the name of the class whose properties are to be retrieved and displayed.

Separating the three values into multiple variables makes it easy to reuse the script for other computers, namespaces, and classes. In fact, you can easily turn these scripts into command-line scripts by using the WSH Arguments collection. This allows a user to retrieve information about any computer, namespace, or class simply by specifying the appropriate information as a command-line argument. For more information about WSH arguments, see "WSH Primer" in this book.

Next the script uses the VBScript GetObject function to connect to the WMI Service on the target computer. You might have noticed something different about the connection string passed to GetObject. In addition to the target namespace, the class name is also specified. This has a profound impact on what GetObject and the WMI scripting library return. Rather than return a reference to an SWbemServices object, as was the case in the previous scripts, GetObject returns a reference to an SWbemObject representing the target class. How? The answer lies in something called an object path. Although object paths are covered in detail later in this chapter, a quick explanation will help you understand what is going on in these scripts.

Every WMI class and every instance of a WMI-managed resource has an object path. An object path is very similar to the file paths associated with files and folders. A file has a fully qualified path that consists of a device name, followed by zero or more directory names, followed by the file name. Likewise, every class and managed resource has an object path that consists of the computer name, followed by the namespace, followed by the managed resource class name, followed by the class key property and the key property value, as shown here. (Note that the square brackets serve only to delimit the four permissible parts of an object path; they are not part of the object path.)

[\\ComputerName][\Namespace][:ClassName][.KeyProperty='Value']

When you use all or part of an object path in the connection string passed to GetObject, the object path you use determines the type of reference returned. For example, if you include only the computer name portion of an object path, you get back an SWbemServices object reference connected to the default namespace. If you include the computer name or the namespace or both, you also get a reference to an SWbemServices object. If you include the computer name, namespace, and class name, you get back a reference to an SWbemObject representing the class. And if you include all four parts, you get back an SWbemObject representing the managed resource instance identified by the class, key, and value.

The object path elements and the objects returned are summarized in Table 6.4.

Table 6.4   Object Path Elements and Objects Returned

Items Specified in Object PathObject Returned
Computer name:
Set objSWbemServices = _ GetObject("winmgmts:\\WebServer")
SWbemServices (connected to the default namespace)
Computer name and/or namespace: Set objSWbemServices = _ GetObject("winmgmts:\\WebServer\root\cimv2") SWbemServices (connected to the specified namespace root\cimv2)
Computer name, namespace, class name:
Set objSWbemObject = GetObject _ ("winmgmts:\\WebServer\root\cimv2:Win32_Service")
SWbemObject (representing the class Win32_Service)
Computer name, namespace, class name, key property: Set objSWbemObject = GetObject _ ("winmgmts:\\WebServer\root\cimv2:" & _ "Win32_Service.Name='Alerter'") SWbemObject (representing the specific instance, the service named Alerter)

The remainder of the script is reasonably straightforward. After echoing a simple header identifying the class name whose properties are going to be displayed, the script uses the SWbemObject reference (objClass) to access the SWbemObject Properties_ property (objClass.Properties_). The Properties_ property references an SWbemPropertySet, which is the collection of properties for the class. Each property in the collection is an SWbemProperty (objClassProperty) object, which is used to read and echo each property name.

Listing 6.14   Using SWbemObject Properties_ to Retrieve Win32_Service Properties

1 2 3 4 5 6 7 8 9 10 11 12 13 
strComputer = "." strNameSpace = "root\cimv2" strClass = "Win32_Service" Set objClass = GetObject("winmgmts:\\" & strComputer & _                          "\" & strNameSpace & ":" & strClass) Wscript.Echo strClass & " Class Properties" Wscript.Echo "                               " For Each objClassProperty In objClass.Properties_     Wscript.Echo objClassProperty.Name Next

The following is output displaying the names of the 25 properties defined (or inherited) by the Win32_Service class.

Win32_Service Class Properties                               AcceptPause AcceptStop Caption CheckPoint CreationClassName Description DesktopInteract DisplayName ErrorControl ExitCode InstallDate Name PathName ProcessId ServiceSpecificExitCode ServiceType Started StartMode StartName State Status SystemCreationClassName SystemName TagId WaitHint 

Listing 6.15 is identical to Listing 6.14, with one exception: The For Each loop enumerates the SWbemMethodSet collection and displays the Name property for each SWbemMethod (objClassMethod) in the SWbemMethodSet collection.

Listing 6.15   Using SWbemObject Methods_ to Retrieve Win32_Service Methods

1 2 3 4 5 6 7 8 9 10 11 12 13 
strComputer = "." strNameSpace = "root\cimv2" strClass = "Win32_Service" Set objClass = GetObject("winmgmts:\\" & strComputer & _                          "\" & strNameSpace & ":" & strClass) Wscript.Echo strClass & " Class Methods" Wscript.Echo "                           -" For Each objClassMethod In objClass.Methods_     Wscript.Echo objClassMethod.Name Next

The following output displays the names of the 10 methods defined (or inherited) by the Win32_Service class.

Win32_Service Class Methods                            - StartService StopService PauseService ResumeService InterrogateService UserControlService Create Change ChangeStartMode Delete 

Listing 6.16 is identical to Listing 6.14 and Listing 6.15, with three exceptions:

  • The For Each loop enumerates the SWbemQualifierSet collection (by way of the Qualifiers_ property) and echoes the Name property for each SWbemQualifier (objClassQualifier) in the collection.
  • Because class qualifiers are part of the class definition and qualifiers have values, Listing 6.16 also retrieves and echoes the Value property for each SWbemQualifier in the collection.
  • Because a qualifier can have multiple values stored in an array, Listing 6.16 must account for this prior to reading the value of a qualifier. Not doing so would result in a run-time error if the script tried to read an array-based qualifier as a "regular" variable. The Win32_NTLogEvent EnumPrivileges qualifier is an example of an array-based qualifier (although only one value, the privilege SeSecurityPrivilege, is stored in the array).

    This checking is done by using the VBScript function VarType to determine the data type of the variable.

Listing 6.16   Using SWbemObject Qualifiers_ to Retrieve Win32_Service Class Qualifiers

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 
strComputer = "." strNameSpace = "root\cimv2" strClass = "Win32_Service" Set objClass = GetObject("winmgmts:\\" & strComputer & _                          "\" & strNameSpace & ":" & strClass) Wscript.Echo strClass & " Class Qualifiers" Wscript.Echo "                               " For Each objClassQualifier In objClass.Qualifiers_     If VarType(objClassQualifier.Value) = (vbVariant + vbArray) Then         strQualifier = objClassQualifier.Name & " = " & _                        Join(objClassQualifier.Value, ",")     Else         strQualifier = objClassQualifier.Name & " = " & _                        objClassQualifier.Value     End If     Wscript.Echo strQualifier     strQualifier = "" Next

The following output displays the names and values of the five class qualifiers defined (or inherited) by the Win32_Service class.

Win32_Service Class Qualifiers                                 dynamic = True Locale = 1033 provider = CIMWin32 SupportsUpdate = True UUID = {8502C4D9-5FBB-11D2-AAC1-006008C78BC7} 

As you might have noticed, Listing 6.14 and Listing 6.15 do not show you the property and method qualifiers. This was done to keep the scripts to a size that could be easily explained.

Using the SWbemObject GetObjectText_ method

Earlier it was noted that you can retrieve managed resource class definitions directly from the MOF file in which the class is defined. For example, if you want to look up the Win32_Service class, look in the systemroot\System32\Wbem\Cimwin32.mof file. However, using MOF files directly comes with a price. You must examine every class in a class hierarchy to obtain the complete blueprint for the managed resource.

For example, if you want to look up Win32_Service, you have to examine all five classes in the Win32_Service class hierarchy to get the complete picture. This is tedious at best. An easier approach to obtaining the MOF representation of a class is to use the WMI scripting library SWbemObject GetObjectText_ method, as demonstrated in Listing 6.17.

Unlike Listing 6.14 through Listing 6.16, Listing 6.17 uses the SWbemServices Get method rather than GetObject to retrieve the class. The Get method must be used so the wbemFlagUseAmendedQuailifiers flag can be enabled. Enabling this flag tells WMI to return the entire managed resource blueprint (class definition) rather than just the local definition. In other words, the information returned includes only the three properties unique to Win32_Service, and no information is returned for all the properties and methods inherited from other classes.

The Get method returns a reference to an SWbemObject (objClass) representing the target class, which is used to call the GetObjectText_ method. The GetObjectText_ method returns the MOF representation for the class. Had GetObjectText_ been used without enabling the wbemFlagUseAmendedQuailifiers flag, the method would have only returned those properties, methods, and qualifiers defined by Win32_Service; inherited properties and methods would have been omitted.

Listing 6.17   Using SWbemObject GetObjectText_ to Retrieve the MOF Representation of the Win32_Service Class

1 2 3 4 5 6 7 8 9 10 11 12 
strComputer = "." strNameSpace = "root\cimv2" strClass = "Win32_Service" Const wbemFlagUseAmendedQualifiers = &h20000 Set objSWbemServices = _     GetObject("winmgmts:\\" & strComputer & "\" & strNameSpace) Set objClass = objSWbemServices.Get(strClass, wbemFlagUseAmendedQualifiers) strMOF = objClass.GetObjectText_ Wscript.Echo strMOF

The output from the script will be similar to this partial output:

[dynamic: ToInstance, provider("CIMWin32"): ToInstance, Locale(1033): Amended, UUID("{8502C4D9-5FBB-11D2-AAC1-006008C78BC7}"): ToInstance, Description("The Win32_Service class represents a service on a Win32 computer system. A service application conforms to the interface rules of the Service Control Manager (SCM) and can be started by a user automatically at system boot through the Services control panel utility, or by an application that uses the service functions included in the Win32 API. Services can execute even when no user is logged on to the system."): ToSubClass Amended] class Win32_Service : Win32_BaseService {    [Description("The Caption property is a short textual description (one-line string) of the object."): ToSubClass Amended] string Caption; 

There is a caveat to using GetObjectText_, however: The method does not return information about inherited qualifiers included in the MOF file. This can present a problem if you want to use GetObjectText_ to determine a Key property when the Key qualifier is defined in a parent class.


send us your feedback Send us your feedback « Previous | Next »   


Microsoft Windows 2000 Scripting Guide(c) Automating System Administration 2003
Microsoft Windows 2000 Scripting Guide(c) Automating System Administration 2003
ISBN: N/A
EAN: N/A
Year: 2004
Pages: 635

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