Windows Management Instrumentation

Purpose

Windows Management Instrumentation (WMI) is the Microsoft implementation of Web-Based Enterprise Management (WBEM), which is an industry initiative to develop a standard technology for accessing management information in an enterprise environment. WMI uses the Common Information Model (CIM) industry standard to represent systems, applications, networks, devices, and other managed components in an enterprise environment.

Where Applicable

WMI can be used in all Windows-based applications; it is most useful in enterprise applications.

Developer Audience

WMI is designed for use by programmers who use C/C++, Microsoft Visual Basic, and scripts. A familiarity with COM programming is required.

Run-time Requirements

Applications that use WMI require Windows NT/Windows 2000, or Windows 95/98. For information on which operating systems are required to use a particular API element, see the Requirements section of the documentation for the function, method, or property.

See Also

Systems Management Server

Overview

General information about WMI.

Reference

Documentation of the WMI COM API, Scripting API, CHString, CHStringArray, and CIM classes.

WMI Application Programming

Information on how to program applications to use WMI.

WMI Provider Programming

Information on how to program WMI providers and documentation on the core WMI providers.

WMI Development Environment

Information on tools and applications provided with the WMI SDK. This section also contains information on utility classes and programmatic access for WMI.

Feedback

Make error reports and feature requests directly to Microsoft.

Built on Friday, October 08, 1999


Windows Management Instrumentation

Legal Information

Windows Management Instrumentation

Information in this document, including URL and other Internet web site references, is subject to change without notice. The example companies, organizations, products, people and events depicted herein are fictitious. No association with any real company, organization, product, person or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property.

©1998-1999 Microsoft Corporation. All rights reserved.

Active Directory, ActiveX, BackOffice, Developer Studio, DirectX, Jscript, Microsoft, MS-DOS, MSDN, Microsoft SQL Server, Visual Basic, Visual C++, Visual J++, Win32, Win32s, Win64, Windows, and Windows NT are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries.

The names of actual companies and products mentioned herein may be the trademarks of their respective owners.


Roadmap to WMI Documentation

Windows Management Instrumentation (WMI) is the Microsoft implementation of Web-Based Enterprise Management (WBEM), which is an industry initiative to develop a standardized technology for accessing management information in an enterprise environment. WMI contributes to the industry-wide drive to lower Total Cost of Ownership.

The WMI SDK documentation includes the following categories:

  • WMI Overview

    Includes high-level information about WMI for all WMI SDK users, including system requirements, architectural information, terms and concepts, high-performance, security issues, and WMI localization. This section also includes information about sample programs included with the WMI SDK.

  • WMI Application Programming

    Includes information on WMI application development, including WMI programming basics and WMI event notification. This section also includes a tutorial that shows how to program a WMI application.

    This section also includes information applicable to network and system administration, including information about the WMI ODBC adapter provided with this SDK and how to manage a network using SNMP. This section also includes overview information about the Scripting API and the WMI ADSI Extension.

  • WMI Provider Programming

    Includes programming basics for WMI Providers. It also includes information on the WMI Providers included with the WMI SDK and the provider framework.

  • WMI Development Environment

    Includes information on ActiveX Controls, WMI applications, Managed Object Format (MOF) Language, and the WMI Query Language. This section also includes information on programmatic access, using DCOM security, and the WMI utility classes.

  • WMI Add-Ons

    Includes information about the WMI add-ons, which extend WMI functionality.

  • WMI Reference

    Includes all reference material for the WMI SDK. This is reference material for:

    WMI System Classes

    WMI System Properties

    WMI Standard Qualifiers

    Provider Framework Classes

    Provider Framework Utility Classes

    COM API for WMI

    Scripting API for WMI

    ActiveX Controls for WMI

    WMI Utility Classes

    SQL for the WMI ODBC Adapter

    MOF Compiler

    BNF Syntax for MOF

    SNMP Compiler Error Messages

    WMI Symbolic Constants

    WMI Command-Line Syntax

    Wbemdump

    WMI Glossary

  • WMI Appendix

    Includes the technical support information and information about how to view the WMI Schema.

To send feedback about this kit, send e-mail to wmi@microsoft.com.


What's New

This section provides information applicable to what has been changed or added into this release of the Windows Management Instrumentation (WMI) SDK. It is important to note that in addition to the following, many optimizations and improvements (including bug fixes) have also been made to the WMI SDK since the Microsoft® Windows® 2000 Beta 3 release.

New section | Description
Windows 2000 Kerberos Security support | Describes the Kerberos support provided by WMI.
WMI Localization | Describes the localization of WMI classes.
WQL Query Builder Tool | WMI CIM Studio now includes a WMI Query Language (WQL) based querying tool. The WQL Query Builder lets you write, save, and execute WMI WQL queries.
Schema Validation Wizard Tool | WMI CIM Studio now includes a Schema Validation Wizard, which verifies that a schema is both CIM and WMI compliant. The wizard conducts additional checks not covered by the MOF compiler.
High Performance API | You can use the high-performance API to write WMI providers that can update information for WMI clients much more rapidly than you can by using standard WMI architecture.
Return Codes | provides a listing of the symbolic constants WMI Error Constants and WMI Non-Error Constants.
IMofCompiler API | Describes the IMofCompiler API.
Performance Counters | A High-Performance API Provider that provides raw counter data, such as the time a disk spends writing data.
Microsoft® ActiveX® redistribution procedures | The WMI SDK now provides the correct procedures to use for redistributing the WMI ActiveX controls. This is covered in Cabinet File Extraction Application.
Log Files | WMI providers create log files that contain trace information and error messages.
Wmi Add-Ons | Late breaking additional WMI components.
Framework Tutorial | A simple step by step tutorial demonstrating how to create a framework provider.
WMI CHString and CHStringArray coverage | WMI has copied both the CString and CStringArray class libraries from the Microsoft Foundation Class (MFC) Library, version 4.0 and renamed them CHString and CHStringArray. Both classes provide the same functionality as their MFC counterparts but eliminate the overhead associated with including MFC libraries.


WMI Overview

Web-Based Enterprise Management (WBEM) provides uniform access to management information. Windows Management Instrumentation (WMI) is the Microsoft implementation of this technology. Such management information includes information on the state of system memory, inventories of currently installed client applications, and other information on client status. Implemented for Microsoft® Windows® platforms, the WMI technology enables systems, applications, networks, and other managed components to be represented using the Common Information Model (CIM) designed by the Distributed Management Task Force (DMTF). CIM can model anything in the managed environment regardless of data source location.

In addition to data modeling, WMI offers a powerful set of base services that include query-based information retrieval and event notification. Access to these services and to the management data is made possible with a single Component Object Model (COM) programming interface.

The WMI software development kit (SDK) includes the tools to create client applications and WMI providers. This overview to the WMI SDK documentation includes the following sections:

Section | Description
System Requirements | Minimum system configurations for WMI.
Architectural Overview | High-level description of the WMI initiative and the components that are part of WMI technology.
Terms and Concepts | Main terms and concepts that are central to WMI.
Using the WMI SDK | Getting started using the WMI SDK.
High-Performance Interface | Information on increasing the speed of WMI clients.
WMI Localization | Adding localized qualifiers to WMI classes.
Security and Authentication | WMI security support for Microsoft® Windows® operating systems.


System Requirements

The Windows Management Instrumentation (WMI) SDK requires the following minimum system configurations:

  • Software Requirements
  • Compiler Requirements
  • Hardware Requirements


Software Requirements

This release of the Windows Management Instrumentation (WMI) SDK supports the following:

  • Microsoft® Windows NT® version 4.0 Service Pack 5 or later, including Microsoft® Windows® 2000
  • Microsoft® Internet Explorer version 5 or later

    Internet Explorer can be downloaded at no cost from the Microsoft Web site at http://www.microsoft.com/ie

Note The WMI operating system components are supported on Windows NT 4.0 with Service Pack 4 or later, including Windows 2000, and on Windows 95 OSR2 and Windows 98.


Compiler Requirements

Although the Microsoft WMI SDK will work with most compilers, Microsoft only supports the Microsoft® Visual C++® version 6.0 development environment.

The .idl and .h files included with the WMI SDK are intended for use with Visual C++ 6.0 compilers. These files require editing before use with compilers from vendors other than Microsoft.


Hardware Requirements

Minimum computer configurations exist and are based on the Microsoft operating system used. For development using the Windows Management Instrumentation (WMI) SDK, it is recommended that the developer have a computer that consists of at least:

Pentium Processors

If you are using a Pentium processor, your computer should consist of at least:

  • Pentium-class computer
  • 32 MB RAM
  • 30 MB of available hard disk space
  • Video graphics card support for 256 colors at an 800 by 600 resolution
  • Network card


Architectural Overview

Web-Based Enterprise Management (WBEM) is an initiative undertaken by the Distributed Management Task Force (DMTF) to provide enterprise system managers with a standard, low-cost solution for their management needs. The WBEM initiative encompasses a multitude of tasks, ranging from simple workstation configuration to full-scale enterprise management across multiple platforms. Central to the initiative is the Common Information Model (CIM), an extensible data model for representing objects that exist in typical management environments, and the Managed Object Format (MOF) language for defining and storing modeled data.

Windows Management Instrumentation (WMI) is an implementation of the WBEM initiative for Microsoft® Windows® platforms. By extending the CIM to represent objects that exist in WMI environments and by implementing a management infrastructure to support both the MOF language and a common programming interface, WMI enables diverse applications to transparently manage a variety of enterprise components.

The WMI management infrastructure consists of the following components:

  • The actual WMI software (Winmgmt.exe), a component that provides applications with uniform access to management data.
  • The Common Information Model (CIM) repository, a central storage area for management data.


WMI Architecture

The architecture of the Windows Management Instrumentation (WMI) technology consists of the following components:

  • Management applications
  • Managed objects
  • Providers
  • Management infrastructure, consisting of the WMI software (Winmgmt.exe) and the CIM repository

Management applications are Microsoft® Windows®-based applications or Microsoft® Windows NT®/Windows 2000 services that process or display data from managed objects. A management application can perform a variety of tasks such as measuring performance, reporting outages, and correlating data.

Managed objects are logical or physical enterprise components. Managed objects are modeled using the CIM, and they are accessed by management applications through WMI. A managed object can be any enterprise component, from a small piece of hardware such as a cable to a large software application such as a database system.

Providers use the COM API to supply WMI with data from managed objects, to handle requests on behalf of management applications, and to generate notifications of events. The WMI software development kit (SDK) supplies several standard providers, such as a registry provider, for accessing information from the system registry. The WMI SDK also supplies a Windows NT/Windows 2000 Event Log Provider that allows applications to receive notifications of Windows NT/Windows 2000 events and to access the information stored in the Windows NT/Windows 2000 event log. Third-party vendors can create custom providers to interact with managed objects specific to their environment.

The management infrastructure consists of WMI and the CIM repository. WMI enables users to handle communications between management applications and providers. Users store their static data in the CIM repository. Applications and providers communicate through WMI using a common programming interface (COM API). The COM API, which supplies event notification and query processing services, is available in the C and C++ programming languages.

The CIM repository holds static management data. Static data is data that does not regularly change. WMI also supports dynamic data, which is data that must be generated on demand because it is frequently changing. Data can be placed in the CIM repository by WMI or network administrators. Third-party developers can place information in the CIM repository with either the Managed Object Format (MOF) language and its compiler or the COM API.

The following diagram shows the relationship between the components in the WMI technology. The top of the diagram provides examples of management applications. Some of these applications access the COM API directly to interact with WMI and the CIM repository to make management requests. Other applications use access methods such as Open Database Connectivity (ODBC) and the Hypertext Markup Language (HTML) to make their requests.

The bottom of the diagram illustrates examples of managed objects and their corresponding providers. Again, there is a variety of access methods used for communication.

The protocol used for communication between local and remote components is Distributed Component Object Model (DCOM).


Management Applications

A management application is an application or a Microsoft® Windows NT®/Microsoft® Windows® 2000 service that uses information originating from one or more managed objects. To access the information, a management application makes a request to Windows Management Instrumentation (WMI) through one of the methods in the COM API or Scripting API.

The WMI technology enables management applications to implement a wide range of features such as producing reports of network inventory, displaying system information, responding to events, starting or stopping system services, and sending an eject command to a disk drive with replaceable media. Although some of the features can also be implemented without WMI, much additional work is necessary.

WMI supports a number of different strategies to implement management applications. Applications can access WMI directly through the COM API or Scripting API or indirectly with one of the following access methods:

  • Web browsers can use a set of Microsoft® ActiveX® controls to control the appearance, relationships, and behavior of data relating to managed objects. The controls are customizable and can be included in a standard schema definition.
  • Web browsers also can use HTML, the standard HTML page and hyperlink paradigm. HTML is supported through an Internet Server API (ISAPI) layer that interacts with WMI.
  • Database applications can use the Microsoft ODBC driver to merge the database capabilities of ODBC with the management capabilities of WMI. With the ODBC driver, an application can use a wide range of ODBC-based reporting packages and tools, such as Microsoft® Excel and Microsoft® Access.

The COM API is available directly to C/C++ programmers.

The Scripting API allows you to develop script and Microsoft® Visual Basic®-based applications that you can use to view or control managed objects. WMI also provides scripting support for the following languages:

  • Visual Basic
  • Visual Basic for Applications
  • Visual Basic, Scripting Edition
  • Microsoft® JScript®

The following figure shows management applications of various types communicating with WMI. Two of the applications use one of the access strategies; one communicates directly to WMI.


WMI, Active Directory, and MMC

[This is preliminary documentation and subject to change.]

A complete enterprise level management application typically encompasses these three key components: WMI, Active Directory, and MMC. WMI provides individual computer information, such as the devices that are installed and the software that it is running. Active Directory provides the enterprise view, focusing on information that needs to be available across the network. Together, WMI and the Active Directory let you provide a complete view of your enterpise. Since both sources of information may be necessary to accomplish a given task, WMI includes an Active Directory provider (Directory Services Provider) to access information stored in the Active Directory.

You can then use MMC's common user interface architecture to present this information to the users. Information from WMI, Active Directory and other sources can be combined within MMC to present a cohesive management view. It is recommended that you develop your snap-in to use WMI as its information source. If a WMI provider does not exist that supplies the information you need, you should consider writing the provider. This will allow the information to be available to your snap-in as well as other WMI clients such as C++, Visual Basic and scripting applications.

For an example of how you can integrate WMI with MMC, see the Snap-in sample.


WMI Provider Overview

Windows Management Instrumentation (WMI) providers act as intermediaries between WMI and one or more managed objects. When WMI receives a request from a management application for data that is not available from the CIM repository or for notifications of events that WMI does not support, it forwards the request to a provider. Providers supply data and event notifications for managed objects that are specific to their particular domain.

Providers are standard COM or DCOM servers that can be implemented using the full range of supported server types:

  • In-process dynamic-link libraries (DLLs)
  • Local or remote Microsoft® Windows NT®/Microsoft® Windows® 2000 services
  • Local or remote standard executable files (.exe files)

The WMI SDK includes several built-in providers. The built-in providers, also referred to as standard providers, supply data from well-known sources such as the system registry and the Microsoft® Win32® subsystem.

The WMI technology also supports the creation of custom providers by third-party developers. These providers service requests relating to managed objects that are environment-specific. Providers typically use the MOF language to define and create classes. They use the COM API to access the CIM repository and to respond to WMI requests made initially by applications.

The following diagram illustrates the architecture of providers. The PerfMon Provider, Registry Provider, and WDM Provider are examples of standard providers. Provider X, Provider Y, and Provider Z are examples of custom providers. The standard providers supply WMI and management applications with data from standard managed objects such as the PerfMon application, the system registry, and Windows Driver Model (WDM) devices. The custom providers supply WMI and applications with data from custom managed objects. Both the standard and custom providers can access data from the CIM repository through the COM API.

The WMI technology categorizes providers by the different features that they support. Every provider can support one or more feature set. For each feature, a different method is implemented. There are basically two types of providers: those that support data retrieval and modification, and those that support event notification. Providers can be categorized further as in the following table.

Provider type | Description
Class | Retrieves, modifies, deletes, and/or enumerates a provider-specific class. It can also support query processing.
Instance | Retrieves, modifies, deletes, and/or enumerates the instances of system and/or provider-specific classes. It can also support query processing.
Property | Retrieves and/or modifies individual property values.
Method | Invokes methods for a provider-specific class.
Event | Generates notifications of events.
Event consumer | Supports event notification by mapping a physical consumer with a logical consumer.

Each of the features listed for the property, instance, and class providers are optional. These providers can choose to support one or more of the possible features. Providers indicate which features they support through the registration process and through their implementation of the corresponding method in the COM API. A provider that does not support a particular feature returns WBEM_E_NOT_SUPPORTED from the corresponding method.

However, to avoid making unnecessary calls, WMI always checks a provider's registration first to determine if it can handle a request. If WMI detects that the provider cannot handle the request because it does not support a feature, WMI never makes the request.


Common Information Model (CIM)

The Common Information Model (CIM) presents a consistent and unified view of all types of logical and physical objects in a managed environment. Managed objects are represented using object-oriented constructs such as classes. The classes include properties that describe data and methods that describe behavior. Designed by the Distributed Management Task Force (DMTF) as part of the Web-Based Enterprise Management (WBEM) initiative, the CIM is not tied to any particular platform. The Windows Management Instrumentation (WMI) technology includes an extension of the CIM for the Microsoft® Windows® operating system platforms.

The CIM defines three levels of classes:

  • Classes representing managed objects that apply to all areas of management. These classes provide a basic vocabulary for analyzing and describing managed systems. They are part of what is called the core model.
  • Classes representing managed objects that apply to specific management areas but are independent of a particular implementation or technology. These classes are part of what is called the common model, which is an extension of the core model.
  • Classes representing managed objects that are technology-specific additions to the common model. These classes typically apply to specific platforms such as UNIX or the Microsoft® Win32® environment.

All classes can be related by inheritance, where a child class includes data and methods from its parent class. Inheritance relationships typically are not visible to the management application using them. These applications are not required to know the inheritance hierarchy. Class hierarchies can be obtained using applications that are included in the WMI SDK. For more information, see WMI SDK Applications.

WMI also supports association classes. Association classes link two other classes to model a user-defined relationship. Association relationships are visible to management applications. WMI defines association classes to support system classes. Third-party developers can also define association classes for their management environment.

WMI supports the concept of schemas to group the classes and instances that are used within a particular management environment. The WMI SDK includes two schemas: the CIM schema and the Win32 schema. The CIM schema contains the class definitions for the first two levels of the CIM. These classes represent managed objects that are part of every management environment regardless of platform. The Win32 schema contains class definitions for managed objects that are part of a typical Win32 environment.

Third-party developers can create their own custom schemas to describe vendor-specific environments. Because schemas are meant to be infinitely extensible, developers can always add new classes to represent new managed objects in an existing environment. Custom schemas are extensions of the CIM or Win32 schema.


WinMgmt.exe

WinMgmt.exe is the primary component in the management infrastructure of Windows Management Instrumentation (WMI) technology. On computers running Microsoft® Windows® 98, WinMgmt.exe runs as a standard executable file. In computers running Windows 2000, WinMgmt.exe runs as a service. In both cases, WinMgmt.exe starts when the first management application makes a call to connect. WinMgmt.exe is activated when the first client application successfully connects and runs continuously as long as management applications actively seek its services.

On computers running Windows 2000 or Windows 98, WinMgmt.exe runs in one of two modes, as either a manual or an automatic service. As an automatic service, WinMgmt.exe goes into a low memory profile state (unloads the major COM DLLs) when all the clients depart. As a manual service, WinMgmt.exe waits 30 seconds and shuts down when all clients are done.

For more information, see WMI Command-Line Syntax..

WMI supports two programming interfaces known as the COM API for WMI and the Scripting API for WMI. The COM API is used by management applications, providers, and schema extensions. The COM API, which enables these components to interact with WMI using C and C++, is based on the Component Object Model (COM). The Scripting API can be used to create client applications with WMI using various scripting languages and Microsoft® Visual Basic®.

When an application makes a request by calling one of the methods in either the COM API or the Scripting API, WMI determines whether the request involves static data stored in the CIM repository, or dynamic data supplied by a provider. Static data can be handled by WMI, whereas dynamic data always involves a provider. Providers register their location and support for particular operations such as data retrieval, modification, deletion, enumeration, or query processing. WMI uses this registration information to match application requests with appropriate providers and to find and load the providers when necessary. When a provider has finished processing a request, it returns the results back to WMI, which, in turn, forwards the result to the application.

WMI ensures that all of the operations specified in the COM API are supported. When an application makes a complex request that a provider cannot handle, WMI supplies the implementation by making an equivalent series of much simpler calls to the provider. WMI is always available to handle a request if a registered provider is unable to do so.

In addition to implementing each of the operations associated with application requests, WMI also supplies the following:

  • Support for event notification
  • Query language support
  • Security support
  • Support for local and remote access

For a complete description of the interfaces in the WMI COM API, see COM API for WMI.

For a description of the interfaces in the Scripting API, see the Scripting API for WMI.


Support for Event Notification

WMI supports the registration for and distribution of event notifications. Event consumers register to receive particular types of notifications. Event providers register to supply particular types of notifications. To enable event consumers to operate independently from event providers, WMI acts as the intermediary, matching registered consumers with corresponding providers and forwarding appropriate events.

WMI supports temporary event consumers and permanent event consumers. Temporary event consumers receive notifications only as long as they are active. When they terminate, their registration is removed. Permanent event consumers receive notifications whenever notifications occur. When a permanent event consumer is registered, WMI does not automatically terminate with the last application; it is automatically restarted after a reboot. WMI must be available at all times to deliver these event notifications.

WMI produces two types of events: timer events and intrinsic events. Timer events occur either periodically, according to a specified time interval, or once at a specified time. Intrinsic events correspond to changes in data stored in the CIM repository.

Whenever possible, providers should implement relevant instrinsic events. This prevents the performance loss which would result from the default polling for this event. For more information on this default polling, see Intrinsic and Extrinsic Events.

Event providers can support a third type of event called an extrinsic event. Although WMI prefers that providers use intrinsic events whenever possible, it is sometimes necessary to create new event types to represent changes to provider-specific managed objects. Events pertaining to provider-specific events are called extrinsic events.

WMI forwards the notifications of all types of events to applications that have registered to receive them. For a detailed description of the event services architecture, see Event Notification.


Query Language Support

WMI currently supports the Windows Management Instrumentation Query Language (WQL) to handle query processing. WQL is a subset of the ANSI standard Structured Query Language (SQL) with WMI-specific extensions. Some extensions support event registration and notification, while others support relationships between classes and instances. WQL is a read-only query language in that it cannot be used to update, insert, or delete data. WQL can only be used to retrieve information.


Security Support

WMI supports a limited form of security that positively identifies and validates each user before the user is allowed to connect to WMI. Validated users are granted access to all of the WMI classes, instances, and namespaces. WMI does not support protection of individual classes or instances. WMI supports security for individual namespaces. See Per Namespace Security for more information.

On Microsoft® Windows NT®/Windows 2000 platforms, there is no distinction between local and remote access. However, with a remote connection, users can specify a user name and password, replacing the current user name and password. With a local connection, users cannot override the current name and password.

On Windows 95 and Windows 98 platforms, local users are considered administrators and are granted full rights. There is no authentication. Remote users, however, are validated using instances of WMI system classes.

Administrators can use the WMI Control application (Wbemcntl.exe) to set permissions for WMI users.

For more information about WMI security, see Security and Authentication.


Support for Local and Remote Access

When an application attempts to connect to WMI, the normal COM or DCOM proxy is loaded to make the connection. On the server side, COM loads the interface stub, performs user-level authentication, and completes the connection.


Terms and Concepts

The Web-Based Enterprise Management (WBEM) technology uses terms and concepts conceived by the Distributed Management Task Force (DMTF) to describe managed objects, standard Component Object Model (COM) terms, and WBEM-specific terms. Windows Management Instrumentation (WMI) is the Microsoft implementation of the WBEM technology. This topic includes the following information:

  • Information about the components of a WMI class: its properties, methods, instances, qualifiers, and flavors.
  • Information about the various types of WMI classes: singleton classes, association classes, and system classes.
  • Information about the date and time and interval formats used in WMI applications and providers.
  • Information about how to specify identity through key properties, namespaces, and object paths.

All of the components of a WMI class are treated as case-insensitive. For information about using the Managed Object Format (MOF) language to create classes, instances, and other class components, see Managed Object Format (MOF) Language.

For additional information about WMI architecture, see Architectural Overview.

For information on working with C++ classes and inheritance, and on other terms and concepts related to C++ and object-oriented programming, see the documentation for the Microsoft® Visual C++® development system or other C++ references. For information on the Microsoft® Visual Basic® development system, see the Visual Basic documentation. For information on COM terms and concepts, see the COM Fundamentals documentation in the Platform SDK.


WMI Classes

Windows Management Instrumentation (WMI) classes define the basic units of management. Each class is a template for a type of managed object. All instances of the type use the template. For example, the Win32_LogicalDisk class is a model representing any disk that can exist on a Microsoft® Windows® computer. For each physical disk that exists, there is an instance of the Win32_LogicalDisk class. Classes can contain properties, which describe the data of the class, and methods, which describe the behavior of the class.

WMI enforces several restrictions on the operations that can be performed on classes that have child classes or instances. The following operations are not normally allowed:

  • Changing a property type.
  • Adding or removing a Key or Indexed qualifier.
  • Adding or removing a Singleton, Dynamic, or Abstract qualifier.

Note Under some special circumstances, such as using the WBEM_FLAG_UPDATE_FORCE_MODE flag in a call to IWbemServices::PutClass, it is possible to circumvent these rules.

The WMI technology incorporates classes defined by the Common Information Model (CIM), WMI, the built-in providers included in the WMI SDK, and third-party providers.

The CIM classes describe managed objects that are independent of a particular implementation or technology. CIM classes also describe objects that exist in every managed environment or in managed environments of specific types.

The WMI classes are called system classes. These system classes are not part of the CIM. They are specific to the Microsoft WBEM implementation for Windows platforms, that is, WMI. System classes describe objects that are used to support WMI core features, such as event notification and security. For a complete description of the system classes, see the WMI system classes.

Managers define classes to describe objects that are specific to their managed environment. These classes can be defined as base classes or as subclasses of a CIM class, a system class, or another provider class. For example, the Microsoft® Windows NT®/Windows® 2000 Event Log Provider defines the Win32_NTEventlogFile class to access the data stored in a Windows NT/Windows 2000 log file. This class is derived from the CIM class CIM_DataFile. The Registry Event Provider defines the RegistryTreeChangeEvent class to describe a change to a registry tree. As with all classes used to describe events supported by a provider, RegistryTreeChangeEvent derives from the system class __ExtrinsicEvent. Application writers can define new classes using either the WMI application programming interface (API) or the Managed Object Format (MOF) language.

The names of classes are case-insensitive strings that can never include leading or trailing underscores. Application writers should assign class names using the following convention:

SchemaName_ClassName

The SchemaName portion of the class name specifies the schema to which the class belongs. The schema is a collection of class definitions that describe managed objects in a particular environment. Schema names cannot contain underscore characters, and they must be unique. If an application or provider includes the schema name as a prefix to the class name, users of the class can strip off the schema name when it is implied by context.

The ClassName portion of the class name specifies the name of the class. Class names should be descriptive and cannot include underscore characters. For example, LogicalDisk is a valid WMI class name.

WMI uses the concept of a namespace to logically distinguish between managed environments. Class names must be unique within a namespace. It is also recommended that a specified class name and its methods and properties not conflict with a class of the same name in another namespace. In this way, client applications that must deal with a particular class in a particular way always succeed, regardless of the namespace.

WMI objects can participate in a relationship known as an association. An association is an instance of an association class that relates two other instances by referring to them in its properties.

Class definitions can be either static or dynamic. A static class has a definition that is persistent, which means the definition is stored in the Common Information Model (CIM) repository until it is explicitly deleted. WMI can provide definitions of static classes without the help of a provider.

A dynamic class definition is supplied by a class provider at run time, as needed. Dynamic class definitions are not stored permanently. Whenever the definition of a dynamic class is requested, WMI makes a call to the appropriate class provider to request it

Because of the shared and distributed nature of classes within WMI, changing a class definition has the potential to affect any WMI managed entities that are deployed currently. You should carefully design your classes so that they do not require modification. However, if you must make modifications to a class, it is recommended that you remove the class and then recreate it. Adding qualifiers is the only way that changes should be made to an existing class.


Classes and Properties

WMI classes can include one or more properties, or name/value pairs, that describe the data of the class. Properties are assigned case-insensitive names that must consist entirely of letters, digits, underscores, or valid Unicode characters with values greater than 0x007F. Property names cannot:

  • Begin with a digit.
  • Include leading or trailing underscores.
  • Contain white space.

Each property has a type. The type can be represented either by its name or a type identifier. Examples of type names are sint32, string, and datetime. Type names are primarily used in MOF syntax and are described in MOF Data Types.

Type identifiers are constants defined by WMI to represent type names. Type identifiers tag the type name with a prefix, such as CIM_SINT32 and CIM_STRING. WMI employs these constants because they are convenient and easy to use.

Superclass properties are always inherited by their subclasses. However, the default values of inherited properties can sometimes be overridden. Whether a subclass can specify its own default value for an inherited property depends on which, if any, qualifier is attached. Qualifiers provide additional information about the use of a property, such as whether it can act as a key or can contain NULL values. Users can define their own qualifiers if one of the WMI standard qualifiers does not suit their purpose. In addition to properties, qualifiers can be attached to classes, class instances, methods, and parameters.

The maximum number of properties allowed in a class is 1,024. Because derived classes inherit properties from their parent class, the number of properties that you can declare for a derived class and the number of properties that are inherited cannot exceed 1,024. However, the total number of properties in a class hierarchy can be greater than 1,024. For example, if a parent class has 1,000 properties and there are two derived classes, each derived class can define up to 24 additional properties. In this example, the total number of properties for the class hierarchy is 1,048.

When a subclass contains a property with the same name as a property in its superclass, the subclass always overrides the inherited property. When a property lacks an initial value, WMI assigns it the value of NULL.


Classes and Methods

[This is preliminary documentation and subject to change.]

The Common Information Model (CIM) supports class methods.

WMI classes can include zero or more methods. Take MyClass, for example:

class MyClass
{
  [key] sint32 KeyProp
  sint32 OtherProp;
  sint32 MyMethod();
}

WMI classes can include zero or more methods. In MyClass, there is one method that returns a single signed 32-bit value and has no parameters. In general, however, CIM classes may have many methods with complex parameter flows, complex return values, or no parameters or return values at all. Parameter in-values, out-values, and return values are packed in IWbemClassObject instances.

Every method must have a unique name. WMI does not allow two methods with the same name and different signatures to exist in one class or within a class hierarchy.

This section includes topics on the following subjects:

  • How WMI executes methods in CIM classes
  • How WMI implements methods in CIM classes
  • Provider bindings
  • Method return types
  • Method parameter types


Executing Methods

[This is preliminary documentation and subject to change.]

A client invokes a method synchronously by calling the IWbemServices::ExecMethod method or asynchronously by calling the IWbemServices::ExecMethodAsync method. These calls expect an object path to the object, against which the method is executed. WMI cannot ensure that the provider in fact properly executes the method against that instance.

Currently, there is no specification stating whether or not side-effects on the properties of an instance are permitted during execution of a method against an instance.

A method may or may not be static. Static methods are designated by the presence of the static qualifier on their definition. Static methods are executed against a class, not a particular instance of that class. The path specified to a method execution API for a static method must, therefore, be a class name. Non-static methods are executed against a particular instance of a class. The path specified to a method execution for a non-static method must, therefore, be an instance path

If a method is marked with the static qualifier, then the method may be executed against the class itself or any instance of the class with the same meaning.

class MyClass
{
  [key] sint32 KeyProp;
  sint32 OtherProp;

  [static]
  sint32 MyMethod();
};

In the preceding code, MyMethod could be executed using an object path of MyClass or MyClass=32 (for an instance).


Implementing Methods

[This is preliminary documentation and subject to change.]

CIM class declarations can include the declaration of one or more methods. Whether an implementation of a method is available depends on whether there is a dynamic method provider for the class. Although a method definition is always passed on from a superclass to a subclass, the method's implementation may not be.

The Implemented qualifier must be associated in a class with any method that has an implementation in that class and which is actually backed by a provider. Omission of the Implemented qualifier indicates that the method has no implementation in that class.

Consider the inheritance tree {A,Bi:A,C:B,Di:C}, which reads, "A is the superclass, B inherits from A and has an Implemented qualifier, C inherits from B, and D inherits from C and has an Implemented qualifier." If the method MyMethod was declared on A, then it is by definition "available" in all classes. However, B is the first place that Implemented appears, and yet another implementation occurs in D. When WMI executes the method, the following search algorithm is applied.

For normal methods (those executed against a particular instance)

For an instance of a given class, search for the nearest implementation, working back toward the parent until an implementation is found. For example:

  • If the method MyMethod is executed against an instance of D, then the implementation in D is the one that is used.
  • If MyMethod is executed against an instance of C, then the implementation in B is used, because there is no implemented qualifier in class C.

If the method is executed against an object path which claims to be of class A, then the true instance is located in the class hierarchy and the same algorithm applies. For example, if the method is executed against the path A=1 then of course the true instance may be of class A or it may be of one of the subclasses. If the instance is actually of one of the subclasses, then the nearest provider which implements the method is called. Note that the traversal is back up the class hierarchy toward the superclass. If the instance were truly of class A, then the method execution would fail, since there is no implementation at A and A is the first class in the hierarchy.

For static methods (execution against a class instead of an instance)

The search algorithm executes the implementation of the class specified in the object path. There is no search algorithm applied. Thus, in the class hierarchy {A,Bi:A,C:B,Di:C} the only valid executions are B.MyMethod and D.MyMethod. Attempts to execute with other object paths to the other classes or instances of those classes will fail.

Thus, if a method is redeclared for a class without the Implemented qualifier, it is considered unimplemented for that class, and the invoked implementation at run time is the implementation of the superclass, if available. The implementation of the superclass is always propagated to a derived class unless the derived class provides its own implementation. Redeclaration of a method in a derived class without implemented is useful only when a qualifier is added to or removed from the method.

If a method is marked with the Disabled qualifier, WMI does not execute the method in its class. Also, WMI does not search further up the class hierarchy for an implementation of the method.

For more information about the standard qualifiers associated with methods, see WMI Standard Qualifiers. For more information about invoking a class method, see Calling a Method.


Provider Binding

[This is preliminary documentation and subject to change.]

Method providers may be provided for either static or dynamic classes and instances.

When a method provider for a class exists, the class must at least be marked with the name of the provider that supplies the method implementation. Second, the necessary provider registration objects (instances of MethodProviderRegistration and __Win32Provider) must also exist.

To bind a method provider to a method, use the following rules:

  • If a provider supports the methods for a class with dynamic instances, it must also be the dynamic instance provider.

    There is no ability to separate the instance provider and the method provider for a given class. The class definition must be tagged with both dynamic and provider qualifiers.

  • If a provider supports methods for static instances, then the class definition includes a provider qualifier with the provider name but not the dynamic qualifier.
  • If a provider for methods is associated with a dynamic class, the same rules apply as for a dynamic instance provider. The same provider for the instances must also supply the methods.


Method Return Types

[This is preliminary documentation and subject to change.]

According to the CIM specification, the return value for a method must be one of the basic CIM data, specifically: Boolean, numeric, char, string, or datetime. However, WMI allows a complete WMI object instance as a return value as well.

class MyClass
{
  [key] sint32 KeyProp;
  sint32 OtherProp;

  sint32 MyMethod();
  datetime MyMethod2();
  SomeOtherObject MyMethod3();
}

Return values of arrays of any type are not permitted. No return type is indicated by use of the keyword void.


Method Parameter Types

[This is preliminary documentation and subject to change.]

In WMI, parameters must be properly tagged with their direction of flow ( such as [in] or [out]) and with an id qualifier.

sint32 MyMethod([in, id(0)] sint32 p1, [out, id(1)] sint32 p2);

The id qualifiers must be numbered sequentially, starting with zero. Their order of appearance is not significant. For example, the following statement is also legal:

sint32 MyMethod([in, id(1)] sint32 p1, [out, id(0)] sint32 p2);

The order of [in] and [out] is not significant

If the id qualifiers are omitted in MOF syntax, they are automatically assigned in the order of declaration of the parameters, starting at zero. The qualifiers must be supplied programmatically.

Parameters may have default values that affect programmatic access. For more information, see Programmatic Access to Methods.

sint32 MyMethod([in, id(0)] sint32 p1 = 123, [out, id(1)] sint32 p2);

Parameters lacking initial values remain unassigned and will default to NULL during programmatic access.

Parameters that have both in and out flows are marked like this.

sint32 MyMethod([in, out, id(0)] sint32 p1);

Parameter Names

You cannot use the same parameter name more than once as an input parameter or more than once as an output parameter. (An exception would be when breaking up an [in,out] parameter into separate parameters.)

sint32 MyMethod([in, id(0)] sint32 p1, [out, id(0)] sint32 p1);

If the same parameter name appears with both in and out qualifiers:

  • The parameter must have an explicit id qualifier with the same value.
  • The qualifiers must be exactly the same for both parameters.

The functionality is conceptually the same as using the [in, out] qualifier on a single parameter:

sint32 MyMethod([in, id(0), MyQualA(1)] sint32 p1, [out, id(0), MyQualA(1)] sint32 p1);

Array Types

Array types may be bounded or unbounded:

sint32 MyMethod([in, id(0)] sint32 p1[]); // unbounded
sint32 MyMethod([in, id(0)] sint32 p1[32]); // bounded
  • Bounded arrays are primarily for documentation. They are the same as declaring an unbounded array with a max qualifier:
    sint32 MyMethod([in, id(0), max(32)] sint32 p1[]); // bounded

    You may not do both simultaneously.

  • Parameters of reference types are permitted:
    sint32 MyMethod([in, id(0)] Win32_LogicalDisk ref p1); // unbounded

    These parameters are actually strings in the form of object paths. Arrays of references are permitted as well.

For more information, refer to the following Platform SDK topics :

  • Registering a Method Provider
  • Implementing IWbemServices::ExecMethodAsync
  • Declaring Methods


Classes and Instances

A WMI class defines a template for describing a type of managed object. An instance of a WMI class represents a specific managed object of the type described by the class. Where the class generally models the real-world device or component in the general sense, each instance represents a specific occurrence of the device or component. For example, a general class called FloppyDisk might exist, with the instances on a particular host computer representing drives A and B.

Some WMI classes are abstract base classes. Abstract classes do not have any instances of their own; only classes derived from them have instances. The CIM_ManagedSystemElement system class, for example, is an abstract class. Instances are created from the CIM_ManagedSystemElement subclasses. Another type of class supports only a single instance. Such classes are known as singleton classes.

There are some operations that cannot be performed on instances. The following operations are invalid:

  • Changing the class of an instance.
  • Changing a property type.
  • Adding or removing a property.
  • Adding or removing a Key or Indexed qualifier.
  • Adding or removing a Singleton, Dynamic, or Abstract qualifier.

All instances of a class exist within the namespace to which the class belongs. Within a namespace, instances can be either static or dynamic. Static instances are persistently stored and remain valid, even across operating system restarts, until they are explicitly deleted. You must place static instances in the CIM repository by using the IWbemServices::PutInstance or IWbemServices::PutInstanceAsync method, or by submitting a MOF to the MOF compiler.

Dynamic instances are supplied by a provider when the need arises and are not stored in the CIM repository. Requests for dynamic instances are forwarded through WMI to the provider for the class. Dynamic support of instances of a class allows a provider to always supply up-to-the-minute property values.

Static classes can support either static or dynamic instances. Within a static instance, either static or dynamic properties can exist. A static class that supports only static instances containing static properties is always available through WMI. Provider involvement is unnecessary.

Static classes with dynamic instances store only the class definition in the CIM repository. When instances are requested, a provider must retrieve the class definition and build the required instance or set of instances.

Static classes with static instances containing both static and dynamic properties can store placeholders for the dynamic properties in the CIM repository. When a request is made for an instance, WMI summons the designated property provider to supply the actual data for each dynamic property.

Dynamic classes support only dynamic instances. With a dynamic class, neither the class definition nor the instances are stored in the CIM repository. The provider responsible for a dynamic class stores information about the definition and instance locations. When an application requests a dynamic class, WMI locates the provider and forwards the request.


Association Classes

A WMI association class describes a type of a relationship that two WMI objects may be in. Each instance of an association class represents a relationship between two specific WMI objects. The properties of an association class include pointers, or references, to the two classes or instances. Each of these references always takes the form of an object path, a string that uniquely identifies the location of the referenced object. By representing relationships outside of the objects themselves, relationships can be added or removed without affecting the objects. Note that since relationships are represented using object paths and not complete objects, the objects themselves may change without any need to update the relationships.

All association classes are identified by the Association qualifier, one of the standard qualifiers defined by WMI for use with classes.

All WMI objects can participate in zero or more associations. Association classes can be system classes defined by WMI, or custom classes defined by a third-party vendor. The CIM defines various types of associations, each type defining a different relationship. For example, the CIM_Dependency class defines a dependency association. That is, two of the properties of the CIM_Dependency class are references to instances that depend upon each other in some way. One instance cannot exist or operate without the other instance. The CIM_HostedService association class is an example of a dependency association. The reference properties of this class include a reference to an instance of the CIM_System class and a reference to an instance of the CIM_Service class

An example of a custom association class might be a NetCardToProtocolBinding class for relating network cards to protocols. Because a network card can support multiple protocols, and the same protocol runs over multiple network cards, defining an association class enables these two types of managed objects to be related without affecting their class definitions, and without knowledge of the providers for the protocol and network card instances.

Applications can query data and schema associations using the ASSOCIATORS OF and REFERENCES OF statements defined in the WMI Query Language (WQL). For more information, see the following topics:

  • ASSOCIATORS OF Statement
  • REFERENCES OF Statement
  • Schema Associations


Ternary Associations

[This is preliminary documentation and subject to change.]

Associations between three CIM classes are called ternary associations. WMI does not fully support associations between more than two classes and you should not create such classes because queries that specify these associations can cause unpredictable results.

The current version of the WMI schema includes one example of ternary association, Win32_ProtocolBinding. This class exists for backward compatibility purposes and may change in the future versions of WMI.

The logic for ternary associations has only been tested to the extent absolutely necessary to support scenarios specific to Win32_ProtocolBinding.


Singleton Classes

WMI supports singleton classes, or classes that can have only one instance. Because there is no need to identify uniquely one instance from another, singleton classes do not designate one or more of their properties as the key.

Singleton classes can be defined programmatically using the methods of the IWbemServices interface or using MOF syntax. In either case, you must attach the Singleton qualifier to the class declaration. Singleton is set to the Boolean value of TRUE to designate the class as a singleton class. To ensure that the qualifier is propagated from the class to the instance, a qualifier flavor must also be included. When defining the class using IWbemServices methods, you should specify the constant WBEM_FLAVOR_FLAG_PROPAGATE_TO_INSTANCES. When defining the class using MOF, you should specify the flag ToInstance

To retrieve an instance of a singleton class, call the IWbemServices::GetObject method with the bstrObjectPath parameter set to "SingletonClassName=@".

For more information about defining classes with MOF syntax, see Managed Object Format (MOF) Language. For more information about qualifiers and qualifier flavors, see Qualifiers and Qualifier Flavors.


Qualifiers

Qualifiers contain information that can be used to describe a class, class instance, property, method, or parameter. Creators of classes and instances can attach qualifiers to their class and instance declarations to provide the user of those declarations—typically management applications—with more detail.

Qualifier usage in the current version of WMI is informational. For example, a property marked with the Read qualifier is intended to be read-only, but WMI does not require the property to be read-only. It is up to the provider supporting the class to protect the property from modification, if necessary.

There are three categories of qualifiers: those defined by the CIM, those defined by WMI, and those defined by developers. The qualifiers defined by WMI are known as the standard qualifiers. Some of the CIM and standard qualifiers are automatically assigned when a class or instance is created. Others must be explicitly specified in class and instance declarations using the MOF language or the IWbemQualifierSet interface.

Qualifiers have a flag called flavor that determines whether the qualifier will be propagated to derived classes and instances, and whether a derived class or instance can override the qualifier's original value.

All qualifiers have a name, a value, and one or more flavors. Qualifier names are case-insensitive and cannot include a leading or trailing underscore. Underscores can, however, appear in the middle of a qualifier name.

Depending on the qualifier and its intended use, the qualifier may or may not be required. For example, WMI defines the Implemented qualifier for methods. If a provider defines a class with a method and includes an implementation of that method, the provider must attach the qualifier Implemented to the method declaration. Another required qualifier is the Key qualifier. The Key qualifier must be attached to every property in a class that serves as part of the key for that class. Optional qualifiers include provider-defined qualifiers and standard qualifiers that can be used as comments. A qualifier is considered optional when its removal does not affect the functionality of the class or instance with which it is associated.


Qualifier Flavors

Qualifier flavors provide additional information about a qualifier. Flavors can be specified with predefined flags in class and class instance declarations using the Managed Object Format (MOF) language. Flavors also can be specified with numeric constants using the IWbemQualifierSet interface. Although developers can define new qualifiers to support their custom classes, they cannot define new flavors. All new and existing classes must use flavors defined by WMI.

Flavor can indicate if a qualifier can be localized. Flavor can also describe rules that specify whether a qualifier is propagated to derived classes and instances, and whether a derived class or instance can override the qualifier's original value. Qualifiers can propagate from:

  • Class to subclass.
  • Class to instance.
  • Class property to instance property.

Qualifiers that are declared for the class or instance do not propagate to properties of that class or instance.

Override permissions define whether a subclass can change the meaning of a qualifier defined in the superclass. Override permissions are set in conjunction with WMI propagation rules. That is, if WMI propagation rules are set for a qualifier, the qualifier must have override permissions for you to specify new qualifier values in classes or instances derived from the superclass.

The following table describes the flags that are used to specify flavors in MOF syntax.

Flavor flag | Meaning
Amended | The qualifier is not required in the basic class definition and can be moved to the amendment, for example to be localized.
DisableOverride | The qualifier value cannot be overridden in a derived class or an instance.
EnableOverride | The qualifier value can be overridden in a derived class or an instance. This is the default.
NotToInstance | The qualifier is not propagated to instances. This is the default.
NotToSubclass | The qualifier is not propagated to derived classes. This is the default.
ToInstance | The qualifier is propagated to instances.
ToSubclass | The qualifier is propagated to derived classes.

To assign a flavor programmatically, call the IWbemQualifierSet::Put method with the lFlavor parameter set to one or more of the following constants.

Constant | Meaning
WBEM_FLAVOR_FLAG_PROPAGATE_TO_DERIVED_CLASS | The qualifier is propagated to derived classes. Using this constant is the same as using the ToSubclass flag.
WBEM_FLAVOR_FLAG_PROPAGATE_TO_INSTANCE | The qualifier is propagated to instances. Using this constant is the same as using the ToInstance flag.
WBEM_FLAVOR_NOT_OVERRIDABLE | The qualifier value cannot be overridden in a derived class or an instance. Using this constant is the same as using the DisableOverride flag.
WBEM_FLAVOR_OVERRIDABLE | The qualifier value can be overridden in a derived class or an instance. This is the default. Using this constant is the same as using the EnableOverride flag.
WBEM_FLAVOR_AMENDED | The qualifier is localized.


System Classes

WMI system classes are a collection of predefined classes included in the WMI Core. The system classes support the activities of WMI. They are automatically defined in every namespace. For example, system classes register providers and describe events that relate both to changes in the CIM repository and to provider-specific components.

System classes are identified by a leading double underscore in their name. All system classes are derived from the abstract base class __SystemClass. Because the system classes are predefined by WMI, developers cannot create their own system classes by starting a class name with a double underscore. However, developers can derive classes from system classes.

For detailed information about each of the WMI system classes, see WMI System Classes.


System Properties

In addition to class-specific properties, WMI defines a set of system properties that are associated with all classes and instances of classes. System properties provide information such as a class name, its derivation, and its namespace.

As with system classes, system properties begin with a double underscore to distinguish them from properties created by applications or providers. Properties created by applications or providers cannot start with a single or double underscore.

Not all system properties are available for all classes or class instances at all times. In particular, a property such as __Path does not have a valid value until the class or instance to which it refers is actually saved to and retrieved from the CIM repository. For detailed information about each WMI system property and its availability, see WMI System Properties.


Date and Time Format

All dates and times in Windows Management Instrumentation (WMI) use the same format, a format originated by the Distributed Management Task Force (DMTF). The format is a fixed-length string. The string contains several fields:

yyyymmddHHMMSS.mmmmmmsUUU

The following table describes each of the fields in the format.

Field | Description
yyyy | Four-digit year (0000 through 9999). Implementations can restrict the supported range. For example, an implementation can support only the years 1980 through 2099.
mm | Two-digit month (01 through 12).
dd | Two-digit day of the month (01 through 31). This value must be appropriate for the month. For example, February 31 is invalid. Implementations, however, are not required to check for valid data.
HH | Two-digit hour of the day using the 24-hour clock (00 through 23).
MM | Two-digit minute in the hour (00 through 59).
SS | Two-digit number of seconds in the minute (00 through 59).
mmmmmm | Six-digit number of microseconds in the second (000000 through 999999). Implementations are not required to support evaluation using this field, but this field must always be present in the string to preserve the string's fixed-length nature.
s | Plus sign (+) or minus sign (-) to indicate a positive or negative offset from Universal Time Coordinates (UTC).
UUU | Three-digit offset indicating the number of minutes that the originating time zone deviates from UTC. For WMI, it is encouraged, but not required, to convert times to GMT with a UTC offset of zero.

Note On Microsoft® Windows NT®/Windows® 2000 systems, WMI does not accept a date earlier than January 1, 1601, due to a limitation of the Microsoft® Win32® application programming interface (API).

All fields must be of the indicated length, using leading zeros as appropriate for the type.

You can use asterisks to indicate unused fields. An unused field indicates no particular value for that field and can be used everywhere except the WHERE clause of a query. For example, a date and time with an unspecified year can occur in any year. If a field is to be unspecified, the entire field must be replaced by asterisks. You cannot replace, for example, one out of the required four digits for the year:

19980416******.000000+***                 // Legal
199*0416******.000000+***                 // Illegal

Although a date-time format with unspecified fields is meant to convey only the data that is specified, an application can interpret such a format as occurring in the current year, time, day, and/or time zone. Not specifying a particular field indicates lack of interest in an absolute point in the calendar, but instead interest in a relative point. For example, "April first" is relative to some unspecified year but is still a defined point if the level of measurement detail is one day:

****0401******.000000+***

Unzoned time can be specified by placing asterisks in the UUU field after either the plus or minus sign:

19980401135809.000000+***
19980401135809.000000-***

An unzoned date and time is interpreted without reference to a particular time zone, but instead with reference to a local, abstract chronometer within the executing operating system. For example, portable computers can have internal clocks whose settings may or may not correspond to the geographical time zone.

Unzoned time must be interpreted by substituting the time zone of the current abstract time source rather than the local time zone.

Special consideration must be given to the meaning of the UTC offset with datetimes in queries. In general, equivalence, greater-than, or less than comparisons will work between two datetimes if they are of the same UTC offset. Datetimes occurring with different time zone offsets will first be converted to GMT, and the resulting times will then be compared.

Queries involving relative datetimes, those with asterisks in one or more subfields, are only meaningful when compared for equivalence. Further, use of asterisks as wildcards is not allowed; relative datetimes will be compared on a character-for-character basis. For example, the following two times are not equivalent:

19980401135809.000000+***
19980401135809.000000+000


Interval Format

Date-time intervals are specified with a format that is similar to the date and time syntax specified by the Distributed Management Task Force (DMTF). The format is a fixed string divided into several fields:

ddddddddHHMMSS.mmmmmm:000

These fields are described in the following table.

Field | Description
dddddddd | Eight digits representing a number of days (00000000 through 99999999).
HH | Two-digit hour of the day using the 24-hour clock (00 through 23).
MM | Two-digit minute in the hour (00 through 59).
SS | Two-digit number of seconds in the minute (00 through 59).
mmmmmm | Six-digit number of microseconds in the second (000000 through 999999). Implementations are not required to support evaluation using this field, but this field must always be present in the string to preserve the string's fixed-length nature.

Intervals always have a trailing :000 as the last four characters. The colon (:) and trailing zeroes are required.

All properties of type CIM_DATETIME that represent intervals must be marked with the Subtype standard qualifier. The qualifier must be set to the string "interval".

The following string represents an interval of 1 day, 12 hours, 0 minutes, and 32 seconds:

00000001120032.000000:000

For information about using date-time intervals with WMI CIM Studio, see Using the Interval Editor.

Note Unlike Date and Time, asterisks cannot be used to indicate unused fields.


Identity and Location

Windows Management Instrumentation (WMI) classes and class instances are identified and located using a formatted string known as an object path.

For classes, an object path identifies the following: the server on which the class resides, the namespace to which the class is assigned, and the name of the class. A namespace is a mechanism for providing scope for keys. By defining key scopes, WMI creates a unit for grouping classes that operate in the same managed environment.

For instances, an object path specifies a key in addition to the server, namespace, and class.


Key Properties

WMI identifies class instances through the use of keys, properties that provide a unique value. Key properties distinguish instances of a class in the same way that key columns distinguish rows of a table in a relational database.

Key properties are designated by the Key qualifier, a standard qualifier defined by WMI. You can attach Key qualifiers to more than one property in a class to create a compound key for the class. Properties chosen as key properties for a class, when taken together, must contain values that can uniquely identify each instance of the class. Any type of property can be used as a key with the following exceptions:

  • Arrays
  • Real and floating-point numbers
  • Embedded objects
  • Characters lower than ASCII 32 (that is, white space characters)

Character strings that are defined as keys must have Unicode ranges of U+0020 or higher. This restriction exists because key values are used in object paths, and you cannot use nonprinting characters in object paths.

The following Managed Object Format (MOF) syntax illustrates how to define a class with a single key property:

class MyClass
{
    [key] string MyKey;
    string RegularProp;
};

When a nonabstract superclass specifies a key, all classes derived from the superclass inherit that key. The derived classes cannot alter the inherited key or define any new key properties. However, when you derive a subclass from an abstract class without a key, you can introduce a key in the subclass.

All classes that define more than one instance must specify a key. Because abstract classes do not define any instances, they do not need to specify keys. Because singleton classes define only one instance, they cannot specify keys.

Note Character strings of type Char16 that are defined as keys must contain values greater than U+0032.


Namespaces

A namespace is a logical unit for grouping classes and class instances, and for controlling their scope and visibility. A namespace is an instance of the __Namespace system class or a class that derives from the __Namespace class. The __Namespace class has a single property: Name. It is a namespace's name that distinguishes it from all other namespaces. Namespace names cannot include leading or trailing underscores.

Namespaces can be nested within each other to form an arbitrary hierarchy of classes and instances. The nesting model resembles that used for a hierarchical file system. Each namespace needs to have a unique name within the scope of its immediate parent object.

To indicate a namespace hierarchy, you separate individual namespace names with backward slashes:

Namespace1\Namespace2\Namespace3........\LastNamespace

Namespaces can be arranged in a hierarchical format, as shown in the example at the end of the topic, or in a lateral format. Either way, the relationship between namespaces has nothing to do with class inheritance. That is, a child namespace does not automatically inherit the classes of its parent namespace.

WMI provides limited support for cross-namespace relationships. An association can contain references to class instances in two different namespaces as long as the instances are statically defined within the Common Information Management (CIM) repository and not supplied by dynamic providers. For more information on static and dynamic definition of class instances, see Classes and Instances.

Typically, a namespace contains a set of classes and instances that represent managed objects in a particular environment. For example, the classes and instances defined to manage objects in the Microsoft® Win32® environment are created in their own unique namespace. Because all operations in the current version of WMI take place in a particular namespace, conflicts do not occur between classes that are named the same and reside in different namespaces. However, when you create a class name and its associated properties and methods, it is recommended that you avoid giving the class the same name as a class in another namespace. This eliminates possible problems for clients and in future releases of WMI.

All WMI installations have four predefined namespaces:

  • Root
  • Root\Default
  • Root\Cimv2

The Root namespace is primarily designed to contain other namespaces. The WMI installation places the other three predefined namespaces under the Root namespace. The Default namespace holds most of the system classes. The Cimv2 namespace contains the classes and instances that represent a Win32 environment, such as Win32_LogicalDisk and Win32_OperatingSystem.

Most operations occur within the Root\Cimv2 namespace. However, if the WMI installation is also acting as a proxy for a logical or network device, you should locate the classes and instances associated with the logical or network device in a namespace other than Root\Cimv2, as shown in the following illustration. Doing so makes it easy to distinguish between the classes and instances for the local computer and those for the logical or network device.

In the following example, two namespaces are nested beneath the Root namespace: Cimv2 and UnixProxy. The Cimv2 namespace models the local computer, and the UnixProxy namespace holds two other namespaces, UnixA and UnixB. The UnixA and UnixB namespaces each model a complete Unix computer.

Because namespaces are represented as instances of the __Namespace class, a new namespace is created when a __Namespace instance is created and a namespace is deleted when a __Namespace instance is deleted. After a namespace is marked for deletion, all clients currently connected to that namespace receive the error code WBEM_E_INVALID_NAMESPACE from any subsequent call to the namespace.


Object Paths

You use WMI object paths to uniquely identify namespaces on a server, classes within a namespace, or instances of a class. Object paths are conceptually similar to Universal Resource Locators (URLs). Both are hierarchical in format, containing one or more elements. The number of elements depends on the type of object path, and whether it is a full path or a path that is relative to a particular location.

Object paths can contain the following:

  • Strings contained in single quotation marks.
  • Forward slashes as separators.
  • Backslashes as separators.
  • Hexadecimal constants for integers.
  • Boolean constants, such as TRUE and FALSE, for classes with keys that take Boolean values.
  • An assumed local server with a partial namespace path. Thus, specifying the Root\Default namespace implies the \Root\Default namespace on the local server.

Object paths cannot contain white space either within an element or between elements. You can use embedded quotation marks in object paths but must delimit them with escape characters, as in a C or C++ application. URL notation can be used to represent non-printing characters, such as %20 for a blank space. Only decimal values are recognized as numeric portions of keys.

Object paths are used in the reference properties of association classes to identify related objects, and as input or output parameters to several methods. Because object paths are treated as strings for the purpose of lookup and comparison, the value of an object path when used as a reference property is always the string itself and not the dereferenced object. String comparisons that deal with object paths are always case-insensitive.

The following table lists the methods that work with object paths to namespaces, classes, or instances.

Type of object path | Method
Namespace object path | IWbemServices::OpenNamespace
Class object path | IWbemServices::ExecMethod
Class object path | IWbemServices::ExecMethodAsync
Class or class instance object path | IWbemServices::GetObject
Class or instance object path | IWbemServices::GetObjectAsync.
Instance object path | IWbemServices::DeleteInstance
Instance object path | IWbemServices::DeleteInstanceAsync
Instance object path | IWbemCallResult::GetResultString

To view the Backus-Naur Form definition for object paths, see BNF Syntax for Object Paths.

For more information on specific types of object path, see:

  • Namespace Object Paths.
  • Class Object Paths.
  • Instance Object Paths.


Namespace Object Paths

A namespace object path is used to locate a particular namespace on a server. A full namespace object path has two elements, server and namespace, and is formatted using either forward or backward slashes, as shown following:

\\Server\Namespace

– Or –

//Server/Namespace

The server element specifies the network name of the computer that is hosting the namespace. If the server is the local computer, a single dot can be used instead of the server name:

\\.\Namespace

The namespace element specifies any valid namespace. A namespace is represented with a hierarchical string containing elements delimited by single backslashes, such as Root\Cimv2. You cannot use forward slashes within namespace names.


Class Object Paths

A class object path is used to locate a class within a namespace. A full object path to a class appends the class name to a namespace path as follows:

\\Server\Namespace:Class

A relative object path can be used to represent a class that resides in the current namespace. A relative object path to a class contains only the class name:

Class

For example, the following full object path can be used to locate the Win32_LogicalDisk class within the Root\Cimv2 namespace on a server called Admin:

\\Admin\Root\CimV2:Win32_LogicalDisk

The same class can be located on the current server in the current namespace with this relative object path:

Win32_LogicalDisk

The following code fragment illustrates how to use the relative object path to retrieve the class definition for Win32_LogicalDisk:

BSTR Path = SysAllocString(L"Win32_LogicalDisk");
IWbemClassObject *pDiskClass = 0;
pHmmSvcs->GetObject(Path, 0, 0, &pDiskClass, 0);


Instance Object Paths

An instance object path is used to locate an instance of a particular class within a namespace. A full instance object path appends the name and value of the key property for the class to a full class object path:

\\Server\Namespace:Class.KeyName="KeyValue"

A relative object path can be used to represent a class instance that resides in the current namespace on the current server. The relative instance path requires only the key property name and key property value. For example, the following object paths point to single instances of the current namespace on the current server:

PropName="E:"

ComPort=2

Relative object paths that also contain the class name are valid. For example, if PropName belongs to MyClass, you can use the following path to identify the instance whose key property contains E:

MyClass.PropName="E"

To retrieve a particular instance, use code similar to the following sample. The call to the Automation function SysAllocString allocates and initializes the character string for the object path to the instance. The call to the IWbemServices::GetObject method retrieves the instance and places it in the contents of the pComPort parameter.

BSTR Path = SysAllocString(L"ComPort=2");
IWbemClassObject *pComPort = 0;
pWbemSvcs->GetObject(Path, 0, 0, &pComPort, 0);

For instances of classes that specify multiple properties as the key, WMI requires no specific ordering of key properties in object paths. You need only specify the value of each of the properties in the object path. For example, assume that the class MyClass2 has a compound key consisting of an integer property IntVal and a string property StrVal. The following object paths show two different ways to identify the same instance of MyClass2:

"MyClass.IntVal=33,StrVal=\"AAA\""

"MyClass.StrVal=\"AAA\",IntVal=33"


64-Bit Key Support

Class instances can have 64-bit key values, as shown below:

class MyBig
{
  [key] sint64 k;
  sint64 p;
};

instance of MyBig
{
  k = 2;
  p = 3;
};

The object path to an instance based on a 64-bit key is always enclosed in quotes. The path to the above instance is

MyBig = "2"

As long as the 32-bit range is not exceeded, the path may omit the quotes and use hex or decimal notation, as for 32-bit paths.

Once the range of the integer exceeds 0x7FFFFFFF (for signed types) or 0x80000000 (for unsigned types), or 32 bits, the quotes must be used. Further, the only valid path is the one in the __RELPATH or __PATH properties of the instance. Thus, hexadecimal notation for the equivalent value, for example, is not supported.

Likewise, if the instance key was recorded as a negative number, then that original number is the one that must be used to retrieve it.

Query semantics are unaffected and behave as expected. This behavior only affects the object path and GetObject / GetObjectAsync operations.


Sample Programs

The following topics describe the sample programs included with the WMI SDK:

  • C++ Sample Programs
  • Scripting Sample Programs


C++ Sample Programs

Provider and client samples are provided with the WMI SDK and are located in the \Vc subdirectory under the \Samples directory of the WMI SDK installation. In addition to the brief descriptions of each sample found here, there is an .htm or .html file in the subdirectory for each of these samples.

Sample | Description
AdvancedClient | AdvancedClient is a sample application that demonstrates some important WMI capabilities, such as connecting to a namespace, listing logical disks, and receiving WMI events.
ClassProv | ClassProv is a sample class provider. The instances are defined using an array named MyDefs which is declared in Classprov.cpp. The class is simple and consists of a string key property and an integer property.
CmdLineConsumer | CmdLineConsumer is a generic event consumer that spawns another application according to the logical consumer instance. To register this consumer, enter at the command prompt: mofcomp cmdline.mof
CustomViews | CustomViews provides alternative views of objects contained in the WMI database. WMI CIM Studio, the browser, and other applications can use these custom views to display application-specific views of WMI objects. For more information, see Displaying Custom Views of Object Data.
EventConsumer | The EventConsumer sample demonstrates a permanent event consumer. This consumer implements the IWBEMEventConsumerProvider interface which returns an event sink based upon an instance of an event consumer. The event consumer demonstrates the implementation of the IWBEMUnboundObjectSink interface, which consumes WMI events.
EventProvider | EventProvider is a sample event provider. It demonstrates a simple shell for such a provider with the minimum amount of required code.
FrameworkProv | FrameWorkProv implements a simple instance provider using the provider framework. It supports enumeration (with the CreateInstanceEnumAsync function), retrieval (with the GetObjectAsync function), deletion (with the DeleteInstanceAsync function), and editing (with the PutInstanceAsync function).
HiPerfClient | The HiPerfClient sample shows how to use the WMI high performance API by creating a refresher.
HiPerfProvider | The HiPerfProvider sample demonstrates the basic framework of a high performance provider. The WMI high performance API is only supported on Microsoft® Windows® 2000 platforms.
Instprov | Instprov is an example of a simple instance provider written without using the provider framework. This sample is a small C++ DLL.
MethCli | MethCli is a simple application that retrieves a method from MethProv.
MethProv | MethProv is an example of a method provider. This sample is a small C++ DLL.
ObjPathParser | ObjPathParser contains a C++ object that parses Common Information Model (CIM) object paths. This is the same object path parser used internally in WMI components.
PingWbem | PingWbem is a simple application that runs in a command prompt window and that tests for the existence of a running and accessible WMI Service.
PropProv | PropProv is an example of a property provider. This sample is a small C++ DLL that returns two properties: a signed 32-bit integer and a string. A property provider is the easiest provider to write, making it the easiest place for a developer to begin. For general information about property providers, see Property Providers.
SimpleClient | SimpleClient is a simple WMI client application that can find and display all instances of a class and display the properties of a class instance. This sample accompanies the topic Creating a WMI Application in MFC.
Snap-in | Snap-in is an MMC standalone snap-in that shows you how to integrate WMI and MMC. For more information on this sample, see Snap-in Sample Details.
TempConsumer | TempConsumer is a sample temporary consumer that consumes events provided by the EventProvider sample.
UtilLib | UtilLib is a set of useful routines and classes used by the provider framework.
WBEMDump | WBEMDump shows the entire contents of the CIM repository in a hierarchical view. WMI supports a number of options to specify which information is shown. To view these options, open a command prompt window in the WMI installation directory and type: Wbemdump /?
WMIDiskPerf | The WMIDiskPerf sample obtains disk performance information produced by the DiskPerf driver.


Snap-in Sample Details

[This is preliminary documentation and subject to change.]

The Snap-in sample is an MMC standalone snap-in that shows you how to integrate WMI and MMC. The snap-in enumerates instances of the SAMPLE_OfficeEquipment class and displays them in the results pane. You can select an instance from the results pane and use the properties dialog box to modify its property values. The sample also shows you how to use event notification in MMC to keep the list of managed data current.

The WMI related code for this sample is contained in equipment.cpp and equipment.h. The sample uses three classes: CEventSink, CEquipmentFolder, and CEquipment. The CEventSink class is the sink that receives the asynchronous event notification calls. It contains the Indicate method that triggers a refresh of the SAMPLE_OfficeEquipment instance data when a new instance is created in the repository. The sink is created in CEquipmentFolder::RegisterEventSink.

The CEquipmentFolder class represents the Office Information node in the scope pane. CEquipmentFolder is responsible for a majority of the work, such as connecting to WMI, registering for event notification, enumerating the office equipment data, and listing the office equipment data in the results pane.

The sample connects to the root\cimv2\sample_office namespace on a background thread in CEquipment::ThreadProc. In addition to the connection event, the thread also listens for a get pointer event, which marshals the IWbemServices object when CEquipment::GetPtr is called. This thread exists for the life of the node.

When a connection has been established, the sample registers to receive temporary event notification for SAMPLE_OfficeEquipment instances that are created. The sample uses IWbemServices:ExecNotificationQueryAsync to register for the event. The event registration occurs in CEquipmentFolder::RegisterEventSink.

Note that because snap-ins are DLLs, the sample uses the IUnsecuredApartment interface to create a dedicated process for hosting its IWbemObjectSink implementation. For more details, see Security Considerations with Asynchronous Calls.

The sink's Indicate method sends a refresh event to the sample's window handler (WindowProc) when a new instance of SAMPLE_OfficeEquipment has been created. The refresh event empties the current enumeration of office equipment (CEquipmentFolder::EmptyChildren), creates a new enumeration that contains the new instance(CEquipmentFolder::EnumChildren), and displays the enumeration in the results pane (CEquipmentFolder::DisplayChildren).

The CEquipmentFolder::EnumChildren method calls IWbemServices::CreateInstanceEnum to create the list of office equipment. The sample traverses the enumeration using IEnumWbemClassObject::Next to create a simple array that is used later to fill the results pane.

The user can update the office equipment property values using the properties dialog box. The CEquipment class is responsible for creating the properties dialog box and updating the instance. When the user clicks OK or Apply on the properties dialog box, the PSN_APPLY case statement, found in CEquipment::DialogProc, determines whether the property values were changed. If the values changed, CEquipment::PutProperty calls IWbemClassObject::Putto update the property values. After the property values have been updated, IWbemServices::PutInstance updates the instance in the CIM repository. Note that the properties dialog box can also be used to create a new instance of office equipment.


Scripting Sample Programs

The WMI SDK includes many sample programs in the \Scripting subdirectory under the \Samples directory of the WMI SDK installation. The samples reside in four subdirectories, as listed in the following table.

Directory | Description
ASP | Samples that demonstrate using the WMI scripting API with Active Server Pages.
HTML | Samples that demonstrate using the scripting API from Hypertext Markup Language (HTML) pages.
VB | Samples that use the scripting API from Microsoft® Visual Basic®.
WSH | Samples that use the scripting API from Microsoft® Windows® Scripting Host.


ASP Scripting Sample Programs

The ASP sample directory contains samples that show how to use the WMI scripting API within Active Server Pages (ASP). These samples are presented using the Microsoft® JScript® and Visual Basic Scripting Edition (VBScript) programming languages.

File | Description
JScript\JSdiskinfo.asp | This JScript sample shows information about each disk on the local host.
VBScript\Vbsdiskinfo.asp | This VBScript sample shows information about each disk on the local host.


HTML Scripting Sample Programs

The HTML sample directory contains samples that show how to use the WMI scripting API in HTML with JScript and VBScript. The JScript samples are as follows.

File | Description
\HTM\JScript\JSService1.htm | Displays a Microsoft® Windows NT®/Windows 2000 service name using only synchronous API calls. This sample creates instances of WMI scripting objects using their class identifiers (CLSIDs) and the HTML <OBJECT> tag. For more information on synchronous versus asynchronous API calls, see Making an Asynchronous Call Using the Scripting API.
\HTM\JScript\AJSService1.htm | Displays a Microsoft® Win32® service name using asynchronous API calls. This sample creates instances of WMI scripting objects using their CLSIDs and the HTML <OBJECT> tag.
\HTM\JScript\JSService2.htm | Displays a Win32 service name using only synchronous API calls. This sample creates instances of WMI scripting objects using their programmatic identifiers (PROGIDs) in calls to the JScript ActiveXObject function.

The VBScript samples are as follows.

File | Description
\HTM\VBScript\VBSService1.htm | Displays a Win32 service name using only synchronous API calls. This sample creates instances of WMI scripting objects using their CLSIDs and the HTML <OBJECT> tag.
\HTM\VBScript\AVBSService1.htm | Displays a Win32 service name using asynchronous API calls. This sample creates instances of WMI scripting objects using their CLSIDs and the HTML <OBJECT> tag.
\HTM\VBScript\VBSService2.htm | Displays a Windows NT/Windows 2000 service name using only synchronous API calls. This sample creates instances of WMI scripting objects using their programmatic identifiers (PROGIDs) in calls to the Visual Basic CreateObject function.
\HTM\VBScript\VBSClassBrowser.htm | Uses the Microsoft® ActiveX® controls for WMI to display property information for classes.


Visual Basic Sample Programs

The VB sample directory contains three Visual Basic samples that show how to use the WMI scripting API with Visual Basic.

File | Description
\VB\VBLogDisk.vbp | Displays information about disk drives attached to your computer.
\VB\VBProcess.vbp | Displays processes running on your computer.
\VB\VBService.vbp | Enables viewing, starting, pausing, and stopping of Windows NT/Windows 2000 services.


WSH Sample Programs

The WSH sample directory contains JScript and VBScript samples that show how to use the WMI scripting API with Windows Scripting Host (WSH). The JScript samples are as follows.

File | Description
\WSH\JScript\Arraytype.js | Shows how to manipulate a property that has an array type.
\WSH\JScript\Classenum.js | Shows the enumeration of subclasses of a class.
\WSH\JScript\Derivation.js | Shows the manipulation of the Derivation_ property of the SWbemObject object.
\WSH\JScript\Embprop.js | Shows the manipulation of embedded object values.
\WSH\JScript\Emptyarray.js | Shows the manipulation of empty arrays on properties, qualifiers, and named value sets.
\WSH\JScript\Execmethod.js | Shows how to call a Common Information Model (CIM) method using the SWbemObject.ExecMethod_ method.
\WSH\JScript\Instenum.js | Shows the enumeration of instances of a class.
\WSH\JScript\Methodex.js | Shows how to invoke a CIM method as if it were an Automation method of SWbemObject.
\WSH\JScript\Methodset.js | Shows the manipulation of method sets.
\WSH\JScript\Nvs.js | Shows the manipulation of named value sets, when the named value is not an array type.
\WSH\JScript\Nvs2.js | Shows the manipulation of named value sets.
\WSH\JScript\Nvsarray.js | Demonstrates the manipulation of named value sets, when the named value has an array data type.
\WSH\JScript\Objpath.js | Shows the manipulation of object paths.
\WSH\JScript\Process.js | Shows how to enumerate processes.
\WSH\JScript\Proparray.js | Shows the manipulation of a property, when the property has an array data type.
\WSH\JScript\Properties.js | Shows the manipulation of the Properties collection of SWbemObject.
\WSH\JScript\Property.js | Shows the manipulation of a property, when the property is not an array data type.
\WSH\JScript\Putinstance.js | Shows how to create a base class and spawn an instance of that class.
\WSH\JScript\Qualarray | Shows the manipulation of qualifiers, when the qualifiers have array values.
\WSH\JScript\Qualifier.js | Shows the manipulation of qualifiers that do not have array values.
\WSH\JScript\System.js | Shows how to get properties from instances of the Win32_ComputerSystem class.

The VBScript samples are as follows.

File | Description
\WSH\VBScript\Cimomid.vbs | Shows how to display WMI installation information.
\WSH\VBScript\Derivation.vbs | Shows the manipulation of the Derivation_ property of SWbemObject.
\WSH\VBScript\Emptyarray.vbs | Shows the manipulation of empty arrays on properties, qualifiers, and named value sets.
\WSH\VBScript\Errmsg.vbs | Shows how to display error object information.
\WSH\VBScript\Methodex.vbs | Shows how to invoke a CIM method as if it were an Automation method of SWbemObject.
\WSH\VBScript\Methodset.vbs | Shows the manipulation of method sets.
\WSH\VBScript\Ntevent.vbs | Shows how to display events in Windows NT/Windows 2000 using a notification query.
\WSH\VBScript\Nvsarray.vbs | Shows the manipulation of named value sets, when the named value is an array data type.
\WSH\VBScript\Objset.vbs | Shows how SWbemObjectSet collections are manipulated.
\WSH\VBScript\Pathbilid.vbs | Shows how to build object paths.
\WSH\VBScript\Privilege.vbs | Shows how to add privileges using the SWbemPrivilegeSet object.
\WSH\VBScript\Process.vbs | Shows how to enumerate processes.
\WSH\VBScript\Resettodefault.vbs | Shows how the SWbemPropertySet.Remove method can return the error code wbemErrResetToDefault when a property is overridden.
\WSH\VBScript\Schema.vbs | Shows browsing of qualifiers, properties, and methods.
\WSH\VBScript\Servicestopped.vbs | Shows how to display all currently stopped services.
\WSH\VBScript\Spawn.vbs | Shows how to create a subclass.
\WSH\VBScript\Startservice.vbs | Shows how to display all installed Windows NT/Windows 2000 services.
\WSH\VBScript\System.vbs | Shows how to display properties from instances of Win32_ComputerSystem.


High-Performance Interface

[This is preliminary documentation and subject to change.]

The Windows Management Instrumentation (WMI) High-Performance API greatly increases the speed at which WMI clients can obtain information from select high-performance WMI providers. Clients of a High-Performance Provider normally issue requests and retrieve data across process boundaries. To cross a process boundary into another address space, the data is marshalled, a relatively slow operation. The WMI Refresher allows data providers and clients to increase their performance by retrieving data without crossing process boundaries.

If both client and server reside on the same machine, the WMI Refresher loads the High-Performance Provider in-process to the client and copies data directly from provider objects into client objects. If client and server reside on different machines, the WMI Refresher provides a performance boost by caching objects on the remote machine and transmitting minimal data sets to the client. The WMI Refresher can also automatically reconnect a client to a remote WMI Service if a network error occurs, or the remote machine is rebooted.

The high-performance provider supplies the performance counters used by the WMI version of the system monitor. For more information on this provider, see Performance Counters Provider. For more information on the High-Performance API itself, see the High-Performance API Reference section.


High-Performance API

[This is preliminary documentation and subject to change.]

The High-Performance API allows you to write WMI providers that can update information for Windows Management Instrumentation (WMI) clients much more rapidly than you can by using standard WMI architecture. Both the client application and the provider must use high-performance interfaces to realize performance gains. For information about how to write a provider using the high-performance interfaces, see High-Performance Provider. For information about how to write client applications that use the high-performance interfaces, see Clients of a High-Performance Provider.

High-performance API interfaces are ideal for developing providers that must rapidly refresh large amounts of data, such as Microsoft® Windows® 2000 performance counter data, to client applications. Windows 2000 platforms come with a high performance provider that provides raw counter data. For more information about this provider, see Performance Counters Provider. For an overview of the High-Performance Interface, see High-Performance Interface.

High-Performance API interfaces | Description
IWbemConfigureRefresher | Used by client application code to add enumerators, objects and nested refreshers into a refresher. WMI provides a native implementation of this interface to allow client code to easily configure refreshers.
IWbemHiPerfProvider | Implemented by providers that supply refreshable objects and enumerators.
IWbemHiperfEnum | Used in refresher operations to provide rapid access to enumerations of instance objects. WMI provides an implementation of this interface which it passes to providers when IWbemHiPerfProvider::CreateRefreshableEnum is called, and it returns to clients when IWbemConfigureRefresher::AddEnum is called. Client applications call the GetObjects method of this interface to retrieve objects from the enumerator.
IWbemObjectAccess | IWbemObjectAccess objects are a container for instances updated by a refresher. The methods of IWbemObjectAccess objects can read and write properties of refreshable objects much faster than equivalent calls to IWbemClassObject::Get and IWbemClassObject::Put.
IWbemRefresher | Provides an entry point through which refreshable objects, enumerators, and other refreshers can be refreshed.


WMI Localization

[This is preliminary documentation and subject to change.]

Windows Management Instrumentation (WMI) implements a technique that allows multiple localized versions of the same class be stored in the repository. To accomplish this the class definition is separated into a language-neutral class definition and one or more language-specific versions.

  • The language-neutral version contains only a basic class definition.
  • The language-specific version contains localized information, such as property descriptions that are specific to a locale.

The language-specific class definitions are stored in a child namespace beneath the namespace that contains a language-neutral basic class definition.

When you request a localized class definition for a specific locale, WMI combines the basic class definition and the localized class information to form a complete localized class. You can get a localized version of a WMI class by specifying a locale when you connect to WMI and setting a flag that indicates that you want localized information. WMI then merges the information from the language-neutral and the language-specific versions of the class definition to form a localized class.

WMI classes that contain localized information are marked with a special qualifier called an amendment qualifier and are called amended classes. You can check to see if a class supports localized information by checking for the amendment qualifier. You can determine what locale the class has been localized for by checking for another qualifier called locale. The locale qualifier contains a localization identifier (Win32 LCID) that identifies a locale. For example, the locale for American English is 0x409. You can tell if a qualifier in an amended class contains localized information by checking for a qualifier flavor called amended.


Localizing WMI Class Information

[This is preliminary documentation and subject to change.]

WMI localization includes these tasks:

  • Creating localized class definitions
  • Compiling localized MOF files
  • Localizing static properties
  • Retrieving amended class information

You can create localized classes by specifying all qualifiers that need to be translatable as amended. For information about how to create amended classes, see Creating Localized Class Definitions.

The MOF compiler splits the original master MOF file into language-neutral and language-specific versions. The language-specific version can be translated into versions for other locales. For information about compiling localized MOF files, see Compiling Localized MOF files.

When you request localized class information, WMI merges the basic class description and the amended class information. For more information about how to retrieve localized class information see Retrieving Amended Classes.


Creating Localized Class Definitions

[This is preliminary documentation and subject to change.]

Creating localized class definitions is a three-step process. You start by writing MOF code that defines the classes, including all qualifiers that need to be localized. This original file is called the master MOF file because it contains all the qualifiers and properties that define the class.

Next, you can use the MOF compiler to create the language-neutral and language-specific versions of the MOF file. The MOF compiler places the basic class description in a new MOF file and creates a localized version of the MOF file that contains only the properties and qualifiers that need to be localized. Although the language-specific and language-neutral versions of the MOF file can have the same file name, you should use an .mfl file extension to indicate that the file contains localized information. You can localize the .mfl file to other locales if it is necessary to support more than one. Storing the class definitions in the CIM repository, requires an additional step of using the MOF compiler to compile both the language-neutral and the language-specific MOF files.

To create and store a localized class definition.

  1. Write the master MOF file that defines the classes you want localized or use the following sample master MOF file code:
    #pragma namespace("\\\\.\\root")

instance of __Namespace
{
    Name = "TEST" ;
} ;

#pragma namespace("\\\\.\\root\\TEST")

[Description("Localized version of MyClass for American English") : Amended, AMENDMENT, LOCALE(0x409)]

class myclass
{
    [DisplayName("User Name") : Amended,
    Description("The Name property contains the name of the user") :
    Amended, key]
     string Name;

    uint64 Value; // non-localized value field

      [DisplayName("Time Stamp") : Amended,
    Description("This property shows when the object was created") :
    Amended]
     uint64 Timestamp;
};

    Save this MOF code in a file called MasterMOF.mof.

  2. Create language-neutral and language-specific versions of the MOF file by compiling the MasterMOF.mof file with the following command:
    mofcomp -MOF:LnMOF.mof -MFL:LsMOF.mfl -Amendment:MS_409 Mastermof.mof
  3. To compile the language-neutral (LnMOF.mof) and language-specific (LsMOF.mfl) files and store the class information in the CIM repository, use the MOF compiler and enter:
    Mofcomp LnMOF.mof
Mofcomp LsMOF.mfl

    After you compile these files, you will have a language-neutral class definition in the Root\Test namespace and a localized class definition in the Root\Test\Ms_409 namespace. For more information about compiling localized MOF files, see Compiling Localized MOF files.


Compiling Localized MOF Files

[This is preliminary documentation and subject to change.]

You must compile your master MOF file to create the language-neutral and language-specific MOF files. The following example shows how to compile a master MOF file.

mofcomp -MOF:LnMOF.mof -MFL:LsMOF.mfl -Amendment:MS_409 Mastermof.mof

When you execute this command, the MOF compiler creates two MOF files from the original MOF file, Mastermof.mof. The MOF compiler produces a language-neutral version, LnMOF.mof, in which all language-specific items are removed. A second, language-specific version, LsMOF.mof, is also created; this file contains only items that were marked with the amended qualifier flavor in the MasterMOF.mof file.

The language-neutral MOF file that is generated (LnMOF.mof) contains the following MOF code:

#pragma namespace("\\\\.\\root")

Instance of __Namespace
{
  Name = "TEST";
};
#pragma namespace("\\\\.\\root\\TEST")

[AMENDMENT,LOCALE(1033)]
class myclass
{
  [key] string Name;
  uint64 Value;
  uint64 Timestamp;
};

The language-specific MOF file that is generated (LsMOF.mfl) contains the following MOF code:

#pragma namespace("\\\\.\\root\\TEST")
instance of __namespace{ name="ms_409";};
#pragma namespace("\\\\.\\root\\TEST\\ms_409")

[Description("Localized version of MyClass for American English") : Amended, AMENDMENT, LOCALE(0x409)]

class myclass
{
    [DisplayName("User Name") : Amended,
    Description("The Name property contains the name of the user") :
    Amended, key]
     string Name;

    [DisplayName("Time Stamp") : Amended,
    Description("This property shows when the object was created") :
    Amended]
     uint64 Timestamp;
};

Compiling a MOF file with the amendment qualifier only generates separate language-neutral and language-specific MOF files; the CIM repository is not updated with the new class information. You must use the MOF compiler to compile the two MOF files that the first compilation produced before any class information will be available to WMI.

When you compile a master MOF file, only qualifiers with the amended flavor will be moved to the language-specific MOF file. Qualifiers that do not have the amended flavor are not localized and will only exist in the basic class definition in the language-neutral MOF file. Non-localized qualifiers could be used for default descriptions to be used if localized descriptions are not available.

You can use the Amendment Pragma Command instead of specifying amendment as a switch to the MOF compiler. Either of these options are equivalent to requesting language-specific and language-neutral versions of a MOF file. If you use either the amendment pragma command or the amendment command-line option, you must specify the name of the output files using the -MFL and -MOF options at the command prompt.

Note The language neutral MOF file that the MOF compiler generates contains the decimal equivalent of the locale ID even if this value was entered in hexadecimal. In the example above, the compiler has converted the value 0x409 to the decimal number 1033 for the output file LnMOF.mof.


Localizing Property Values

[This is preliminary documentation and subject to change.]

The CIM schema localization model provides a mechanism for localizing qualifiers. It does not support direct localization of property values.

In some cases, however, the string properties values in the static instances can be replaced by an enumerated integer type and a value map can be defined for the property in the class definition. In these cases, the Values qualifier should be localized. Using enumeration qualifiers is the principal mechanism of localizing property values. Any other forms of property value localization are not supported.

The following example demonstrates how static properties can be localized using partial value maps with regular expressions. Note in this example the pre-defined subset of values is initialized in the schema using static instances. The rest of the values are provided dynamically.

[abstract]
class DataGroup
{
[key] string GUID;
[Description ("data group display name")]
[ValueMapSyntax("LEX"),
 ValueMap{"Logical Disk",
          "CPU Utilization",
          ".+"},
 Values{{"Logical Disk",
         "CPU Utilization",
         "User-defined"}:amended]
    string GroupDisplayName;

[ValueMapSyntax("LEX"),
 ValueMap{"Monitors percentage of disk free space",
          "Monitors percentage CPU utilization",
          ".+"},
 Values{"Monitors percentage of disk free space",
        "Monitors percentage CPU utilization",
        "User defined data group"}:amended]
string GroupDescription;
}

[static, Description ("pre-configured parameters") :amended]
class InitialGroup : DataGroup {
}

[dynamic, provider("HMProvider"), Description ("user-defined parameters") :amended]
class UserDefionedGroup : DataGroup {
}

instance of InitialGroup {
    GUID = "abc";
    GroupDisplayName = "Logical Disk";
    GroupDescription = "Monitors percentage of disk free space";
}

instance of InitialGroup {
    GUID = "def";
    GroupDisplayName = "CPU Utilization";
    GroupDescription = "Monitors percentage CPU utilization";
}


Localizing Static Properties

[This is preliminary documentation and subject to change.]

You can localize static properties by using partial value maps. The following example demonstrates how static properties can be localized using partial value maps with regular expressions.

To use value maps to localize static properties:

  1. Create a master MOF file (MasterVm.mof) that contains the following MOF code:
    [Locale(0x409)]
class Group1
{
    [key] string ID;
    [DisplayAs("Numbers"),
        ValueMap{0,1,2,3}:amended,
        Values{"Zero", "One", "Two", "Three"}:amended]
    Uint32 Numbers;
};
  2. To create the language-neutral and language-specific versions of the MOF file, use the following command in the MOF compiler.
    mofcomp -MOF:LnVm.mof -MFL:LsVm.mfl -Amendment:MS_409 MasterVm.mof

    The MOF compiler generates the language-specific and language-neutral MOF files LsVm.mfl and LnVm.mfl. The American English values for the Numbers property would be put into the MFL file for the American English namespace. The resulting MFL file, LsVm.mfl, would look like this:

    #pragma namespace("\\\\.\\root\\default")
instance of __namespace{ name="ms_409";};
#pragma namespace("\\\\.\\root\\default\\ms_409")

[AMENDMENT, LOCALE(0x409)]
class Group1
{
  [ValueMap{0, 1, 2, 3} : Amended,
      Values{"Zero", "One", "Two", "Three"} : Amended]
  Uint32 Numbers;
};
  3. To compile the two MOF files and store the class information in the CIM repository, use the MOF compiler and enter the following code:
    Mofcomp LnVm.mof
Mofcomp LsVm.mfl
  4. Localize the MFL file for other locales. For example, a localizer might use data in LsVm.mfl to produce the following MFL file for the French namespace.
    #pragma namespace("\\\\.\\root\\default")
instance of __namespace{ name="ms_40C";};
#pragma namespace("\\\\.\\root\\default\\ms_40C")

[AMENDMENT, LOCALE(0x40C)]
class Group1
{
    [key] string ID;
    [ValueMap{0, 1, 2, 3} : Amended,
        Values{"Zéro", "Un", "Deux", "Trois"} : Amended]
    Uint32 Numbers;
};

The net result is that both the display name and the value of the Numbers property will depend on the locale of the logged-on user. If the user specifies a locale that has not been provided, the default qualifier data will come from the English (ms_409) namespace.

The implication of this design is that each string value is used as a lookup identifier, which cannot be localized. When defining this scheme, you must ensure that the value the provider puts in is locale-independent.

Note  WMI does not currently provide run-time support for mapping values to strings defined by qualifiers. Interpretation of the suggested syntax is the application's responsibility.


Retrieving Amended Classes

[This is preliminary documentation and subject to change.]

You can retrieve and modify an amended class by specifying a locale and setting a flag that indicates that you want localized information. The procedure used to retrieve localized class definitions depends on how you connect to WMI. For more information see:

Retrieving Amended Classes Using the WMI Scripting API

Retrieving Amended Classes Using the WMI COM API


Retrieving Amended Classes Using the WMI Scripting API

[This is preliminary documentation and subject to change.]

If you are using the WMI scripting API to retrieve or store localized class information, specify the locale as part of a moniker. Or, you can supply the locale name in the strLocale parameter to the SWbemLocator.ConnectServer method. To indicate that you want class definitions that have been localized, you should specify wbemFlagUseAmendedQualifiers as a flag for the iFlags parameter for the SWbemServices.Get method. If you use a moniker and specify a locale to connect to WMI, you will get localized data even if you do not use the wbemFlagUseAmendedQualifiers flag. The following example shows how to retrieve a localized class by using a WMI scripting moniker.

Set objwbemobject = GetObject("winmgmts:[locale=ms_409]!root/test:myclass")

The next example shows how to set the locale parameter and use the wbemFlagUseAmendedQualifiers flag.

Set Locator = CreateObject("WbemScripting.SWbemLocator")
Set service = Locator.ConnectServer(, "root\test", , , "ms_409")
Set objwbemobject = _
    service.Get("myclass", wbemFlagUseAmendedQualifiers)


Retrieving Amended Classes Using the WMI COM API

[This is preliminary documentation and subject to change.]

If you are using the WMI COM API to retrieve or store localized class information, specify the locale in the strLocale parameter to the IWbemLocator::ConnectServer interface. When reading or writing amended classes, indicate that you want to use localized class definitions by specifying WBEM_FLAG_USE_AMENDED_QUALIFIERS as a flag for the iFlags parameter. Both synchronous and asynchronous versions of the following methods use this flag.

IWbemServices::CreateClassEnum

IWbemServices::CreateClassEnumAsync

IWbemServices::CreateInstanceEnum

IWbemServices::CreateInstanceEnumAsync

IWbemServices::ExecQuery

IWbemServices::ExecQueryAsync

IWbemServices::GetObject

IWbemServices::GetObjectAsync

IWbemServices::PutClass

IWbemServices::PutClassAsync

IWbemServices::PutInstance

IWbemServices::PutInstanceAsync


Amended Class Considerations

[This is preliminary documentation and subject to change.]

You cannot create instances of the amended classes in the localized namespace. Amended classes in the localized namespace are treated as if they are abstract although they do not contain the abstract qualifier.

If you retrieve an amended class from a localized namespace using the WBEM_FLAG_USE_AMENDED_QUALIFIERS flag and spawn an instance from it, the instance will contain all the amended qualifiers of the amended class. You cannot store this new class in the namespace that contains the basic class definition unless you perform the put operation with the WBEM_FLAG_USE_AMENDED_QUALIFIERS flag. This flag instructs WMI to strip away any amended qualifiers before saving the object. If you do not specify WBEM_FLAG_USE_AMENDED_QUALIFIERS, the put operation will fail with a WBEM_E_AMENDED_OBJECT error.


Security and Authentication

[This is preliminary documentation and subject to change.]

Windows Management Instrumentation (WMI) supports full security for the Microsoft® Windows NT®/Microsoft® Windows® 2000 operating system, and limited security for Windows 95/98. WMI security validates a user's logon information both for the local computer and for remote access. WMI grants a validated user some form of controlled access to the entire Common Information Model (CIM) repository.

In its current release, WMI does not provide security for system resources such as individual classes and instances. However, administrators can use WMI to control global permissions on schema operations, such as limiting the access of some users to read-only operations. WMI also supports per namespace security.

The WMI approach to security is to use a security descriptor (SD) to control access to WMI services. This SD is a standard Windows NT security descriptor, and it contains an access control list (ACL), a list of access control entries (ACEs). Each ACE grants permission to execute a restricted operation, such as writing to a file or formatting a disk. ACEs particular to WMI allow logons, remote access, method execution, and writing to the CIMOM repository.

The WMI SDs are stored in the CIMOM repository. For Windows NT, the actual ACEs are stored. For Windows 95/98, pseudo ACEs are stored.

You can use the WMI Control application to set permissions for WMI users. The WMI Control help file documents how to use this control.

To execute the WMI Control application

From the Start menu, click Run and enter wbemcntl (in Windows 95/98 and Windows NT version 4.0). In Windows 2000, enter wmimgmt.msc.

WMI performs security checks with every call into WMI. Applications can specify security settings at both the process level and the interface level. For more information, see Setting Process Level Security and Setting Interface Level Security.


Per Namespace Security

[This is preliminary documentation and subject to change.]

Each namespace has its own security descriptor (SD), which allows the namespace to have its own security settings. Like the Microsoft® Windows NT® file system (NTFS), inheritance may be used to simplify the administration of security. Each access control entry (ACE) in the namespace SD has a flags field, which indicates what inheritance, if any, is to be performed. For example, if container inheritance is allowed, then the ACE of the namespace SD is inherited by child namespaces.

The SD is constructed when a connection to the namespace is first made. The SD is constructed from the access control lists (ACLs) of the namespaces in the inheritance chain, as modified by the inheritance bits of each namespace. By default, the owner will be the local administrator account, and the local administrators group has rights to all operations, including remote access.

The security of a namespace can be controlled programmatically. For more information, see Programmatic Access to Per Namespace Security.


Authentication

[This is preliminary documentation and subject to change.]

Authentication is the means by which a client process identifies itself to the server. Impersonation is the means by which a client allows a server to call other servers on its behalf.

User identification involves verifying the user name and password, the responsibility of system security packages such as NTLM. Security packages have no information about access rights; their only responsibility is to positively identify valid users.

Depending on the operating system, WMI supports varying levels of authentication. On Microsoft® Windows® 95/98 platforms, all local users are assumed to be authentic, regardless of the user and password. There is no local authentication, and true authentication only occurs over remote connections. On Microsoft® Windows NT®/Windows 2000 systems, all users are authenticated. After authentication, the user is still subject to permissions settings, which are strictly enforced.

Permission assignment involves granting access to valid users and is the responsibility of WMI. Because Windows 95 and Windows 98 are not secure operating systems, granting and denying permissions have less effect on these systems than on other systems. For example; on Windows NT/Windows 2000 systems, file operations may be denied to a user even if WMI considers the user as having full access.

Under Windows NT version 4.0, the only authentication service is NTLM. Under Windows 2000, two additional authentication services are available: Kerberos and Negotiate. Negotiate is recommended for use with code that needs to work in both Kerberos and non-Kerberos domains.

If the client and server are on two different Windows 2000 machines, the default authentication service will be Negotiate. In all other cases, the default authentication service is NTLM.


NTLM Authentication

[This is preliminary documentation and subject to change.]

NTLM is available on all Windows Platforms. On Windows 95/98, it is available as an add-on. Under NTLM, a server can only impersonate a client across a single machine boundary. A server cannot pass (or delegate) a client identity to another machine.


Kerberos Authentication

[This is preliminary documentation and subject to change.]

Kerberos can only be used in remoting scenarios. Attempting to set Kerberos as the authentication package for local proxies will fail. Kerberos requires mutual authentication. In other words, the client must be able to identify the server and the server must be able to identify the client. One of the major features of Kerberos, as applicable to WMI, is that it allows for delegation of a client's identity across multiple machine boundaries. In other words, a client request can be passed by a server to another machine and still maintain the identity of the client. Kerberos is only available on Windows 2000 machines on Windows 2000 networks. If there is no Key Distribution Center (KDC) on a network, attempting to use Kerberos between two Windows 2000 machines will fail.

Negotiate Authentication

[This is preliminary documentation and subject to change.]

When you connect to WMI using two Windows 2000 machines, proxy security automatically defaults to Negotiate. The Negotiate authentication service chooses the best authentication package to use. This is the recommended service to use for applications that must function in both Kerberos and non-Kerberos domains.


Default Access and Permissions

[This is preliminary documentation and subject to change.]

DCOM assumes the current user if no user and password is specified. For remote access, a user name and password can be specified that override the current user. For local access, it is not possible to override the current user name because DCOM does not allow such an override.

By default, any user that is a member of the local administrators group is granted full local and remote access to WMI. This group typically includes the local administrator and the domain administrator.

Registry permissions pertain only to Microsoft® Windows NT®/Microsoft® Windows® 2000 systems. On these systems, registry permissions are set automatically when WMI is installed. Read/write permissions are assigned to members of the administrators group, and read-only permissions to everyone else.

Note Remote logon attempts fail on Windows NT/Windows 2000 systems if the user is not an administrator for the remote system and the Windows Management Service is not already running on the remote system. If the user does have administrative rights on the remote system, DCOM starts the Windows Management Service on the remote system and allows the user to log on, provided that all logon credentials are accepted.


WMI Application Programming

The Windows Management Instrumentation (WMI) SDK is designed for those who create software that uses WMI (such as application developers and provider developers), and those who use WMI to extract management information from a computer organization (such as network administrators and system managers).

The WMI SDK provides tools to build and tailor management applications. You can create applications that extract useful information from the CIM repository or control managed objects.

The following topics are useful for application developers, network administrators, and system managers.

Topic | Description
WMI ODBC Adapter | Use the WMI ODBC adapter to develop database management applications. These applications gain access to data in database management systems (DBMS) using SQL for the WMI ODBC Adapter.
Network Management with SNMP | Seamlessly integrate the modeling and manipulation of SNMP information into WMI.
Scripting API | Develop scripts and Microsoft® Visual Basic® applications to view information about managed objects or to control managed objects.
WMI ADSI Extension | Perform queries to find objects contained in the Microsoft® Active Directory®.
Programming Basics for WMI Applications | Find useful background information for programming WMI applications.
Event Notification | Explore the WMI event model.
Creating a WMI Application in MFC | Walk through the process of creating a WMI application using the Microsoft® Foundation Classes (MFC).


WMI ODBC Adapter

The Open Database Connectivity (ODBC) adapter is used by applications to gain access to data in database management systems (DBMS). The ODBC adapter uses Structured Query Language (SQL) as a standard. You can use the ODBC interface to develop, compile, and ship an application without targeting a specific DBMS.

By using the Windows Management Instrumentation (WMI) ODBC adapter, applications can get information from WMI without using the Component Object Model (COM) API or the Microsoft® ActiveX® controls. This adapter provides a standard API that allows ODBC-based applications to use the data in the Common Information Management (CIM) repository as if the repository were a database. By providing information to ODBC, the WMI ODBC adapter acts as a driver to the ODBC driver architecture.

The WMI ODBC adapter is read-only. You cannot use the WMI ODBC adapter to create tables, add records, or edit records.

For information about the WMI ODBC adapter, see the following sections:

  • About the WMI ODBC Adapter
  • Using ODBC and WMI
  • WMI ODBC Adapter Reference


About the WMI ODBC Adapter

You can set up applications such as Microsoft® Access to use the information provided by Windows Management Instrumentation (WMI) through the WMI Open Database Connectivity (ODBC) adapter. This makes it possible for you to use WMI without having to write programs. For example, you could create a report that contains current statistics, graphs, and charts showing the health of your network. Applications such as Access use the Configure Connection dialog box to gather information needed to connect to WMI.

The WMI ODBC adapter is only supported in conjunction with Access; no other applications are supported.

For more information, including Access limitations, see WMI ODBC Adapter General Information.


WMI ODBC Adapter General Information

This section discusses some general issues that may be helpful when working with the WMI ODBC adapter.

  • The WMI ODBC adapter is supported only on Microsoft® Windows NT® version 4.0 with Service Pack 4 or later. The WMI ODBC adapter is also supported on Microsoft® Windows® 2000 as a value-added extension to the operating system installation of WMI. To install the WMI ODBC adapter on Windows 2000, run the setup program found on the installation CD in the \Valueadd\Msft\Mgmt\Wbemodbc directory.
  • The information you get using the WMI ODBC adapter is read-only, which means you cannot edit any information in the CIM repository.
  • The WMI ODBC adapter supports only SQL SELECT statements.
  • To view WMI system classes (those classes beginning with a double underscore, such as __Namespace) you must invoke SQLTables with a "SYSTEM TABLE" TABLE_TYPE. For more information, see the Microsoft ODBC 2.0 Programmer's Reference and SDK Guide.
  • You can see system class properties by selecting the check box in the Configure Connection dialog box. You can also turn on system properties by adding SYSPROPS=TRUE to the connection string.
  • There are limitations you should be aware of when working with applications that can connect to a WMI ODBC data source. For details, see WMI ODBC Adapter Limitations.


WMI ODBC Adapter Limitations

This section discusses some of the restrictions you may encounter when using the WMI ODBC adapter and other applications.

  • Microsoft Access
  • 16-Bit Client Applications
  • WMI ODBC Adapter Queries and SQL Reserved Words


Microsoft Access

The Access client application uses the ODBC 1.0 SQL_C_LONG and SQL_C_SHORT data types to access 32-bit and 16-bit integers. These data types fetch and display integers as signed integers. As a result, some large unsigned integers in WMI can be displayed as negative numbers in Access.

When linking tables, Access always assumes the same table qualifier for all its invocations. Access caches and uses the table qualifier defined in the first table link. The SQLDriverConnect function is called only once and the connection information is used for all subsequent invocations. Because the WMI ODBC adapter maps the table qualifier to the WMI namespace, all table links are limited to the same WMI namespace. Access makes non-qualified SQLExecDirect calls to the adapter. This is also true for passthrough queries.

There is a known issue with the improper display of 64 bit integers in Access 2000. Whereas Access 97 properly converts integers of type SQL_BIGINT (Sint64 or Uint64) into equivalent character strings, Access 2000 currently will display "box" characters for text strings converted from type SQL_BIGINT.


16-Bit Client Applications

The WMI ODBC adapter does not work with 16-bit client applications. Use the adapter only with 32-bit client applications.


WMI ODBC Adapter Queries and SQL Reserved Words

SQL passthrough queries from Access, Microsoft Query, and Microsoft® Visual Basic® all fail if property names are SQL-reserved words. For example, 'Index' is a reserved word in SQL. If a property named Index is explicitly named in a SELECT clause or is referenced in a WHERE clause, the query will fail. The following WMI CIM classes contain properties named Index:

Win32_SCSIController

Win32_NetworkAdapter

Win32_DiskDrive

Win32_DiskPartition

Win32_POTSModem

Additionally, Microsoft Query expands "SELECT *" into an explicit list of all columns, including Index, which causes an ODBC failure on these classes.

To work around this problem in Access, you must refer to the property in quotation marks, as in the following example:

SELECT "Index" FROM win32_DiskDrive WHERE "Index" = 0


Configure Connection Dialog Box

[This is preliminary documentation and subject to change.]

The Configure Connection dialog box is the most common way for applications to make a connection to an ODBC data source.

The Configure Connection dialog box has the following elements.

Element | Description
User name | Needed only for remote security.
Password | Needed only for remote security.
Interpret empty password as: | Determines how the WMI ODBC adapter processes the Password box if you leave it blank. If you click NULL, the password of the current user is used. If you click Blank, an empty password is used to connect to WMI.
Authority | Indicates the NTLM Domain name to which the user account belongs. Needed only for remote security.
System Properties | Indicates if the driver exposes WMI system properties. Select this box to access system properties.
Impersonation | Indicates that the adapter attempts to impersonate the user account defined by the User name and Password values. It is important not to confuse DCOM impersonation levels with user impersonation associated with services. DCOM impersonation levels specify the permissions granted to individual DCOM calls to WMI. User impersonation attempts to make calls through ODBC as if another user account requested them.
Passthrough only | Indicates that the adapter only attempts to get the query data through a single, direct WQL query statement. Select this box if you want to get a result or a failure quickly.
Server name | Used to connect to WMI on a remote system. Leave this box blank to connect to WMI on the local computer.
 | Displays a dialog box to select namespaces from a remote WMI server. For more information, see Browsing for Namespaces on Remote WMI Servers.
Locale | Indicates the locale to use. If unspecified, the current locale is used.
 | Enables the namespace selection pane so you can select a local or remote namespace. When clicked, changes to Refresh.
 | Equivalent to reconnecting. Any history of selected nodes in the namespace selection pane is lost.

Click Connect, and the namespace selection pane displays namespaces. The namespace selection tree control is cleared of any current information and replaced by the tree control for the new remote server.


Browsing for Namespaces on Remote WMI Servers

[This is preliminary documentation and subject to change.]

In the Configure Connection dialog box, clicking Browse… displays the Server Selection dialog box, which allows you to select namespaces from a remote WMI database.

The Server Selection dialog box initially displays the network resources on the local LAN, and includes the following buttons.

Button | Description
 | Entire Network clears the current display, and displays the chosen network resource.
 | Previous allows you to return to the previous network resource selection.
 | List View displays all the network resources in list view format (parallel columns).
 | Report View displays all the network resources in report view format (single column).


Selecting a Namespace

[This is preliminary documentation and subject to change.]

The namespace selection pane contains a standard tree control showing the nesting of namespaces. Each namespace has an associated check box showing its state. Select the namespace that contains the data to retrieve. For example, select the SNMP branch of the namespace tree to get simple network management protocol (SNMP) data.

Click the check box or folder to select or clear the namespace. If the namespace tree control item has not been expanded, a recursive selection or clearing is performed relative to the current state of the tree control item. If the item is already expanded or has no child tree items, then only the tree control item is affected as specified above.

The state of each tree control item is described by symbols.

Symbol | State
 | Item is not selected and no child items (if any) are selected.
 | Item is selected but no child items (if any) are selected.
 | Item is not selected, but at least one child item is selected.
 | Item is selected and at least one child item is selected.


Installing the WMI ODBC Adapter

The WMI software development kit (SDK) installs the ODBC version 3.0 components (ODBC Driver Manager and administrator), if required. The ODBC 3.0 Driver Manager is backward-compatible with ODBC 2.x drivers.

Use the Control Panel ODBC utility to add, modify, or delete data sources. A system data source known as WBEM Source is created when WMI is installed. WBEM Source is available to all users and services on a computer. You can set up a user data source, which is available only to the current logged-on user, with the Control Panel ODBC utility.

The following steps describe how to add a user data source.

To add a user data source

  1. In Control Panel, double-click the ODBC icon.
  2. In the ODBC utility, click Add on the User DSN tab.
  3. In the Create New Data Source dialog box, select WBEM ODBC Driver.
  4. Click Finish. In the Setup WBEM ODBC Datasource dialog box, you will be prompted for a data source name. This name is just a label you use to refer to this data source. It can be almost any combination of letters or numbers.

If you use the SDK Driver Setup Toolkit, you can install the adapter from the standard Control Panel ODBC utility.

You can install the ODBC software programmatically, silently or non-silently, from Systems Management Server (SMS) startup or a menu option. The SQLInstallODBC function is called to install the ODBC software and drivers/adapters.


ODBC API Conformance

The WMI ODBC adapter reports ODBC API Level 1 conformance, which includes all the functionality of Core Level conformance.

The WMI ODBC adapter includes the following Level 1 functionality:

  • Specifies the schema of database tables and views (using two-part naming).
  • Invokes true asynchronous execution of ODBC functions, where applicable ODBC functions are all synchronous or all asynchronous on a given connection.
  • Uses scrollable cursors, and thereby achieves access to a result set in methods other than forward-only.
  • Obtains primary keys of tables.
  • Uses stored procedures, through the ODBC escape sequence for procedure calls, and queries the data dictionary regarding stored procedures.
  • Connects to a data source by interactively browsing the available servers.
  • Uses ODBC functions instead of SQL statements to perform certain database operations.
  • Gains access to the contents of multiple result sets generated by batches and stored procedures.
  • Delimits transactions spanning several ODBC functions, with true atomicity and the ability to specify SQL_ROLLBACK in SQLEndTran.

For more information about ODBC conformance levels, see Interface Conformance Levels in the ODBC Programmer's Reference section of MSDN™ (Microsoft Developer Network).


Using ODBC and WMI

The following topic shows how to gather information from the Microsoft® Win32® provider about the status of drives attached to your computer. You can use the same techniques to get information from any Windows Management Instrumentation (WMI) provider for applications that can access data using Open Database Connectivity (ODBC).

For more information, see WMI ODBC Adapter and Access 97.


WMI ODBC Adapter and Access 97

You can display WMI provider information through ODBC, using forms in Microsoft® Access® 97. The following steps describe how to use Access with the WMI ODBC adapter.

To get data from WMI using Access and ODBC

  1. From your Access database, click File, and then click Get External Data.

2. Select Link Tables.

  3. In the Link dialog box, select ODBC Databases from the Files of type list.
  4. In the Select Data Source dialog box, there are two tabs: File Data Source and Machine Data Source. If you have saved a file data source previously, you can select it from the File Data Source tab. Otherwise, click the Machine Data Source tab, and you can select either a previously set-up machine data source, or the default machine data source WBEM Source. For more information on WBEM Source, see Installing the WMI ODBC Adapter .
  5. Click OK.
  6. In the Configure Connection dialog box, enter information for User Name, Password, Authority, Server name, and Locale. Usually this information is needed only when you get information from a remote WMI provider. If your Access database application gets data from your own computer, you may be able to leave these boxes blank.
  7. Click Connect.
  8. In the namespace selection pane, click the plus sign next to the root node to expand the tree. Select the check box next to the CIMv2 namespace, and click OK.
  9. Click OK. Common Information Management (CIM) objects are represented as tables in the Link Tables dialog box.
  10. Select an object about which to retrieve information, such as Win32LogicalDisk, and click OK.

    The WMI ODBC adapter displays the properties of CIM objects as if they were fields in a table. The Select Unique Record Identifier dialog box asks that you specify a unique property for each instance of the selected CIM object. In this case, the name of the drive is unique to each drive on a computer system and is stored in the field DeviceID.

  11. Select the unique field, and click OK. The new table is added to your database.

    The information in this linked table is updated each time you access it with a query or an Access form. However, you cannot manually edit any information in it because the WMI ODBC adapter provides read-only access only.


WMI to ODBC Mapping

WMI namespaces map to ODBC databases. In WMI, namespaces are represented by instances of the __NameSpace class. Namespaces can contain child namespaces, which can be enumerated like any other instance of a class.

WMI classes map to ODBC tables. The table qualifier is the fully qualified __NameSpace name. A class is unique. If a class exists in two different namespaces, the adapter maps them as two different tables. Properties of the classes used to represent ODBC tables map to table columns as follows.

WMI | ODBC
Property name | Column name
Property value | Column value
Property qualifiers | Column metadata

The property qualifiers are exposed to the ODBC clients by using SQLColumns. Some of the metadata is used to determine the standard metadata exposed by SQLColumns. All qualifiers are contained as a SQL_LONGVARCHAR in a thirteenth column added to the resultant rowset. The adapter only exposes qualifiers on a per-class basis, not on a per-class, per-instance basis. Therefore, the adapter does not access property qualifier information that varies across instances.

Class qualifiers map to metadata of a table (as exposed through SQLTables). A sixth column of the rowset has been added to SQLTables to return all class qualifiers as a SQL_LONGVARCHAR. The adapter exposes qualifiers on a per-class basis only. Therefore, the adapter does not access class qualifier information that varies across instances.

WMI data types map to ODBC SQL data types. WMI uses variants to return property values. The WMI ODBC adapter supports these variant types. The Cimtype standard qualifier has more semantics than the variant type. For example, if the variant type is BSTR and the Cimtype value is IpAddress, the variant BSTR is in fact an IP address. The adapter uses the Cimtype qualifier sparingly. For more information on data types, see Appendix D of the ODBC 2.0 Programmer's Reference and SDK Guide.

The following table shows the mapping of variant types to ODBC types.

Cimtype type | Data source dependent name | Cimtype qualifier | SQL type
CIM_SINT8 | SINT8 |  | SQL_TINYINT
CIM_UINT8 | UINT8 |  | SQL_TINYINT
CIM_SINT16 | SINT16 |  | SQL_SMALLINT
CIM_UINT16 | UINT16 |  | SQL_SMALLINT
CIM_SINT32 | SINT32 |  | SQL_INTEGER
CIM_UINT32 | UINT32 |  | SQL_INTEGER
CIM_SINT64 | SINT64 |  | SQL_BIGINT
CIM_UINT64 | UINT64 |  | SQL_BIGINT
CIM_DATETIME | TIMESTAMP | DATETIME This property is a string that contains additional information about GMT offset or interval times. GMT offset is ignored, and interval times may be identified by a ":" in the CIM DATETIME string. | SQL_TIMESTAMP
CIM_STRING or CIM_REFERENCE | SMALL_STRING | STRING The property must also have a Max qualifier with a value less than or equal to 254. If the Max qualifier value cannot be retrieved, the default value of 254 is used. | SQL_VARCHAR
CIM_STRING or CIM_REFERENCE | STRING | STRING The property must also have a Max qualifier with a value greater than 254. If the Max qualifier value is greater than 16384, the value is limited to 16384. | SQL_LONGVARCHAR
CIM_REAL32 | REAL |  | SQL_DOUBLE
CIM_REAL64 | DOUBLE |  | SQL_DOUBLE
CIM_BOOLEAN | BIT |  | SQL_BIT
VT_ARRAY | CIM_SINT8 | SINT8_ARRAY |  | SQL_TINYINT
VT_ARRAY | CIM_UINT8 | UINT8_ARRAY |  | SQL_TINYINT
VT_ARRAY | CIM_SINT16 | SINT16_ARRAY |  | SQL_SMALLINT
VT_ARRAY | CIM_UINT16 | UINT16_ARRAY |  | SQL_SMALLINT
VT_ARRAY | CIM_SINT32 | SINT32_ARRAY |  | SQL_INTEGER
VT_ARRAY | CIM_UINT32 | UINT32_ARRAY |  | SQL_INTEGER
VT_ARRAY | CIM_BOOLEAN | BOOL_ARRAY |  | SQL_BIT
VT_ARRAY | CIM_REAL32 | REAL_ARRAY |  | SQL_DOUBLE
VT_ARRAY | CIM_REAL64 | DOUBLE_ARRAY |  | SQL_DOUBLE
VT_ARRAY | CIM_SINT64 | SINT64_ARRAY |  | SQL_BIGINT
VT_ARRAY | CIM_UINT64 | UINT64_ARRAY |  | SQL_BIGINT
VT_ARRAY | CIM_STRING or VT_ARRAY | CIM_REFERENCE | SMALL_STRING_ARRAY | STRING The property must also have a MaxLen qualifier with a value less than or equal to 254. If the MaxLen qualifier value cannot be retrieved, the default value of 254 is used. | SQL_VARCHAR
VT_ARRAY | CIM_STRING or VT_ARRAY | CIM_REFERENCE | STRING_ARRAY | STRING The property must also have a MaxLen qualifier with a value greater than 254. If the MaxLen qualifier value is greater than 16384, the value is limited to 16384. | SQL_LONGVARCHAR
VT_ARRAY | CIM_DATETIME | TIMESTAMP_ARRAY | DATETIME | SQL_TIMESTAMP


WMI Array Mapping to ODBC

As described in the previous table, WMI supports multiple array types. These array types are returned as their basic unit type in multiple ODBC instances. One WMI instance with array type properties maps onto multiple ODBC instances.

For example, a table has two columns: MyKey and MyData. MyKey is a standard integer type while MyData is an array type. This is what the table looks like in the WMI database (two WMI instances).

MyKey | MyData
1 | 12, 24
2 | 6, 100, 255

The WMI ODBC adapter will return the following instances back to the client application (five ODBC instances).

MyKey | MyData
1 | 12
1 | 24
2 | 6
2 | 100
2 | 255

WMI class and property qualifiers that change with the instance of a class are not exposed. WMI associations are only exposed when they are represented by classes. Thus, foreign keys are not used in a table to relate the classes of an association.

An ODBC data source can include several databases. For information on database configuration, see Connecting to a Data Source.


Connecting to a Data Source

In the connection string to SQLDriverConnect, the caller specifies either of the following strings, both of which include the attribute keywords, as described next:

  • "DSN=dataSourceName"
  • "DRIVER=driverName"

In addition to the standard data source name, user name, and password, the adapter recognizes the attribute-keywords listed in Attribute-Keyword Reference.

If you specify the DRIVER keyword, the user is prompted to enter a database category.

If the connection string information is insufficient and fCompletionFlag is not SQL_NO_PROMPT, a dialog box opens for namespace selection. In this dialog box, a tree control shows the nesting of namespaces.


Multi-threading Issues in the Adapter and Client Applications

Because the ODBC Driver Manager is thread-safe, the WMI ODBC adapter is inherently thread-safe.

The only exception to this is when an SQLCancel function is invoked while synchronously executing the hStmt statement handle object from a different thread. The ODBC Driver Manager uses critical sections (non-reentrant pieces of code) on the hEnvs environment handle, hDbcs connection handle, and hStmt handle to guarantee synchronous operation on these objects.

An action on one of these objects causes the ODBC Driver Manager to enter a critical section for that object. In the case of SQLCancel, the ODBC Driver Manager enters a "cancel-in-progress" critical section. This prevents SQLCancel from being reentered before the first SQLCancel function call is completed. The adapter's SQLCancel function is then invoked.

If there is no simultaneous action on the statement handle, the SQLCancel function is treated as an SQLFreeStmt or SQL_CLOSE operation. The adapter returns SQL_SUCCESS_WITH_INFO with an SQLSTATE of 01S05. This causes the ODBC Driver Manager to return SQL_SUCCESS to the application.

If there was simultaneous action on the statement handle, the return code from the original thread's ODBC function determines if the SQLCancel function was successful.

The adapter's SQLCancel function is implemented as follows:

  1. In the adapter, each statement has a critical section.
  2. This critical section is entered on all ODBC functions that take a statement handle (except SQLCancel), and is left upon exit.
  3. The SQLCancel code inspects this critical section to determine if the section has been entered (non-zero owning thread). This is the test for determining if an SQLFreeStmt/SQL_CLOSE statement needs to be called.
  4. If there is activity on the statement, the adapter sets a CANCEL flag on the statement handle, which the original thread periodically checks to determine if the operation should be canceled, to be done in an appropriate manner.

The ODBC 2.0 Programmer's Reference and SDK Guide suggests two techniques for writing thread-safe, multithreaded ODBC applications:

  • Have multiple statement handles on a single connection handle, with a single thread for each statement handle.
  • Have multiple connection handles, with a single statement handle and single thread for each connection handle.

The application must monitor which operations are being performed on an object. For example, if a thread calls the SQLFetch function on a statement handle and begins to process the data, and a second thread calls the SQLFetch function on the same statement handle into the same buffer, the first thread might get columns from the first row of the rowset mixed with columns from the second row.

Also, the application must prioritize when calling the SQLFreeStmt function. For example, if an application attempts to perform an operation on a statement handle that is being freed, the application blocks on the statement handle. When the application unblocks, it fails with an access violation because the statement handle no longer exists. The application must ensure that the statement handle is inactive before calling SQLFreeStmt, SQL_DROP, or SQLDisconnect.


WMI ODBC Adapter Synchronous and Asynchronous Operation

Windows Management Instrumentation

›WMI ODBC Adapter Synchronous and Asynchronous Operation

By default, the WMI ODBC adapter operates in synchronous mode. That is, the adapter does not return control to a client application until the function call is complete.

However, the adapter also supports asynchronous operation. In ODBC, asynchronous processing is performed on a statement-by-statement basis. The following steps describe how to use the adapter asynchronously.

To execute a statement asynchronously

  1. Call SQLSetStmtOption with the SQL_ASYNC_ENABLE option enabled.
  2. Call the ODBC function. The adapter begins asynchronous operation and returns SQL_STILL_EXECUTING.
  3. Perform other operations and call other ODBC functions on different statement handles while the adapter is working.
  4. Optionally, the application can call the original function on the original statement handle to determine if the function has completed. If it has completed, the function returns SQL_SUCCESS or SQL_SUCCESS_WITH_INFO. Otherwise, the function returns SQL_STILL_EXECUTING.

Note The WMI ODBC adapter is a Windows Management Instrumentation client. Therefore, the adapter has limited control over the duration of synchronous WMI API calls, and this duration can be substantial. Applications may have to spawn a thread to implement ODBC functionality. This is especially true for all ODBC client applications designated for use with diverse ODBC data sources.


SQL Grammar

The WMI ODBC adapter supports a subset of the ODBC minimum SQL grammar. It does not support data definition language (DDL) constructs and writeable data manipulation language (DML) constructs. If the data provider supports queries, the adapter decomposes the ODBC minimum SQL into a series of WMI Level 1 queries, and then passes the queries to the data provider. Thus, queries can be optimized for specific data providers.

In Level 1 Provider SQL Grammar, all operations are on a single table, and dynamic parameters are not supported. This grammar can be converted into postfix notation (which means the functions are preceded by all their operands) to facilitate the implementation of a simpler stack-based SQL parser in the data provider.


WMI ODBC Adapter Reference

The following reference topics apply to the implementation of the Windows Management Instrumentation (WMI) Open Database Connectivity (ODBC) adapter:

  • ODBC Minimum SQL Grammar

    • Quick Reference Table

  • Attribute-Keyword Reference


Attribute-Keyword Reference

The following table lists the attribute-keywords recognized by the WMI ODBC adapter.

Keyword | Description
AUTHORITY | Indicates the domain name to which the user account belongs.
DBQ | Database qualifier (the fully qualified, default, working namespace).
HOME | Common root path to all the namespaces specified in the NAMESPACES keyword list.
IMPERSONATE | Indicates that the adapter attempts to impersonate the user account defined by the UID and PWD values.
LOCALE | Indicates the locale to use.
NAMESPACES | Comma-separated list of namespace names.
PASSTHROUGHONLY | Indicates that the adapter only attempts to fetch the query data through a single, direct WQL query statement.
SERVER | Name of the target computer that acts as a WMI server.
SYSPROPS | Indicates whether the adapter exposes WMI system properties.
UIDPWDDEFINED | Indicates that the user name and password have been defined (even if not present in the connection string).


AUTHORITY Attribute-Keyword

The AUTHORITY attribute-keyword indicates the domain name to which the user account belongs. It can take the form of NTLMDOMAIN.DomainName to specify an override domain. You can also specify authority using the Authority check box in the Configure Connection dialog box.


DBQ Attribute-Keyword

The DBQ attribute-keyword is the database qualifier. This is the fully-qualified, default, working namespace.


HOME Attribute-Keyword

The HOME attribute-keyword is the common root path name to all the namespaces specified in the NAMESPACES keyword list. If the HOME keyword is defined, all names in the NAMESPACES list are assumed to be relative to the HOME namespace. The fully-qualified namespace path can be derived by adding the HOME namespace (as a prefix) to each of the names in the NAMESPACE list. If the HOME keyword is not defined, all namespaces in the NAMESPACES list are assumed to be fully qualified. The following example shows the fully-qualified namespace root\redmond\fred:

HOME=Root\Redmond;NAMESPACES=Fred


IMPERSONATE Attribute-Keyword

The IMPERSONATE attribute-keyword indicates that the WMI ODBC adapter attempts to impersonate the user account defined by the UID and PWD values. This is similar to setting up a service to log on as a different user to grant it different permissions than the current user.

Impersonation fails if the host account is not set up with sufficient security permissions. To set up a Microsoft® Windows NT®/Microsoft® Windows® 2000 system for impersonation, you need to be logged on as administrator on the computer where the WMI ODBC adapter is installed.

To set up a system for impersonation

  1. From the Tools menu, choose User Manager for Domains and set up the privilege Act as part of the operating system for the user account you will be running under (not the account you are trying to impersonate).
  3. Restart your computer to activate these settings/tokens.

The IMPERSONATE keyword acts as a flag and does not require any value. This keyword can be omitted if not needed.

You can also specify impersonation using the Impersonation check box in the Configure Connection dialog box.

Impersonation is not supported on Windows 95.

Note It is important not to confuse DCOM impersonation levels with user impersonation associated with services. DCOM impersonation levels specify the permissions granted to individual DCOM calls to WMI. User impersonation attempts to make calls through ODBC as if another user account requested them.


LOCALE Attribute-Keyword

The LOCALE attribute-keyword indicates the locale to use. If this is not specified, the current locale is used. For Microsoft locale identifiers, the format of the string is "MS_xxxx", where xxxx is a string in hexadecimal form that indicates the locale identifier (LCID). For example, American English would appear as "MS_409".

You can also specify locale using the Locale check box in the Configure Connection dialog box.


NAMESPACES Attribute-Keyword

The NAMESPACES attribute-keyword is a comma-separated list of namespace names. Unless the HOME keyword is specified, these must be fully-qualified namespaces that the adapter can use directly with the WMI API.

Specify the namespace names as follows, where style can be either shallow (the default, include only the specified namespace), or deep (include the specified namespace and all its children):

NAMESPACES={namespace, style}

The following examples both specify just the root\default namespace:

NAMESPACES={Root\Default, shallow}
NAMESPACES=Root\Default

The following example specifies the root\default namespace and all its children:

NAMESPACES={Root\Default, deep}

The following example specifies the Root\MyNamespace namespace plus the Root\OtherNamespace namespace plus all the children of the root\cisco namespace:

NAMESPACES={Root\MyNamespace , shallow},{Root\OtherNamespace, deep}


PASSTHROUGHONLY Attribute-Keyword

The PASSTHROUGHONLY attribute-keyword indicates that the WMI ODBC adapter only attempts to fetch the query data through a single, direct WQL query statement. Use this option to get a success or failure report right away.

If you do not specify PASSTHROUGHONLY, the adapter attempts to get the query data through an alternative route and the query may take a long time before returning the data or failing. If you specify PASSTHROUGHONLY, the adapter succeeds or fail immediately. You can also activate passthrough-only mode through the Passthrough only check box in the Configure Connection dialog box.

The PASSTHROUGHONY keyword acts as a flag and does not require any value. This keyword can be omitted if not needed.


SERVER Attribute-Keyword

The SERVER attribute-keyword is the name of the target computer that acts as a WMI server. This attribute-keyword is used primarily to specify a remote WMI server. If this attribute-keyword is omitted, the local WMI server is used. The following example shows a remote WMI server:

SERVER=\\MYSERVER


SYSPROPS Attribute-Keyword

The SYSPROPS attribute-keyword indicates whether the WMI ODBC adapter exposes WMI system properties. Set this keyword to TRUE to expose system properties; that is, in the connection string, include SYSPROPS=TRUE. You can also activate system properties using the check box control in the Configure Connection dialog box.

Currently, under certain queries, the use of SYSPROPS=TRUE results in some additional properties being returned which would not be expected in a typical SQL environment. For example, the following statement returns all system properties and all non-system properties, as expected:

SELECT * FROM MyClass

However, you cannot at this time specify the return of a partial set of the system properties. For example, the following statement returns MyProperty and ALL system properties.

SELECT __CLASS, MyProperty FROM MyClass

In addition, specifying only system properties in a select list returns all system properties and all non-system properties, as if you had specified "SELECT * FROM MyClass" instead of the following:

SELECT __CLASS FROM MyClass


UIDPWDDEFINED Attribute-Keyword

The UIDPWDDEFINED attribute-keyword indicates that the user name and password have been defined (even if they are not present in the connection string). This keyword has been added to fix some optimizations performed by a number of client applications. Some client applications check the values of the user name and password in the connection string. If these values are defined as empty strings, the applications will remove these keyword/value pairs from the connection string. As a consequence of this removal, and the fact that user name and password are mandatory parameters for a full connection, a no-prompt connection would thus fail. Using the UIDPWDDEFINED keyword forces the adapter to flag that the user name and password are defined.

The UIDPWDDEFINED keyword acts as a flag and does not require any value. This keyword can be omitted if not needed.


Network Management with SNMP

The Simple Network Management Protocol (SNMP) is a well-established, widely used technology. It is a protocol used in conjunction with LAN and WAN-based devices, and is primarily used to configure and administer parameters on routers, repeaters, bridges, and so forth. This topic presents material on using SNMP in conjunction with WMI in the following sections:

  • Mapping SNMP to the CIM Schema. Simple Network Management Protocol (SNMP) uses a schema to define objects. This schema is different from the schema used in Windows Management Instrumentation (WMI).
  • SNMP Troubleshooting Guide. This guide is designed to help users retrieve information from a Simple Network Management Protocol (SNMP) device.
  • SNMP Support. The following components to support SNMP are included: class providers, instance providers, event providers, and an SNMP information module compiler.


Mapping SNMP to the CIM Schema

Simple Network Management Protocol (SNMP) uses a schema to define objects. This schema is different from the schema used in Windows Management Instrumentation (WMI). The SNMPv1 and SNMPv2C schema, called the Structure of Management Information (SMI), is packaged as Management Information Base (MIB) files. MIB files define objects using a standard language — Abstract Syntax Notation 1 (ASN.1) — and a number of macro definitions that serve as templates for describing the objects. The macros provide information such as the object's name, identifier, syntax, description, access rights, protocol operations, and protocol encoding.

The SNMP providers convert the following MIB macros.

Macro | Description
OBJECT-TYPE | SNMPv1 and SNMPv2C. Describes the basic characteristics of an object, such as the object name, syntax, access rights, and so forth.
TEXTUAL-CONVENTION | SNMPv2C only. Assigns a name and, in some cases, a range of values to an existing data type.
TRAP-TYPE | SNMPv1 only. Describes event messages (traps).
NOTIFICATION-TYPE | SNMPv2C only. Describes event messages (notifications).

The SNMP class provider uses the services of the MIB correlator and the SMIR to enumerate and instantiate a set of class definitions against a CIM namespace. The SNMP class provider supports two modes:

  • Correlated
  • Non-correlated

A special flag designates whether the mode is correlated or non-correlated. This flag can be set either by attaching qualifiers to the namespace or by specifying the "correlated" context value in an IWbemContext object. This context value is a Boolean with the key name "Correlate" that can be set to the Boolean value VARIANT_TRUE or VARIANT_FALSE. The context object takes precedence over the qualifiers if both are specified. The default mode is correlated.

The SNMP class provider enumerates class definitions with IWbemServices::CreateClassEnum or IWbemServices::CreateClassEnumAsync. The SNMP class provider retrieves a class definition with IWbemServices::GetObject or IWbemServices::GetObjectAsync.

For each class returned by the provider, the class is modified so that all qualifiers present within the containing namespace are inherited by that class.

The SNMP instance provider maps SNMP MIB objects to class instances. The SNMP instance provider enumerates class instances with IWbemServices::CreateInstanceEnum or IWbemServices::CreateInstanceEnumAsync. The SNMP instance provider retrieves class instances with IWbemServices::GetObject or IWbemServices::GetObjectAsync.

Applications can retrieve a particular instance, create a particular instance from MIB data, and enumerate instances of an SNMP CIM class.

The following topics explain how class definitions and instances of classes are created from MIB object data:

Enumerating SNMP Class Definitions

Instantiating SNMP Class Definitions

Retrieving an SNMP Class Instance

Instantiating SNMP Class Instances of CIM SNMP Classes

Enumerating SNMP Class Instance


Mapping the OBJECT-TYPE Macro

The OBJECT-TYPE macro describes the basic characteristics of an individual MIB object. A set of OBJECT-TYPE macros can be considered as a group of related objects. In SNMPv2C, you can use the OBJECT-GROUP macro to formally group sets of related objects into a collection. However, there is no formal mechanism for creating collections in SNMPv1. For the purposes of the SNMP providers, the OBJECT-GROUP macro is ignored, but you can invent grouping relationships and fabricate collections.

Fabricating Collections

You can fabricate collections for each SNMPv1 and SNMPv2C information module. You can fabricate both scalar and table collections. The following notation is needed to understand how collections are created:

  • A named node in an SNMP information module is a definition of the form:
    namedNode OBJECT IDENTIFIER ::= <object identifier value>
  • The function objId, applied to a named node, returns the object identifier assigned to that named node.
  • The function objId, applied to an instance of the OBJECT-TYPE macro, returns the object identifier value assigned to that instance.

Using the preceding notation, the manner in which collections are fabricated can be stated as follows:

Scalar Collections

Let n be a named node in an SNMP information module M, and CS(M,n) the set of OBJECT-TYPE instances in M defined by:

CS(M,n) = { s | s is a scalar and objId(s) = objId(n).x, for some integer x}

Then if CS(M,n) is not empty, it defines a scalar collection for the SNMPv1 or SNMPv2C information module M.

Table Collections

Let n be a named node in an SNMP information module M, and CT(M,n) the set of OBJECT-TYPE instances in M defined by:

CT(M,n) = { c | c is a column of table n and objId(c) = objId(n).x.y, for some integers x, y}

Then if CT(M,n) is not empty, it defines a table collection for the SNMPv1 or SNMPv2C information module M.

Mapping Process

These definitions provide a basis for the following mapping process used by the SNMP providers:

  1. All objects in a table collection map to properties of a single CIM class definition. The object descriptor for a table collection is defined as the object descriptor of n for CT(M,n).
  2. All objects in a scalar collection map to properties of a single CIM class definition. The object descriptor for a scalar collection is defined as the object descriptor of n for CS(M,n).


CIM Property and Qualifier Compliance

The following topics briefly describe the CIM system properties, class qualifiers, and property qualifiers used by the SNMP providers when mapping the MIB OBJECT-TYPE macro to CIM class definitions.


CIM System Properties

WMI defines a set of system properties that are associated with all classes and instances of classes in addition to class-specific properties. (For more information on class-specific properties, see WMI System Properties.)

The SNMP providers use the following CIM system properties when mapping MIB object definitions to CIM class definitions. Mandatory properties must be present for the SNMP providers to fully resolve a group object. Failure to define a mandatory property returns an error.

Property name | Property syntax | Status | Description
__CLASS | string | Mandatory | For instances, the class to which the object belongs. For classes, this is the class name.
__DYNASTY | string | Optional | The name of the class that is the ultimate base class for the current object (not its immediate parent class).
__GENUS | uint32 | Mandatory | Type of object. Can be one of : 1 - Class 2 - Instance
__NAMESPACE | string | Mandatory | The namespace where the object is located.
__PATH | string | Mandatory | The absolute path to the object.
__PROPERTYCOUNT | uint32 | Mandatory | The number of non-system properties defined for the object.
__RELPATH | string | Mandatory | The relative path to the object.
__SERVER | string | Mandatory | The server supplying the object.
__SUPERCLASS | string | Optional | The immediate parent class of the object.


CIM Class Qualifiers

The SNMP providers use the following CIM class qualifiers when mapping MIB object definitions to CIM class definitions. A mandatory qualifier must be present for the SNMP providers to fully resolve a group object. Failure to define a mandatory qualifier returns an error. Specifying an illegal qualifier value also returns an error.

Qualifier | Qualifier syntax | Status | Description
description | string | Optional | Describes the class.
group_objectid | string | Optional | Specifies the object identifier of the fabricated collection. It is mandatory if the class is for the SNMP class provider.
module_imports | string | Optional | Contains a comma-separated list of MIB module names used to resolve imports.
module_name | string | Optional | Specifies the identity name of a MIB module.
reference | string | Optional | Refers to another document that contains additional information about the class.
singleton | Bool | Mandatory for classes mapped from scalar collections. | Indicates a class that can only have one instance.


CIM Property Qualifiers

The SNMP providers use the following CIM property qualifiers when mapping MIB object definitions to CIM class definitions. A mandatory qualifier must be present for the SNMP providers to fully resolve a MIB object. Failure to define a mandatory qualifier returns an error. Specifying an illegal qualifier value also returns an error.

Qualifier | Qualifier syntax | Status | Description
bits | string | Mandatory if textual_convention == BITS. | Specifies enumerated values for the subtype definition of a bit.
cimtype | string | Mandatory. | Specifies the CIM textual representation that formats an underlying CIM protocol value.
defval | string | Optional. | Specifies the object's default value.
description | string | Optional. | Describes the object.
display_hint | string | Optional. | Specifies how the object's data should appear to a user.
encoding | string | Optional. | Specifies the SNMP type used when encoding SNMPv1 and SNMPv2C protocol frames.
enumeration | string | Mandatory if textual_convention == ENUMERATEDINTEGER. | Specifies enumerated values for an enumerated integer subtype definition.
fixed_length | uint32 | Optional. | Specifies fixed-length value.
key | Bool | Optional. | Indicates a key property of a class definition.
key_order | uint32 | Optional; mandatory if key is specified. | Specifies the order of the key property in the class definition.
name | string | Mandatory; note that this qualifier is not explicitly defined. | The implicit name of the property.
object_identifier | string | Mandatory. | The object's MIB object identifier.
object_syntax | string | Optional. | Specifies the object's named type definition.
read | Bool | Optional; at least one of read or write must be specified. | Grants read access to the object.
reference | string | Optional. | Refers to another document that contains additional information about the object.
status | string | Optional. | Indicates whether the object must be supported.
textual_convention | string | Mandatory. | The textual representation of the SYNTAX clause of the MIB OBJECT-TYPE macro.
units | string | Optional. | Precisely defines what the object represents.
variable_length | string | Optional. | Specifies the minimum, maximum, and fixed-length values associated with the object's type definition.
variable_value | string | Optional. | Specifies the ranged and fixed values associated with the object's type definition.
virtual_key | Bool | Optional. | Specifies that the property's value should be based on the superset of instance information associated with all accessible MIB objects in the class definition.
write | Bool | Optional; at least one of read or write must be specified. | Grants write access to the object.


Mapping Collections to CIM Classes

Windows Management Instrumentation

Mapping SNMP Collections to CIM Classes

The following rules apply when mapping SNMP collections to CIM classes. Unless otherwise specified, these rules apply to both scalar and table collections:

  • A collection maps to a CIM class.
  • The elements of a collection map to properties of a CIM class.
  • All generated CIM class definitions must be derived from the SnmpObjectType class. The following class definitions parent all generated class definitions:
    [abstract]
class SnmpMacro
{
};

[abstract]
class SnmpObjectType:SnmpMacro
{
};
  • The mapping process generates CIM class names by concatenating "SNMP_", the MIB module identity name, "_", and the collection's object descriptor. For example:

    system translates to SNMP_RFC1213_MIB_system

    ifTable translates to SNMP_RFC1213_MIB_ifTable

    In all cases, hyphens (-) in SNMP MIB identifiers map to underscores (_) in CIM class names.

  • Naming conflicts can occur due to CIM name case-insensitivity. If a naming conflict occurs, the providers choose one of the conflicting group definitions and ignore the remaining definitions.
  • The identity name of the MIB module that contains the collection maps to the CIM class qualifier module_name.
  • The object identifier of the fabricated collection maps to the CIM class qualifier group_objectid.
  • The MIB module imports list (obtained from the MODULE-IDENTITY macro definition) maps to the CIM class qualifier module_imports. This qualifier contains a comma-separated list of module names.


Mapping Components of the OBJECT-TYPE Macro

The OBECT-TYPE macro contains mandatory and optional clauses that describe the basic characteristics of a MIB object. The SNMP providers convert the following parts of the OBJECT-TYPE macro:

object descriptor, which assigns a name to a MIB object.

SYNTAX clause, which defines the MIB object's data and type.

INDEX clause, which defines a key for selecting a unique table row.

AUGMENTS clause, which can replace the INDEX clause in SNMPv2C.

OBJECT-IDENTIFIER, which assigns a unique identifier to the MIB object.

ACCESS and MAX-ACCESS clauses, which define the access rights to the MIB object.

DESCRIPTION clause, which describes the MIB object.

STATUS clause, which indicates whether the MIB object must be supported.

DEFVAL clause, which assigns a default value to a MIB object.

REFERENCE clause, which cross-references additional information about the MIB object.

UNITS clause, which provides a more precise definition of what the MIB object represents.


Mapping MIB Object Descriptors

A unique name or object descriptor identifies each MIB object. Each MIB object descriptor maps verbatim to a CIM property name. For example, ifIndex translates to ifIndex.


Mapping the SYNTAX Clause

The OBJECT-TYPE macro contains a SYNTAX clause that defines the MIB object's data and type. The SYNTAX clause refers to one of the following types.

Type | Description
SNMP primitive type | One of the basic data types defined in the Structure of Management Information (SMI) documents RFC 1213 and RFC 1903.
SNMP textual convention | A type definition generated through the explicit use of the SNMPv2C TEXTUAL-CONVENTION macro or generated through the use of a named type. A textual convention assigns a name and, in some cases, a range of values to an existing data type (for example, the SNMPv1 named type Displaystring within RFC 1213).
SNMP constrained type | A primitive type, named type, or textual convention that has been constrained by some subtyping mechanism defined in the SMI documents RFC 1213 and RFC 1903.
SNMP named type | A named reference to a primitive type, textual convention, or constrained type.

The topics that follow describe the mapping process for each of these types.


General Type Mapping Rules

The following mapping rules apply to all of the data types described in Mapping the SYNTAX Clause:

  • The textual representation of the SYNTAX clause maps to the CIM property qualifier textual_convention.
  • The named type definition in the SYNTAX clause maps to the CIM property qualifier object_syntax. This mapping differs depending on the data type. See the individual mapping descriptions for details.
  • The SNMP type used when encoding SNMPv1 and SNMPv2C protocol frames maps to the CIM property qualifier encoding.
  • The CIM property qualifier cimtype contains the textual representation that formats the underlying CIM protocol value.


SNMP Primitive Types

SNMP primitive types map to CIM defined types. The following tables define the mapping when the SYNTAX clause explicitly refers to a primitive type.


Table 1: Mapping SNMPv1 Primitive Types

MIB Type | CIM Variant Type | CIM Qualifier: textual_convention | CIM Qualifier: encoding | CIM Qualifier: object_syntax | CIM Qualifier: cimtype | Default Value
INTEGER | VT_I4 | INTEGER | INTEGER | INTEGER | sint32 | NULL
OCTET STRING | VT_BSTR | OCTETSTRING | OCTETSTRING | OCTETSTRING | string | NULL
OBJECT IDENTIFIER | VT_BSTR | OBJECTIDENTIFIER | OBJECTIDENTIFIER | OBJECTIDENTIFIER | string | NULL
NULL | VT_NULL | NULL | NULL | NULL | Not supported (1) | NULL
IpAddress | VT_BSTR | IpAddress | IpAddress | IpAddress | string | NULL
Counter | VT_I4 | Counter | Counter | Counter | uint32 | NULL
Gauge | VT_I4 | Gauge | Gauge | Gauge | uint32 | NULL
TimeTicks | VT_I4 | TimeTicks | TimeTicks | TimeTicks | uint32 | NULL
Opaque | VT_BSTR | Opaque | Opaque | Opaque | string | NULL
NetworkAddress | VT_BSTR | NetworkAddress | NetworkAddress | NetworkAddress | string | NULL

(1) The OBJECT-TYPE macro is ignored when its SYNTAX clause refers to NULL, either explicitly or through a named type assignment.


Table 2: Mapping SNMPv2C Primitive Types

MIB Type | CIM Variant Type | CIM Qualifier: textual_convention | CIM Qualifier: encoding | CIM Qualifier: object_syntax | CIM Qualifier: cimtype | Default Value
INTEGER | VT_I4 | INTEGER | INTEGER | INTEGER | sint32 | NULL
OCTET STRING | VT_BSTR | OCTETSTRING | OCTETSTRING | OCTETSTRING | string | NULL
OBJECT IDENTIFIER | VT_BSTR | OBJECTIDENTIFIER | OBJECTIDENTIFIER | OBJECTIDENTIFIER | string | NULL
IpAddress | VT_BSTR | IpAddress | IpAddress | IpAddress | string | NULL
Counter32 | VT_I4 | Counter32 | Counter32 | Counter32 | uint32 | NULL
Gauge32 | VT_I4 | Gauge32 | Gauge32 | Gauge32 | uint32 | NULL
Unsigned32 | VT_I4 | Unsigned32 | Unsigned32 | Unsigned32 | uint32 | NULL
Integer32 | VT_I4 | Integer32 | Integer32 | Integer32 | sint32 | NULL
Counter64 | VT_BSTR | Counter64 | Counter64 | Counter64 | uint64 | NULL
TimeTicks | VT_I4 | TimeTicks | TimeTicks | TimeTicks | uint32 | NULL
Opaque | VT_BSTR | Opaque | Opaque | Opaque | string | NULL

The following mapping rules apply to SNMP primitive types:

  • The previously stated general type mapping rules apply.
  • The named type definition in the SYNTAX clause maps verbatim to the CIM property qualifier object_syntax.


SNMP Textual Conventions

SNMP textual conventions map to CIM defined types. The following table defines the mapping when the SYNTAX clause explicitly refers to a textual convention (through the use of the SNMPv2C TEXTUAL-CONVENTION macro) or refers to an implied textual convention.


Table 3: Mapping SNMPv1 and SNMPv2C Textual Conventions

Textual Convention | CIM Variant Type | CIM Qualifier: textual_convention | CIM Qualifier: encoding | CIM Qualifier: object_syntax | CIM Qualifier: cimtype | Default Value
DateAndTime | VT_BSTR | DateAndTime | OCTETSTRING | DateAndTime | string | NULL
Displaystring | VT_BSTR | Displaystring | OCTETSTRING | Displaystring | string | NULL
MacAddress | VT_BSTR | MacAddress | OCTETSTRING | MacAddress | string | NULL
PhysAddress | VT_BSTR | PhysAddress | OCTETSTRING | PhysAddress | string | NULL
SnmpUDPAddress | VT_BSTR | SnmpUDPAddress | OCTETSTRING | SnmpUDPAddress | string | NULL
SnmpOSIAddress | VT_BSTR | SnmpOSIAddress | OCTETSTRING | SnmpOSIAddress | string | NULL
SnmpIPXAddress | VT_BSTR | SnmpIPXAddress | OCTETSTRING | SnmpIPXAddress | string | NULL

The following mapping rules apply to SNMP textual conventions.

  • The previously stated general type mapping rules apply.
  • The named type definition in the SYNTAX clause maps verbatim to the CIM property qualifier object_syntax.
  • For textual conventions that are not listed in the preceding table, the CIM-defined variant type, and the CIM property qualifiers textual_convention, encoding, object_syntax, and cimtype, map using the underlying primitive type (which may be generated through a type assignment hierarchy) and the mapping specified in Table 1 and Table 2.
  • The DISPLAY-HINT clause of the SNMPv2C TEXTUAL-CONVENTION macro maps verbatim to the CIM property qualifier display_hint. This qualifier is not generated if there is no TEXTUAL-CONVENTION macro, or the macro does not contain a DISPLAY-HINT clause.

SNMPv1 Textual Convention Example

   myNamedType ::= DISPLAYSTRING (SIZE (0..127))

   myNamedProperty OBJECT-TYPE
   SYNTAX  myNamedType
   ACCESS read-only
   STATUS MANDATORY
   DESCRIPTION ""

This example generates the following CIM qualifiers:

object_syntax("myNamedType"),
textual_convention("DISPLAYSTRING"),
encoding("OCTETSTRING"),
variable_length("0..127")

SNMPv2C Textual Convention Example

myDisplaystring ::= TEXTUAL-CONVENTION
DISPLAY-HINT "255a"
STATUS current
DESCRIPTION ""
SYNTAX OCTET STRING (SIZE (0..127))

myNamedProperty OBJECT-TYPE
SYNTAX  myDisplaystring
MAX-ACCESS read-only
STATUS current
DESCRIPTION ""

This example generates the following CIM qualifiers:

object_syntax("myDisplaystring"),
textual_convention("OCTETSTRING"),
encoding("OCTETSTRING"),
display_hint("255a"),
variable_length("0..127")


SNMP Constrained Types

The following topics define the mapping when subtyping is applied to a primitive type, named type, or textual convention. When subtyping occurs, additional CIM qualifiers are required to specify the subtype values.

Mapping Subtype Enumeration Definitions

The following table defines the mapping when the SYNTAX clause refers to a primitive type, named type, or textual convention that is subtyped as enumerated INTEGER. In this case, the CIM property qualifier enumeration is used to specify the enumerated values.


Table 4: Mapping SNMPv1 and SNMPv2C Subtype Enumeration Definitions

Constrained MIB Type | CIM Variant Type | CIM Qualifier: textual_convention | CIM Qualifier: encoding | CIM Qualifier: cimtype | Default Value
Enumerated Integer | VT_BSTR | enumeratedinteger | INTEGER | string | NULL

The following mapping rules apply to subtype enumeration definitions:

  • The previously stated general type mapping rules apply.
  • The named type definition in the SYNTAX clause maps verbatim to the CIM property qualifier object_syntax up to but not including the enumerated value assignments.
  • The CIM property qualifier enumeration specifies the enumerated values. This qualifier is represented as a string containing a comma-separated list of signed 32-bit integer values.

Enumerated INTEGER Subtype Example

Status := INTEGER {

up(1),
down(2),
testing(3)
}

This example maps to:

enumeration("up(1),down(2),testing(3)")

Mapping Subtype BITS Definitions

The following table defines the mapping when the SYNTAX clause refers to a primitive type, named type, or textual convention that is subtyped as BITS. In this case, the CIM property qualifier bits is used to specify the enumerated values.


Table 5: Mapping the Subtype BITS Definitions

Constrained MIB Type | CIM Variant Type | CIM Qualifier: textual_convention | CIM Qualifier: encoding | CIM Qualifier: cimtype | Default Value
BITS | VT_ARRAY | VT_BSTR | bits | OCTETSTRING | string | NULL

The following mapping rules apply to subtype BITS definitions:

  • The previously stated general type mapping rules apply.
  • The named type definition in the SYNTAX clause maps verbatim to the CIM property qualifier object_syntax up to but not including the enumerated value assignments.
  • The CIM property qualifier bits specifies the enumerated values. This qualifier is represented as a string containing a comma-separated list of signed 32-bit integer values.

BITS Subtype Example

Status := BITS {

up(1),
down(2),
testing(3)
}

This example maps to:

bits("up(1),down(2),testing(3)")

Mapping Variable-Length Subtype Definitions

The following mapping rules apply when the SYNTAX clause refers to a primitive type, named type, or textual convention that is subtyped as a variable-length OCTET STRING or Opaque:

  • The previously stated general type mapping rules apply.
  • The named type definition in the SYNTAX clause maps verbatim to the CIM property qualifier object_syntax up to but not including the size constraints.
  • The CIM property qualifier variable_length specifies the minimum, maximum, and fixed-length values associated with the type definition. This qualifier is implemented as a string in the following format where the variable-length values are represented as unsigned 32-bit integers:
    (((0.9) .. (0.9)) | (0.9))(, (((0.9) .. (0.9)) | (0.9)))*

Variable-length Subtype Example

MySnmpOSIAddress ::=  TEXTUAL-CONVENTION

    DISPLAY-HINT    "*1x:/1x:"
    STATUS        current
    DESCRIPTION
            "Represents an OSI transport-address:

               octets   contents           encoding
                  1     length of NSAP     'n' as an unsigned-integer
                                              (either 0 or from 3 to 20)
               2..(n+1) NSAP                concrete binary representation
               (n+2)..m TSEL               string of (up to 64) octets
            "
    SYNTAX         OCTET STRING (SIZE (1|4..85))

This example maps to:

display_hint("*1x:/1x:"),
encoding("OCTETSTRING"),
textual_convention("OCTETSTRING"),
variable_length ("1,4..85")

Mapping Fixed-Length Subtype Definitions

The following mapping rules apply when the SYNTAX clause refers to a primitive type, named type, or textual convention that is subtyped as a fixed-length OCTET STRING or Opaque:

  • The previously stated general type mapping rules apply.
  • The named type definition in the SYNTAX clause maps verbatim to the CIM property qualifier object_syntax up to but not including the fixed-length value.
  • The CIM property qualifier fixed_length specifies the fixed-length value. This qualifier is represented as an unsigned 32-bit integer value.

Fixed-length Subtype Example

IPXADDRESS := OCTET STRING (SIZE (6))

This example maps to:

fixed_length(6)

Mapping Range Subtype Definitions

The following mapping rules apply when the SYNTAX clause refers to a primitive type, named type, or textual convention that is subtyped as a ranged or fixed-value INTEGER or Gauge:

  • The previously stated general type mapping rules apply.
  • The named type definition in the SYNTAX clause maps verbatim to the CIM property qualifier object_syntax up to but not including the ranged or fixed value.
  • The CIM property qualifier variable_value specifies the ranged and fixed values associated with the type definition. This qualifier is implemented as a string in the following format where the range and fixed-length values are represented as unsigned 32-bit integers:
    (((0.9)..(0.9))|(0.9))(,(((0.9)..(0.9))|(0.9)))*

Range Subtype Example

Status := INTEGER (10..20|8)

This example maps to:

variable_value("10..20,8")


SNMP Named Types

SNMP named types map to CIM defined types. When the SYNTAX clause refers to a primitive type, textual convention, or constrained type through a type assignment derivation, use the following process to determine which mapping procedures apply.

If, through derivation of the type assignment rules:

  1. You encounter a constrained type definition, and if, through further derivation:
    1. You encounter one of the textual conventions listed in Table 3, then apply the mapping rules for constrained types and textual conventions.
    2. Otherwise, if you encounter one of the primitive types listed in Table 1 or Table 2, apply the mapping rules for primitive types and constrained types.
  2. Otherwise, if you encounter one of the textual conventions listed in Table 3, apply the mapping rules for textual conventions.
  3. Otherwise, if you encounter one of the primitive types listed in Table 1 or Table 2, apply the mapping rules for primitive types.

Note Classes containing property types that do not conform to the mapping described above are invalid. In this case, the provider returns an error if and when the provider requests the retrieval of a class definition while executing an instance retrieval function.


Textual Conventions for Type Values

Each MOF syntax type is assigned a syntactical convention used when specifying values for property assignments. The following table defines the MOF syntax type definition and its syntactical representation in the LEX notational convention.

MOF Syntax Type | Can be empty? | Syntactical Representation
INTEGER | FALSE | ( [1-9] ) ( [0-9] )* | ( [0-7] )+ | ( 0x ( ( [0-9] | [a-f] | [A-F] ) + ) )
OCTETSTRING | TRUE | ( ( [0-9] | [a-f] | [A-F] ) ( [0-9] | [a-f] | [A-F] ) )*
OBJECTIDENTIFIER | FALSE | ( [1-9] ) ( [0-9] )* ( . ( [1-9] ) ( [0-9] )* ) *
NULL | MANDATORY |
IPADDRESS | FALSE | ( [1-9] ) ( [0-9] )* ( . ( [1-9] ) ( [0-9] )* ) 3
COUNTER | FALSE | ( [1-9] ) ( [0-9] )* | ( [0-7] )+ | ( 0x ( ( [0-9] | [a-f] | [A-F] ) ) + )
GAUGE | FALSE | ( [1-9] ) ( [0-9] )* | ( [0-7] )+ | ( 0x ( ( [0-9] | [a-f] | [A-F] ) )+ )
TIMETICKS | FALSE | ( [1-9] ) ( [0-9] )* | ( [0-7] )+ | ( 0x ( ( [0-9] | [a-f] | [A-F] ) )+ )
OPAQUE | TRUE | ( ( [0-9] | [a-f] | [A-F] ) ( [0-9] | [a-f] | [A-F] ) )*
NETWORKADDRESS | FALSE | ( [1-9] ) ( [0-9] )* ( . ( [1-9] ) ( [0-9] )+ ) 3
Displaystring | TRUE | .*
MacAddress | FALSE | ( [0-9] | [a-f] | [A-F] ) ( [0-9] | [a-f] | [A-F] )
 |  | ( : ( [0-9] | [a-f] | [A-F] ) ( [0-9] | [a-f] | [A-F] ) ) ) 5
PhysAddress | TRUE | ( [0-9] | [a-f] | [A-F] ) ( [0-9] | [a-f] | [A-F] ) ( : ( [0-9] | [a-f] | [A-F] ) ( [0-9] | [a-f] | [A-F] ) ) ) *
EnumeratedINTEGER | FALSE | One of enumerated values
BITS | TRUE | Array of enumerated values
DateTime | FALSE | ( [1-9] ) ( [0-9] )* '-' ( [1-9] ) ( [0-9] )* '-' ( [1-9] ) ( [0-9] )* '.' ( [1-9] ) ( [0-9] )* ':' ( [1-9] ) ( [0-9] )* ':' ( [1-9] ) ( [0-9] )* '.' ( [1-9] ) ( [0-9] )* ',' ( '+' | '-' ) ( [1-9] ) ( [0-9] )* ':' ( [1-9] ) ( [0-9] )*
SnmpOSIAddress | FALSE | ( ( [0-9] | [a-f] | [A-F] )+ '/' ( ( [0-9] | [a-f] | [A-F] )+
SnmpUDPAddress | FALSE | ( [1-9] ) ( [0-9] )* ( . ( [1-9] ) ( [0-9] )+ ) 3 '/' ( [1-9] ) ( [0-9] )*
SnmpIPXAddress | FALSE | ( [0-9] | [a-f] | [A-F] ) 4 '.' ( ( ( [0-9] | [a-f] | [A-F] ) ( [0-9] | [a-f] | [A-F] ) ) (':' ( [0-9] | [a-f] | [A-F] ) ( [0-9] | [a-f] | [A-F] ) ) 5 ) '.' ( [0-9])+

Note The NETWORKADDRESS type currently only supports IpAddress; therefore, the syntactical representation is always assumed to be IpAddress.


Mapping the INDEX Clause

The INDEX clause specifies a key to select a unique row in a table.

Scalar Collections

Scalar collections map to CIM singleton classes: classes that can have only one instance. Because there is no need to uniquely identify one instance from another, singleton classes do not designate one or more of their properties as the key.

The following mapping rules apply to scalar collections:

  • A class generated from a scalar collection does not contain a key property qualifier.
  • A class generated from a scalar collection contains the standard CIM class qualifier singleton, which is of type Bool.

Table Collections

Table collections map to CIM classes that can have more than one instance. As a result, the CIM class definition must contain at least one property that defines the object key; that is, a property that uniquely identifies an instance of the class. The INDEX clause of a table collection's OBJECT-TYPE macro specifies the collection's set of key properties.

The following mapping rules apply:

  • The CIM qualifier that defines a key property is key, which is of type Bool.
  • The ordering of the INDEX information within the table collection defines the ordering of the keys within the CIM class definition. The CIM property qualifier that defines the ordering of the keys is key_order. This qualifier is an unsigned 32-bit integer value which, for the purposes of the MOF qualifier syntax, must be converted to a signed 32-bit integer value using the twos-complement operation.

Currently, the mapping of the SNMPv2C INDEX clause does not handle the use of the IMPLIED qualifier. A CIM class definition is not generated in this case.

Because of the flexibility of the INDEX clause within the OBJECT-TYPE macro, the specification of keyed properties is not straightforward. The following possibilities must be considered when mapping the INDEX clause:

INDEX Clause Containing Internal Accessible MIB OBJECT-TYPE References

INDEX Clause Containing External Accessible MIB OBJECT-TYPE References

INDEX Clause Containing a MIB Type Reference

INDEX Clause Containing Inaccessible MIB OBJECT-TYPE References

INDEX Clause Containing a Fixed-Length Subtype


INDEX Clause Containing Internal Accessible MIB OBJECT-TYPE References

The INDEX clause can contain an internal accessible indexobject value. The indexobject value is a named value that refers to a MIB object definition appearing in the conceptual row of the same table that contains the INDEX clause. In this case, the MIB object definition referred to in the INDEX clause maps to a keyed property of the CIM class definition.


INDEX Clause Containing External Accessible MIB OBJECT-TYPE References

The INDEX clause can contain an external accessible indexobject value. The indexobject value is a named value that refers to a MIB object definition appearing in the conceptual row of a different table. In this case, the MIB object definition referred to in the INDEX clause maps to a keyed property of the CIM class definition.


INDEX Clause Containing a MIB Type Reference

The INDEX clause can contain an accessible indextype type. The indextype type is a named type that refers to one of the following: INTEGER, OCTET STRING, OBJECT IDENTIFIER, NetworkAddress, or IpAddress.

In this case, the following mapping rules apply:

  • The MIB object referred to in the INDEX clause maps to a keyed property of the CIM class definition. Its type syntax is based on the indextype type specified in the INDEX clause which maps to CIM property qualifiers using the procedures described in Mapping the SYNTAX Clause.
  • The mapping process generates a unique property name by concatenating the MIB table object descriptor, an underscore (_), and the rank order of the INDEX clause indextype. For example, the property name for the third component indextype of the MIB table enterpriseIfTable is enterpriseIfTable_3.
  • The CIM property is annotated with the virtual_key qualifier. This qualifier specifies that the SNMP providers should calculate the value of the property based on the superset of instance information associated with all the accessible MIB object definitions in the class definition.
  • The CIM class definition must contain at least one property that does not have an associated virtual_key qualifier; failure to specify this property invalidates the class definition.


INDEX Clause Containing Inaccessible MIB OBJECT-TYPE References

The INDEX clause can contain an inaccessible indexobject value. The indexobject value is a named value that refers to a MIB object definition appearing in the conceptual row of either the same table that contains the INDEX clause or a different table.

In this case, the following mapping rules apply:

  • The MIB object definition referred to in the INDEX clause maps to a keyed property of the CIM class definition, but is annotated with the CIM property qualifier virtual_key. This qualifier specifies that the SNMP providers should calculate the value of the property based on the superset of instance information associated with all of the accessible MIB object definitions in the class definition.
  • A class definition must contain at least one property that does not have an associated virtual_key qualifier; failure to specify this property invalidates the class definition.


INDEX Clause Containing a Fixed-Length Subtype

When the INDEX clause of an SNMP table collection contains an SNMP-supported type that is subtyped as a fixed-length OCTET STRING, the CIM property qualifier fixed_length must be used to specify this value.

Example

This example is an excerpt from the bridge-forwarding table.

MacAddress ::= OCTET STRING (SIZE (6))

dot1dTpFdbTable OBJECT-TYPE
       SYNTAX  SEQUENCE OF Dot1dTpFdbEntry
       ACCESS  not-accessible
       STATUS  mandatory
       DESCRIPTION
               "A table that contains information about unicast
               entries for which the bridge has forwarding and/or
               filtering information.  This information is used
               by the transparent bridging function in
               determining how to propagate a received frame."
       ::= { dot1dTp 3 }

dot1dTpFdbEntry OBJECT-TYPE
       SYNTAX  Dot1dTpFdbEntry
       ACCESS  not-accessible
       STATUS  mandatory
       DESCRIPTION
               "Information about a specific unicast MAC address
               for which the bridge has some forwarding and/or
               filtering information."
       INDEX   { dot1dTpFdbAddress }
       ::= { dot1dTpFdbTable 1 }

   Dot1dTpFdbEntry ::=
       SEQUENCE {
           dot1dTpFdbAddress
               MacAddress,
           dot1dTpFdbPort
               INTEGER,
           dot1dTpFdbStatus
               INTEGER
       }

   dot1dTpFdbAddress OBJECT-TYPE
       SYNTAX  MacAddress
       ACCESS  read-only
       STATUS  mandatory
       DESCRIPTION
               "A unicast MAC address for which the bridge has
               forwarding and/or filtering information."
       REFERENCE
               "P802.1d/D9, July 14, 1989: Section 3.9.1, 3.9.2"
       ::= { dot1dTpFdbEntry 1 }

This example maps to the following CIM class definition:

    [
        description (

            "A table that contains information about unicast
            entries for which the bridge has forwarding and/or
            filtering information.  This information is used
            by the transparent bridging function in
            determining how to propagate a received frame.

            Information about a specific unicast MAC address
            for which the bridge has some forwarding and/or
            filtering information."
        ) ,
        module_name ("RFC1286-MIB"),
        group_objectid ("1.3.6.1.2.1.17")
    ]
    class SNMP_RFC1286_MIB_Dot1dTpFdbTable
    {
        [   read,key,key_order(1),
            fixed_length(6),
            object_syntax("MacAddress"),
            textual_convention("MacAddress"),
            encoding("OCTETSTRING"),
            object_identifier("1.3.6.1"),
            description (

            "A unicast MAC address for which the bridge has
           forwarding and/or filtering information."
            )
        ]
        string dot1dTpFdbAddress;
    }


Mapping the SNMPv2C AUGMENTS Clause

In SNMPv2C, the AUGMENTS clause can replace the INDEX clause. The AUGMENTS clause indicates that the table collection it specifies can be considered an extension of another table collection. The collections referred to by the AUGMENTS clause can be combined with the other table collection to form one collection. The resulting collection shares the primary key properties specified in the last table collection in the chain.

In this case, the previous mapping rules specified for the INDEX clause should be applied to the last table collection in the chain. The collection of objects then maps to one CIM class definition.


Mapping the Object Identifier

Each MIB object is referred to by a unique object identifier. This object identifier maps to the CIM property qualifier object_identifier.


Mapping the ACCESS and MAX-ACCESS Clauses

Each MIB object definition contains either an ACCESS (SNMPv1) or MAX-ACCESS (SNMPv2C) clause that defines the access rights to the object.

The following table defines the mapping of the SNMPv1 ACCESS clause.

MIB ACCESS class | CIM qualifiers
read-only | read
read-write | read, write
write-only | write
not-accessible | not_accessible

The following table defines the mapping of the SNMPv2C MAX-ACCESS clause:

MIB MAX-ACCESS class | CIM qualifiers
read-only | read
read-write | read, write
read-create | read
accessible-for-notify | not_accessible
not-accessible | not_accessible

When a MIB object maps to not-accessible and is not a keyed property of the class, there is no mapping of the MIB object itself.


Mapping the DESCRIPTION Clause

Each MIB object definition contains a DESCRIPTION clause that provides a text description of the object. This clause may be empty. The DESCRIPTION clause maps to the CIM property qualifier description.

Each TABLE and ENTRY object in an SNMP table definition contains a DESCRIPTION clause, which may be empty. The TABLE and ENTRY DESCRIPTION clauses are concatenated and the result maps to the CIM class qualifier description.


Mapping the STATUS Clause

Each MIB object definition contains a STATUS clause that indicates whether the object must be supported. When the value of the STATUS clause is obsolete, the MIB object is discarded from the mapping. Otherwise, the STATUS clause maps to the CIM property qualifier status.

For SNMPv1, the preferred value of the status property qualifier is either mandatory or optional, but the qualifier can contain some other value.

For SNMPv2C, the preferred value of the status property qualifier is either current or deprecated, but the qualifier can contain some other value.


Mapping the DEFVAL, REFERENCE, and UNITS Clauses

The following mapping applies to the optional DEFVAL, REFERENCE, and UNITS clauses:

Clause | Description | CIM Mapping
DEFVAL | Assigns a default value to a variable in a logical table row. | Maps to the CIM property qualifier defval, which is of type string.
REFERENCE | Refers to another document that contains additional information about the object. | Maps to the CIM property qualifier reference, which is of type string.
UNITS | Provides a precise definition of what the object represents. | Maps to the CIM property qualifier units, which is of type string.


Mapping the TRAP-TYPE and NOTIFICATION-TYPE Macros

The SNMPv1 TRAP-TYPE and SNMPv2C NOTIFICATION-TYPE macros describe the characteristics of an SNMP event. For uniformity, each instance of the TRAP-TYPE macro is first mapped to an instance of the NOTIFICATION-TYPE macro using the mapping defined in RFC 1908.

The NOTIFICATION-TYPE macro maps to one of two types of CIM event classes: encapsulated or referent. Some mapping procedures differ depending on which type of class is used.

The following topics describe the mapping procedures for the NOTIFICATION-TYPE macro.


The NOTIFICATION-TYPE Macro

The NOTIFICATION-TYPE macro contains clauses that describe the basic characteristics of an SNMP event. The SNMP providers convert the following parts of the NOTIFICATION-TYPE macro:

  • object descriptor

    Assigns a name to the notification object.

  • OBJECTS clause

    Enumerates the set of objects associated with the notification object.

  • REFERENCE clause

    Cross-references additional information about the notification object.

  • DESCRIPTION clause

    Describes the notification object.

  • STATUS clause

    Indicates whether the notification object must be supported.

The mapping procedures for some components differ, depending on whether the resulting CIM event class is an encapsulated or referent class.


Encapsulated and Referent CIM Classes

The SNMP providers map the NOTIFICATION-TYPE macro to one of the following types of CIM event class definitions:

  • Encapsulated class definition

    Does not expose the instance information associated with the MIB object. The class definition encodes the OBJECTS clause as a series of properties of the CIM event class. Each CIM property reflects the name, type, and value of the corresponding MIB object in the OBJECTS clause.

    If instance information is required, the referent class must be used.

  • Referent class definition

    Defines the MIB objects and the instance information used to obtain them. The class definition encodes the OBJECTS clause as a series of properties of the CIM event class. Each CIM property reflects the name of the corresponding MIB object in the OBJECTS clause and the type as an embedded object reflecting an instance of the class associated with that MIB object. The class associated with the MIB object is generated through the procedures described in Mapping the OBJECT-TYPE Macro. For example, ifIndex maps to an embedded class named SNMP_RFC1213_MIB_ifIndex.


Mapping to an Encapsulated CIM Class

When the NOTIFICATION-TYPE macro maps to an encapsulated CIM class, the class is derived from the CIM abstract class SnmpNotification, which is defined as follows:

[abstract]
class SnmpNotification : __ExtrinsicEvent
{
    [read] String Identification ;
    [read] String Community ;
    [read] String TimeStamp ;
    [read] String AgentTransport ;
    [read] String AgentTransportAddress ;
    [read] String AgentAddress ;

} ;


Mapping to a Referent CIM Class

When the NOTIFICATION-TYPE macro maps to a referent CIM class, the class is derived from the CIM abstract class SnmpExtendedNotification, which is defined as follows:

[abstract]
class SnmpExtendedNotification : __ExtrinsicEvent
{
    [read] String Identification ;
    [read] String Community ;
    [read] String TimeStamp ;
    [read] String AgentTransport ;
    [read] String AgentTransportAddress ;
    [read] String AgentAddress ;

} ;


Common Properties of Encapsulated and Referent CIM Classes

Both encapsulated and referent CIM classes contain a number of common properties that are mapped from an SNMP TRAP protocol data unit (PDU).

TimeStamp and Identification Properties (SNMPv2C)

The first two objects in an SNMPv2C TRAP PDU variable bindings list must contain a time stamp property and an identification property.

The time stamp property refers to the MIB variable sysUptime.0, which is of type INTEGER32. This property maps to the CIM class property TimeStamp, which is of type uint32.

The identification property refers to the MIB variable snmpTrapOID.0, which is of type OBJECT IDENTIFIER. This property maps directly from the object identity of the NOTIFICATION-TYPE macro to the CIM class property Identification, which is of type string.

A NOTIFICATION-TYPE macro that contains references to an OBJECT-TYPE macro named TimeStamp or Identification causes a mapping conflict. If this conflict occurs, the required properties take precedence and the conflicting references must be renamed.

Community Property (SNMPv1 and SNMPv2C)

Each SNMPv1 and SNMPv2C TRAP PDU specifies a community name associated with an instance of the PDU. The community name authenticates the originator of the PDU. The SNMP community name maps to the CIM class property Community, which is of type string.

A NOTIFICATION-TYPE macro that contains references to an OBJECT-TYPE macro named Community causes a mapping conflict. If this conflict occurs, the required properties take precedence and the conflicting references must be renamed.

AgentAddress Property (SNMPv1)

The SNMPv1 TRAP PDU specifies a NetworkAddress associated with an instance of the PDU. This address identifies the transport address of the originating SNMP entity. When the management entity uses SNMP over UDP, the transport address refers to an IP address. When the management entity uses SNMP over IPX, the transport address is set to NULL. NetworkAddress maps to the CIM class property AgentAddress, which is of type string.

AgentTransportAddress Property (SNMPv1 and SNMPv2C)

Each SNMPv1 and SNMPv2C TRAP PDU has an associated transport protocol frame and transport source address. This address identifies the transport address of the originating SNMP entity, which may be acting as a proxy. When the management entity uses SNMP over UDP, the transport address refers to an IP address. When the management entity uses SNMP over IPX, the transport address refers to an IPX address. The transport address maps to the CIM class property AgentTransportAddress, which is of type string.

AgentTransport Property (SNMPv1 and SNMPv2C)

Each SNMPv1 and SNMPv2C TRAP PDU has an associated transport protocol. The transport protocol maps to the CIM class property AgentTransport, which is of type string.


Mapping the NOTIFICATION-TYPE Object Descriptor

Each NOTIFICATION-TYPE macro defines an object descriptor that names the information associated with an SNMP event. The object descriptor maps to the CIM class name.

Encapsulated CIM class name

The name for an encapsulated CIM class is generated by concatenating "SNMP_", the MIB module identity name, an underscore (_), the object descriptor, and "_Notification".

For example, the notification named vtpServerDisabled from the CISCO-VTP-MIB maps to an encapsulated CIM class named SNMP_CISCO_VTP_MIB_vtpServerDisabled_Notification.

Referent CIM class name

The name for a referent CIM class is generated by concatenating "SNMP_", the MIB module identity name, an underscore (_), the object descriptor, and "_ExtendedNotification".

For example, the notification named vtpServerDisabled from the CISCO-VTP-MIB maps to a referent CIM class named SNMP_CISCO_VTP_MIB_vtpServerDisabled_ExtendedNotification.


Mapping the NOTIFICATION-TYPE OBJECTS Clause

The OBJECTS clause of the NOTIFICATION-TYPE macro enumerates the set of objects associated with the notification object.

The following rules apply when mapping to either encapsulated or referent CIM classes:

  • Each member of the OBJECTS clause maps to a property of the CIM class definition. The object descriptor of the member maps verbatim to the CIM property name. For example, ifIndex translates to ifIndex.
  • The procedures for mapping individual members of the OBJECTS clause differ depending on whether an encapsulated or referent CIM class is used. See Mapping Members of the OBJECTS Clause.
  • Each CIM property generated by the mapping process contains the following qualifier.
Qualifier Qualifier
syntax 		Status Description
VarBindIndex uint32 Mandatory An integer specifying the position of the object as it appears in the OBJECTS clause of the TRAP-TYPE or the NOTIFICATION-TYPE macro. The integer also specifies the position of the property as it appears in the variable bindings list of the SNMPv1 or SNMPv2C TRAP PDU, respectively. (Because the first two variable bindings are always TimeStamp and Identification, any additional variables are numbered after the value 2.)

When the CIM event class is generated from an SNMPv1 TRAP-TYPE macro, the VarBindIndex qualifier has an initial value of 1 for the first variable in the variable bindings list.

When the CIM event class is generated from an SNMPv2C NOTIFICATION-TYPE macro, the VarBindIndex qualifier has an initial value of 3 for the first variable in the variable bindings list.


Mapping Members of the OBJECTS Clause

The mapping for members of the OBJECTS clause differs depending on whether an encapsulated or referent CIM class is used.

Encapsulated CIM Classes

When an encapsulated CIM class is used, each member of the OBJECTS clause maps to a CIM property that reflects the name, type, and value of the corresponding MIB object. The mapping procedures used are specified in following topics:

  • Mapping the SYNTAX Clause
  • Textual Conventions for Type Values
  • Mapping the Object Identifier
  • Mapping the ACCESS and MAX-ACCESS Clauses
  • Mapping the DESCRIPTION Clause
  • Mapping the STATUS Clause
  • Mapping the DEFVAL, REFERENCE, and UNITS Clauses

Referent CIM Classes

When a referent CIM class is used, each member of the OBJECTS clause maps as follows:

  • Each member of the OBJECTS clause maps to a single property of the CIM class. The property is strongly typed as an embedded object.
  • The class of the embedded object is generated through the mapping procedure described in Mapping the OBJECT-TYPE Macro. For example, ifTable maps to an embedded class named SNMP_RFC1213_MIB_ifTable.
  • The values associated with the variable bindings of a TRAP PDU are instantiated as embedded objects of an object of the referent class. Each embedded object contains values for each of the keyed properties of the object and the value of the property in the variable binding being mapped.


Mapping the REFERENCE, DESCRIPTION, and STATUS Clauses

The REFERENCE, DESCRIPTION, and STATUS clauses of the NOTIFICATION-TYPE macro use the following mapping for both encapsulated and referent CIM classes:

Clause | Description | CIM Mapping
REFERENCE clause | Refers to another document that contains additional information about the object. | Maps to the CIM class qualifier reference, which is of type string.
DESCRIPTION clause | Describes the object. | Maps to the CIM class qualifier description, which is of type string.
STATUS clause | Indicates whether the object must be supported. | When the status is either obsolete or deprecated, the notification is discarded from the mapping. Otherwise, this clause maps to the CIM class qualifier status, which is of type string.


Example Mappings

The following topics contain examples of mapping to encapsulated CIM classes:

  • SNMPv1 Encapsulated CIM Class Example
  • SNMPv2C Encapsulated CIM Class Example

The following topics contain examples of mapping to referent CIM classes:

  • SNMPv1 Referent CIM Class Example
  • SNMPv2C Referent Class Example


SNMPv1 Encapsulated CIM Class Example

The following example maps the SNMPv1 TRAP-TYPE macro instantiation of sdlcPortStatusChange to an encapsulated CIM event class definition.

sdlcPortStatusChange TRAP-TYPE
ENTERPRISE sdlcTraps
-- sdlcTraps = 1.3.6.1.2.1.41.1.3
VARIABLES
{
ifIndex,
ifAdminStatus,
ifOperStatus,
sdlcPortOperLastFailTime,
sdlcPortOperLastFailCause
}
DESCRIPTION
"This trap indicates that the state of an SDLC port has transitioned to active or inactive."
::= 1

This example maps to the following CIM class definition:
[Description("This trap indicates that the state of an SDLC port has transitioned to active or inactive.")]
class SNMP_SNA_SDLC_MIB_sdlcPortStatusChange_Notification : SnmpNotification
{
String Identification = "1.3.6.1.2.1.41.1.3.0.1"; //the value of sdlcTraps.0.1

[object_identifier("1.3.6.1.2.1.2.2.1.1"),
textual_convention("INTEGER"),
encoding("INTEGER"),
object_type(),
read,
TableClass("SNMP_RFC1213_MIB_ifTable),
KeyTypes("sint32"),
KeyValues("ifIndex ="),
VarBindIndex(3),
Description("A unique value for each interface.  Its value
                      ranges between 1 and the value of ifNumber.  The
                      value for each interface must remain constant at
                      least from one re-initialization of the entity's
                      network management system to the next re-
                      initialization.")
]
sint32 ifIndex;

[
object_identifier("1.3.6.1.2.1.2.2.1.7"),
textual_convention("EnumeratedInteger"),
read,
write,
encoding("INTEGER"),
enumeration("up(1),down(2),testing(3)"),
Description("The desired state of the interface.  The
                      testing(3) state indicates that no operational
                      packets can be passed."),
TableClass("SNMP_RFC1213_MIB_ifTable),
KeyTypes("sint32"),
KeyValues("ifIndex =")
VarBindIndex(4)
]
string ifAdminStatus;

[
object_identifier("1.3.6.1.2.1.2.2.1.8"),
textual_convention("EnumeratedInteger"),
read,
encoding("INTEGER"),
enumeration("up(1),down(2),testing(3)"),
TableClass("SNMP_RFC1213_MIB_ifTable),
KeyTypes("sint32"),
KeyValues("ifIndex =")
VarBindIndex(5),
Description("The current operational state of the interface.
                      The testing(3) state indicates that no
                      operational
                      packets can be passed.")
]
string ifOperStatus;

[
object_identifier("1.3.6.1.2.1.41.1.1.2.1.12"),
textual_convention("TimeTicks"),
read,
encoding("TimeTicks"),
TableClass("SNMP_SNA_SDLC_MIB_sdlcPortOperTable"),
KeyTypes("sint32"),
KeyValues("ifIndex =")
VarBindIndex(6),
Description("This object describes the value of sysUpTime
    when this SDLC port last failed.  If the port
    has not failed, then this value shall be zero.")
]
uint32 sdlcPortOperLastFailTime;

[
object_identifier("1.3.6.1.2.1.41.1.1.2.1.13"), textual_convention("EnumeratedInteger"),
read, encoding("INTEGER"), enumeration("undefined(1),physical(2)"),
TableClass("SNMP_SNA_SDLC_MIB_sdlcPortOperTable"),
KeyTypes("sint32"),
KeyValues("ifIndex =")
VarBindIndex(7),
Description("This enumerated object describes the cause of
             the last failure of this SDLC port.  If the
port has not failed, then this object has a
    value of undefined(1).")
]
uint32 sdlcPortOperLastFailCause;
};


SNMPv2C Encapsulated CIM Class Example

The following example maps the SNMPv2C NOTIFICATION-TYPE macro instantiation of sdlcPortStatusChange to an encapsulated CIM event class definition.

sdlcPortStatusChange NOTIFICATION-TYPE
OBJECTS
{
ifIndex,
ifAdminStatus,
ifOperStatus,
sdlcPortOperLastFailTime,
sdlcPortOperLastFailCause
}
STATUS  current
DESCRIPTION  "This trap indicates that the state of an SDLC port has transitioned to active or inactive."
::= { sdlcTraps 1 }

This example maps to the following CIM class definition:

[
Description("This trap indicates that the state of an SDLC port has transitioned to active or inactive.")
]
class SNMP_SNA_SDLC_MIB_sdlcPortStatusChange_Notification : SnmpNotification
{
String Identification = "1.3.6.1.2.1.41.1.3.1"; //the value of sdlcTraps.1

[
object_identifier("1.3.6.1.2.1.2.2.1.1"),
textual_convention("INTEGER"),
encoding("INTEGER"), read,
TableClass("SNMP_RFC1213_MIB_ifTable),
KeyTypes("sint32"),
KeyValues("ifIndex =")
VarBindIndex(3),
Description("A unique value for each interface.  Its value
                      ranges between 1 and the value of ifNumber.  The
                      value for each interface must remain constant at
                      least from one re-initialization of the entity's
                      network management system to the next re-
                      initialization.")
]
Sint32 ifIndex;

[
object_identifier("1.3.6.1.2.1.2.2.1.7"),
textual_convention("EnumeratedInteger"),
read,
write,
encoding("INTEGER"),
enumeration("up(1),down(2),testing(3)"),
TableClass("SNMP_RFC1213_MIB_ifTable),
KeyTypes("sint32"),
KeyValues("ifIndex =")
VarBindIndex(4),
Description("The desired state of the interface.  The
                      testing(3) state indicates that no operational
                      packets can be passed.")
]
String ifAdminStatus;

[
object_identifier("1.3.6.1.2.1.2.2.1.8"),
textual_convention("EnumeratedInteger"),
read,
encoding("INTEGER"),
enumeration("up(1),down(2),testing(3)"),
TableClass("SNMP_RFC1213_MIB_ifTable),
KeyTypes("sint32"),
KeyValues("ifIndex =")
VarBindIndex(5),
Description("The current operational state of the interface.
                      The testing(3) state indicates that no
                      operational
                      packets can be passed.")
]
String ifOperStatus;

[
object_identifier("1.3.6.1.2.1.41.1.1.2.1.12"),
textual_convention("TimeTicks"),
read,
encoding("TimeTicks"),
TableClass("SNMP_SNA_SDLC_MIB_sdlcPortOperTable"),
KeyTypes("uint32"),
KeyValues("ifIndex =")
VarBindIndex(6),
Description("This object describes the value of sysUpTime
    when this SDLC port last failed.  If the port
    has not failed, then this value shall be zero.")
]
    uint32 sdlcPortOperLastFailTime;

[
object_identifier("1.3.6.1.2.1.41.1.1.2.1.13"),
textual_convention("EnumeratedInteger"),
read,
encoding("INTEGER"),
enumeration("undefined(1),physical(2)"),
TableClass("SNMP_SNA_SDLC_MIB_sdlcPortOperTable"),
KeyTypes("sint32"),
KeyValues("ifIndex =")
VarBindIndex(7),
Description("This enumerated object describes the cause of
    the last failure of this SDLC port.  If the
    port has not failed, then this object has a
    value of undefined(1).")
]
sint32 sdlcPortOperLastFailCause;
};


SNMPv1 Referent CIM Class Example

The following example maps the SNMPv1 TRAP-TYPE macro instantiation of sdlcPortStatusChange to a referent CIM event class definition.

sdlcPortStatusChange TRAP-TYPE

ENTERPRISE sdlcTraps
-- sdlcTraps = 1.3.6.1.2.1.41.1.3
VARIABLES
{
ifIndex,
ifAdminStatus,
ifOperStatus,
sdlcPortOperLastFailTime,
sdlcPortOperLastFailCause
}
DESCRIPTION
"This trap indicates that the state of an SDLC port has transitioned to active or inactive."
::= 1

This example maps to the following CIM class definition:

[Description("This trap indicates that the state of an SDLC port has transitioned to active or inactive.")]
class SNMP_SNA_SDLC_MIB_sdlcPortStatusChange_ExtendedNotification : SnmpExtendedNotification
{
string Identification = "1.3.6.1.2.1.41.1.3.0.1"; //the value of sdlcTraps.0.1
    [VarBindIndex(3)]    SNMP_RFC1213_MIB_ifTable        ifIndex;
    [VarBindIndex(4)]    SNMP_RFC1213_MIB_ifTable        ifAdminStatus;
    [VarBindIndex(5)]    SNMP_RFC1213_MIB_ifTable        ifOperStatus;
    [VarBindIndex(6)]    SNMP_SNA_SDLC_MIB_sdlcPortOperTable    sdlcPortOperLastFailTime;
    [VarBindIndex(7)]    SNMP_SNA_SDLC_MIB_sdlcPortOperTable    sdlcPortOperLastFailCause;
};


SNMPv2C Referent Class Example

The following example maps the SNMPv2C NOTIFICATION-TYPE macro instantiation of sdlcPortStatusChange to a referent CIM event class definition.

sdlcPortStatusChange NOTIFICATION-TYPE
OBJECTS
{
ifIndex,
ifAdminStatus,
ifOperStatus,
sdlcPortOperLastFailTime,
sdlcPortOperLastFailCause
}
STATUS  current
DESCRIPTION  "This trap indicates that the state of an SDLC port has transitioned to active or inactive."
::= { sdlcTraps 1 }

This example maps to the following CIM class definition:

[Description("This trap indicates that the state of an SDLC port has transitioned to active or inactive.")]
class SNA_SDLC_MIB_sdlcPortStatusChange_Event : SnmpExtendedNotification
{
string Identification = "1.3.6.1.2.1.41.1.3.1"; //the value of sdlcTraps.1
    [VarBindIndex(3)]    SNMP_RFC1213_MIB_ifTable        ifIndex;
    [VarBindIndex(4)]    SNMP_RFC1213_MIB_ifTable        ifAdminStatus;
    [VarBindIndex(5)]    SNMP_RFC1213_MIB_ifTable        ifOperStatus;
    [VarBindIndex(6)]    SNMP_SNA_SDLC_MIB_sdlcPortOperTable    sdlcPortOperLastFailTime;
    [VarBindIndex(7)]    SNMP_SNA_SDLC_MIB_sdlcPortOperTable    sdlcPortOperLastFailCause;
};


SNMP Protocol Encoding

Although the class mapping accepts both SNMPv1 and SNMPv2C schemas, it is important to note the following:

  • The SNMP providers only generate SNMPv1 protocol requests in an SNMPv1-defined namespace. When no corresponding conversion between the SNMPv2C and SNMPv1 type is applicable, the SNMP providers do not generate a request for that property and the property value retains its default value.
  • The SNMP providers only generate SNMPv2C protocol requests in an SNMPv2C-defined namespace. When no corresponding conversion between the SNMPv1 and SNMPv2C type is applicable, the SNMP providers do not generate a request for that property and the property value retains its default value.

SNMPv1 Protocol Encoding

The following table defines the protocol encoding type used when generating SNMPv1 protocol frames.

CIM Encoding qualifier | SNMPV1 protocol encoding
INTEGER | INTEGER
OCTETSTRING | OCTET STRING
OBJECTIDENTIFIER | OBJECT IDENTIFIER
NULL | NULL
IpAddress | IpAddress
Counter | Counter
Gauge | Gauge
TimeTicks | TimeTicks
Opaque | Opaque
NetworkAddress | NetworkAddress
Counter32 | Counter
Gauge32 | Gauge
Unsigned32 | Gauge
Integer32 | INTEGER
Counter64 | No Supported Conversion

SNMPv2C Protocol Encoding

The following table defines the protocol encoding type used when generating SNMPv2C protocol frames.

CIM Encoding qualifier | SNMPv2C protocol encoding
INTEGER | INTEGER32
OCTECTSTRING | OCTET STRING
OBJECTIDENTIFIER | OBJECT IDENTIFIER
NULL | No supported conversion
IpAddress | IpAddress
Counter | Counter32
Gauge | Gauge32
TimeTicks | TimeTicks
Opaque | Opaque
NetworkAddress | No supported conversion
Counter32 | Counter32
Gauge32 | Gauge32
Unsigned32 | Unsigned32
Integer32 | INTEGER32
Counter64 | Counter64


Enumerating SNMP Class Definitions

Applications can enumerate a set of class definitions by calling IWbemServices::CreateClassEnum or IWbemServices::CreateClassEnumAsync. The class provider supports two modes: correlated and uncorrelated.

When enumerating correlated class definitions, the set of definitions returned is a subset of the definitions that can be enumerated from the scalar and table collection classes present in the SMIR database. The actual set of definitions returned will be determined by the capability of the designated SNMP agent device.

The SNMP class provider uses the MIB correlator to analyze the agent device using the list of SMIR fabricated groups. The provider passes the transport information associated with the designated device to the correlator. This transport information is retrieved from the set of qualifiers present within the containing namespace such as AgentAddress and AgentTransport. For a description of these qualifiers, see Creating an SNMP Namespace.

If the agent device supports the group definition, the provider maps that group definition to the set of class definitions contained within the group. These classes are passed back to the user by WMI. Otherwise the group definition and those classes contained within that group will be ignored.

When enumerating non-correlated class definitions, the set of definitions returned is the set that can be enumerated from the scalar and table definitions present within the SMIR database. The class provider maps the collection definition to a class definition and adds the resulting value to the set of reported classes.


Instantiating SNMP Class Definitions

Applications can instantiate a class definition by calling IWbemServices::GetObject or IWbemServices::GetObjectAsync. The SNMP class provider maps class definitions to either scalar collections or table collection definitions. The class provider supports instantiation in two modes: correlated and uncorrelated.

When instantiating a correlated class definition, the class name is presented to the SMIR to determine if the class is supported. If it is supported, the group object identifier associated with the group containing the class is retrieved from the set of class qualifiers. The group object identifier is then presented to the MIB correlator to determine if the object identifier supports the group. The correlator is passed transport information associated with the designated device such as the transport address and community name.

This information is retrieved from the set of qualifiers presented with the current namespace or from the context object. If information from both sources is present, the information in the context object takes precedence over the information in the qualifiers. If the device supports the group definition, the class retrieved from the SMIR is returned to the caller. If the group definition is not supported, an error is returned.

When instantiating a non-correlated class definition, the class provider presents the name of the class to the SMIR to determine if the class is supported. If the SMIR supports the class, then it is assumed that the device supports the class and the class definition is returned to the caller. If the class definition is not supported by the SMIR, an error is returned.

For each class returned by the provider, the class will be modified so that all qualifiers present within the containing namespace will be inherited by that class.


Retrieving an SNMP Class Instance

Applications can call IWbemServices::GetObject or IWbemServices::GetObjectAsync to retrieve a particular instance of an SNMP CIM class. The object path for the strObjectPath parameter must include all of the key values. If any of the properties that are marked with the Key qualifier are missing, the method returns an error.


Enumerating SNMP Class Instances

The SNMP instance provider services requests to enumerate instances associated with classes that represent devices. If a particular property cannot be obtained, the instance provider sets the property in the instance to NULL and attaches the not_available qualifier to it. If a mismatch between a property type and a MIB type occurs, the instance provider marks the property with the type_mismatch property and sets the property to a value representing the SNMP protocol encoding type.

When an application requests that the instance provider enumerate instances from a device that is not responding, the provider returns WBEM_E_FAILED. Instances that have been returned either semisynchronously or asynchronously remain valid.


Instantiating SNMP Class Instances

The SNMP instance provider services requests to instantiate instances of classes that represent MIB objects or SNMP events. MIB objects are mapped to SNMP CIM classes using the OBJECT-TYPE macro; events are mapped to classes using the TRAP-TYPE and NOTIFICATION-TYPE macros. For more information about these mapping procedures, see one of the following topics:

  • Mapping the OBJECT-TYPE Macro
  • Mapping the TRAP-TYPE and NOTIFICATION-TYPE Macros

It is possible that the SNMP instance provider will not obtain all of the MIB objects that refer to a particular property of an instance. When this occurs with an instance of a MIB object class, the instance provider marks the property as NULL and attaches the Boolean qualifier not_available. When a MIB object is unavailable for an event class, the event provider sets the corresponding property to NULL without attaching the not_available qualifier.

When an error occurs due to type mismatching between property definitions and MIB definitions, the instance provider marks the property with another Boolean qualifier, type_mismatch. The property itself is assigned a value representing the SNMP protocol encoding type.

For example, consider the property ifType that disallows the value 0. If a type mismatching occurs for this property, the instance provider sets:

  • The type_mismatch qualifier
  • The ifType property to the string value '0'

The SNMP event providers also mark the property with type_mismatch if the object identifier in a variable binding does not match the object identifier of the event class property.

For each instance returned by the provider, the instance will be modified so that all qualifiers present within the containing namespace will be inherited by that instance.

The SNMP Referent Event Provider (SREP) creates embedded objects using instance information in the variable binding's object identifier to create key properties for the embedded object. If the object identifier of the variable binding has inconsistent instance information such that the key properties cannot be determined, the keys of the embedded object are set to NULL and marked with the type_mismatch qualifier.

The SREP detects a conflict between the data in a variable binding and the instance information in the variable binding's object identifier when the following occurs:

  • The property being set is a key property.
  • The data in the variable binding does not have the same value as the value taken from the instance information from the variable binding's object identifier.

In this case, the property will be given the value from the variable binding data and marked with the qualifier value_mismatch.


SNMP Troubleshooting Guide

This guide is designed to help users retrieve information from a Simple Network Management Protocol (SNMP) device. The guide describes common errors that can occur during operations performed by the SNMP providers, and suggests solutions for correcting the problems.

The error descriptions and solutions are grouped according to the following categories:

  • Installation and registration errors
  • Transport protocol operation errors
  • SNMP MIB mapping errors


Troubleshooting SNMP Installation and Registration Errors

The following topics describe errors that can occur during the installation and registration of the SNMP providers. These errors are associated with the SNMP device namespace configuration.

Errors:

Dynamic class provider not registered in the SNMP device namespace.

Dynamic class provider incorrectly registered in the SNMP device namespace.

Solution:

The SNMP class provider needs to be registered with Windows Management Instrumentation (WMI). See Registering the SNMP Class Provider and Sample Registration for the SNMP Instance and Class Providers.

Errors:

Dynamic instance provider not registered in the SNMP device namespace.

Dynamic instance provider incorrectly registered in the SNMP device namespace.

Solution:

The SNMP instance provider needs to be registered with WMI. See Registering the SNMP Instance Provider and Sample Registration for the SNMP Instance and Class Providers.

Error:

No classes loaded into the SNMP device namespace.

Solution:

Load a static SNMP device-compatible Managed Object Format (MOF) definition into the SNMP device namespace.

Error:

No classes loaded into the SMIR for an SNMP dynamic class provider-backed SNMP device namespace.

Solution:

Load a static SMIR SNMP-device-compatible MOF definition into the SMIR namespace.


Troubleshooting Transport Protocol Operation Errors

The following topics describe errors associated with the SNMP transport protocol operation.

Illegal Transport Address

AgentAddress Errors

ICMP Port Unreachable Packets

ICMP Host Unreachable Packets

ICMP Net Unreachable Packets

No SNMP Agent Response

SNMP Agent Responds After Timeout

Multiple Packets with the Same Protocol Request Identifier

SNMP Provider Returns Subset

SNMP Provider Returns Empty Result Set

SNMP Provider Returns Error Result

Set of Returned Classes Changes Intermittently

Set of Returned Instances Changes Intermittently


Illegal Transport Address

Error Message

SNMP device namespace instance or SNMP-compatible class contains an illegal transport address.

Solutions:

  • Verify that the AgentAddress qualifier is of type string.
  • If the AgentAddress qualifier is a dotted decimal Internet Protocol (IP) address, the address must be a valid unicast IP address.
  • If the AgentAddress qualifier is a host-name-resolvable string, verify that the host name is resolvable using the Microsoft® Windows® executable file:

    ping.exe <hostname>

    where hostname is the host-name-resolvable string.


AgentAddress Errors

Error Message

The AgentAddress qualifier of the SNMP device namespace instance or SNMP-compatible class is correct but the operation hangs for a period of time before successfully returning.

Further Description:

If the AgentAddress qualifier is a host-name-resolvable string, check the response time of the Windows executable file ping.exe <hostname>, where hostname is the host-name-resolvable string. Windows may be trying to resolve the host name across multiple network interface cards. In this case, Windows is performing a less-than-optimal search order.

Solution:

Try rearranging the binding order of the network interface cards.

Error Message

The AgentAddress qualifier of the SNMP device namespace instance or SNMP-compatible class is a resolvable host name but the operation hangs for a period of time before unsuccessfully returning.

Further Description:

If the AgentAddress qualifier is a host-name-resolvable string, check the response time of the Windows executable file ping.exe <hostname>, where hostname is the host-name-resolvable string. Windows may be trying to resolve the host name across multiple network interface cards. In this case, Windows is performing a less-than-optimal search order.

Solution:

The marshalling interface between the WMI client and the WMI server may be timing out before the operation completes. Try increasing the marshalling timeout period.

Error Message

The AgentAddress qualifier of the SNMP device namespace instance or SNMP-compatible class is an IP address but the operation hangs for a period of time before unsuccessfully returning.

Further Description:

If the AgentAddress qualifier has been entered incorrectly, the SNMP providers assume the value is a resolvable host name. The providers then unsuccessfully attempt to resolve the host name.

Solution:

Make sure the AgentAddress qualifier is really a dotted decimal IP address.


ICMP Port Unreachable Packets

Error Message

The SNMP protocol data units generate ICMP-port-unreachable packets.

Further Description:

The AgentAddress qualifier specified in the SNMP device namespace instance or SNMP-compatible class does not have an associated agent bound to the SNMP UDP port 161.

Solution:

Verify that the IP address is correct and that the SNMP agent is enabled on the device.


ICMP Host Unreachable Packets

Error Message

The SNMP protocol data units generate ICMP-host-unreachable packets.

Further Description:

The subnet associated with the IP transport address specified in the AgentAddress qualifier of the SNMP device namespace instance or SNMP-compatible class is known by a local router. However, the IP transport address on that subnet is not discoverable by the subnet-connected router using the address resolution protocol.

Solution:

Verify that the IP address is correct, and that the hardware device is switched on and connected to the network.


ICMP Net Unreachable Packets

Error Message

The SNMP protocol data units generate ICMP-net-unreachable packets.

Further Description:

The subnet associated with the IP transport address specified in the SNMP device namespace instance or SNMP-compatible class is not known by a local router.

Solution:

Check that the IP address is correct, and that the routing device has the appropriate routing table entries for that subnet.


No SNMP Agent Response

Error Message

The SNMP agent receives an SNMP protocol data unit but does not return a response.

Further Description:

The SNMP agent does not respond to an SNMP protocol operation because the SNMP protocol data unit is not a valid authenticated packet.

Solutions:

For the SNMPv1 protocol operations GET and GET-NEXT, make sure that the AgentReadCommunityName qualifier of the SNMP device namespace instance or SNMP-compatible class is valid for that SNMP agent device.

For the SNMPv1 protocol operation SET, make sure that the AgentWriteCommunityName qualifier of the SNMP device namespace instance or SNMP-compatible class is valid for that SNMP agent device.

Error Message

The SNMP agent does not respond to an SNMP protocol operation because the SNMP operation protocol data units are being dropped before reaching their destination.

Further Description:

Some entity between the source and destination is dropping packets due to network saturation.

Solutions:

Increase the value of the AgentRetryCount qualifier of the SNMP device namespace instance or SNMP-compatible class.

Decrease the value of the AgentFlowControlWindowSize qualifier of the SNMP device namespace instance or SNMP-compatible class. This reduces the number of outstanding protocol data units sent to that device.

Error Message

The SNMP agent does not respond to an SNMP protocol operation because the SNMP response protocol data units are being dropped before reaching their destination.

Further Description:

Some entity between the destination and source is dropping packets due to network saturation.

Solutions:

Increase the value of the AgentRetryCount qualifier of the SNMP device namespace instance or SNMP-compatible class.

Decrease the value of the AgentFlowControlWindowSize qualifier of the SNMP device namespace instance or SNMP-compatible class. This reduces the number of outstanding protocol data units sent to that device and, therefore, the number of responses being returned.

Error Message

The SNMP agent does not respond to an SNMP protocol operation because the SNMP agent is dropping the SNMP protocol data units.

Further Description:

The SNMP agent is dropping packets due to saturation.

Solutions:

Increase the value of the AgentRetryCount qualifier of the SNMP device namespace instance or SNMP-compatible class.

Decrease the value of the AgentFlowControlWindowSize qualifier of the SNMP device namespace instance or SNMP-compatible class. This reduces the number of outstanding protocol data units being sent to that device and, therefore, the number of responses being returned.

Decrease the value of the AgentVarBindsPerPDU qualifier of the SNMP device namespace instance or SNMP-compatible class. This reduces the number of variable binding operations the SNMP agent must process before responding with an SNMP protocol response.


SNMP Agent Responds After Timeout

Error Message

The SNMP agent responds to an SNMP protocol operation after the SNMP provider times out of the protocol operation response.

Solutions:

Increase the value of the AgentRetryCount qualifier of the SNMP device namespace instance or SNMP-compatible class.

Increase the value of the AgentRetryTimeout qualifier of the SNMP device namespace instance or SNMP-compatible class. This causes the SNMP provider to wait longer for a protocol response before timing out of the operation.


Multiple Packets with the Same Protocol Request Identifier

Error Message

The SNMP provider sends out multiple packets with the same protocol request identifier even when the agent is responding to the SNMP protocol operation.

Further Description:

The SNMP provider is encountering a race condition because the SNMP agent device is responding slowly to protocol requests, and the SNMP provider is timing out before receiving those responses. This causes the SNMP provider to use the retransmission policy.

Solution:

Increase the value of the AgentRetryTimeout qualifier of the SNMP device namespace instance or SNMP-compatible class. This causes the SNMP provider to wait longer for a protocol response before timing out and performing a protocol operation retransmission.


SNMP Provider Returns Subset

Error Message

The SNMP provider returns a subset of the properties present for a given class definition because some entity is dropping a percentage of SNMP packets between the source and destination.

Further Description:

The SNMP provider is returning a small percentage of NULL properties for a given instance of a class because the SNMP operation and response packets are being dropped between the source and destination.

Solutions:

See the error messages in No SNMP Agent Response.

Error Message

The SNMP provider returns a subset of the instances expected for a class definition because the SNMP agent device is returning GET-NEXT variable bindings that are not lexicographically ordered.

Further Description:

The SNMP provider uses a repeated GET-NEXT process to return all the instances of a Common Information Model (CIM) class definition. The SNMP provider may find that a response to an SNMP GET-NEXT operation contains a variable binding that is lexicographically previous to the requested variable binding. In this case, the SNMP provider removes the variable binding from the next SNMP GET-NEXT operation so that the provider does not cycle in an infinite loop.

Solution:

Determine if a software upgrade to the SNMP agent software fixes this ordering problem.

Error Message

The SNMP provider returns a subset of the properties present for a class definition because the SNMP agent does not return properties that are defined as optional.

Further Description:

The SNMP provider uses both GET-NEXT and GET operations to retrieve instance information from a device. The device may fail to generate responses for all properties of a given instance because the properties are defined as optional.

Solution:

This is the expected behavior.

Error Message

The SNMP provider returns a subset of the properties present for a class definition because the SNMP agent experiences some internal error processing those properties.

Solution:

Determine if a software upgrade to the SNMP agent software fixes the internal error.

Error Message

The SNMP provider returns a subset of the properties present within an instance of a class because the SNMP agent is returning key information that is incompatible with the CIM MOF definition.

Further Description:

The SNMP provider uses a GET-NEXT operation to retrieve instance information from a device. The device may return keyed property information that is inconsistent with the MOF definition of the class being retrieved. Where keyed properties are marked with the virtual_key qualifier value set to True, these properties are derived from the SNMP instance information present within the variable binding list of the non-virtual-keyed and non-keyed properties present within the class definition. These properties are not initialized because the typing information is inconsistent with the MOF class definition.

Solutions:

  • Check that the MOF class definition is consistent with the SNMP Management Information Base (MIB) definition used to derive it.
  • Check with the SNMP agent vendor to determine the expected typing for these properties.


SNMP Provider Returns Empty Result Set

Error Message

The SNMP provider returns an empty result set for a given instance because the SNMP agent is returning key information that is inconsistent with the CIM MOF definition.

Further Description:

The SNMP provider uses a GET-NEXT operation to retrieve a particular instance of a class from a device. The device returns property information that is inconsistent with the MOF definition of the instance being retrieved. The SNMP providers drop these erroneous instances.

Solutions:

  • Check that the MOF class definition is consistent with the SNMP MIB definition used to derive it.
  • Check with the SNMP agent vendor to determine the expected typing for these properties.

Error Message

The SNMP provider returns an empty result set for a given instance because the SNMP agent is expecting key information that is inconsistent with the CIM MOF definition.

Further Description:

The SNMP provider uses a GET operation to retrieve a particular instance of a class from a device and a SET operation to update a particular instance of a class. The device may expect keyed property information that is inconsistent with the MOF definition of the instance. The SNMP agent returns an error indicating that the instance is not available.

Solutions:

  • Check that the MOF class definition is consistent with the SNMP MIB definition used to derive it.
  • Check with the SNMP agent vendor to determine the expected typing for these properties.


SNMP Provider Returns Error Result

Error Message

The SNMP provider returns an error result because the qualifier values of the SNMP device namespace instance or SNMP-compatible class do not match the expected type or values.

Further Description:

The SNMP provider uses a number of qualifiers to determine the transport context used to communicate with an SNMP agent device. All mandatory qualifiers must be present, and all optional qualifiers that are present must be defined using the correct type and values.

Solution:

Verify that the namespace qualifier values are of the expected types and values. See Creating an SNMP Namespace for information on the qualifier values and types.


Set of Returned Classes Changes Intermittently

Error Message

The set of classes returned by the SNMP providers changes intermittently.

Further Description:

The SNMP class provider uses a correlation procedure to determine the set of class definitions supported by an SNMP device. The correlation process may return different results depending on the state of the network nodes connecting the SNMP providers and the SNMP agent. If additional MIBs are compiled into the SMIR, the correlation process may return additional classes that have not been available previously from the SMIR.

Solutions:

See the following topics:

  • ICMP Host Unreachable Packets
  • ICMP Net Unreachable Packets
  • No SNMP Agent Response


Set of Returned Instances Changes Intermittently

Error Message

The set of instances returned by the SNMP providers changes intermittently.

Further Description:

The SNMP instance provider may use the services of the SNMP class provider to supply class definitions that define the SNMP MIB schema definitions used to access an SNMP device. The set of classes returned by the SNMP class provider can change intermittently due to network connectivity.

Solution:

See the following topic:

Set of Returned Classes Changes Intermittently


Troubleshooting SNMP MIB Mapping Errors

The following topics describe errors associated with SNMP Management Information Base (MIB) mapping.

Error Returned for a MIB Class

Returns Subset of Class Definition Properties

CIM MOF Class Errors


Error Returned for a MIB Class

Error Message

The SNMP provider returns an error for a class because some mandatory property qualifiers are not present or some qualifiers are not of the correct type and value.

Solution:

Make sure the qualifiers are correct for all properties of the SNMP-compatible class. See the CIM Property Qualifiers table for details.

Error Message

The SNMP provider returns an error for a class because some mandatory qualifiers are not present within the class definition or some qualifiers are not of the correct type and value.

Solution:

Make sure the qualifiers are correct for the SNMP-compatible class. See the CIM Class Qualifiers table for details.

Error Message

The SNMP provider returns an error for a class because some properties of a CIM MOF class definition do not contain valid values for some property qualifiers.

Solution:

See Mapping SNMP to the CIM Schema to make sure qualifiers are of the expected type and value.


Returns Subset of Class Definition Properties

Error Message

The SNMP provider returns a subset of the properties present for a class definition because the object_identifier qualifier value is incorrect with respect to the SNMP MIB definition.

Solution:

Check the SNMP MIB definition to make sure the object identifier is set to the correct value.


CIM MOF Class Errors

Error Message

The SNMP provider returns an error for a CIM MOF class because none of the properties of the class definition have read access.

Solution:

Check SNMP MIB definition to make sure the MOF definition is consistent with MOF class definition.

Error Message

The SNMP provider returns an error for a CIM MOF class because none of the properties of a given CIM MOF class definition have write access.

Solution:

Check SNMP MIB definition to make sure MOF definition is consistent with MOF class definition.

Error Message

The SNMP provider returns an error for a CIM MOF class because some properties of a given CIM MOF class definition are marked as keyed and no associated key_order qualifier is present, or the key_order values are invalid.

Further Description:

The key_order values are invalid if they are nonconsecutive and do not begin from index value "1".

Solutions:

  • Add the correct key_order qualifier to all properties marked as being keyed.
  • Check the ordering of all properties with the key_order qualifier to make sure that the initial value of key_order is "1" and that they are monotonically incremented based on the ordering of the properties within the SNMP MIB.


SNMP Support

The Simple Network Management Protocol (SNMP) uses a distributed architecture consisting of several nodes (that is, network devices such as hosts, routers, and terminal servers) and one or more management stations. Management stations run applications that monitor and control the nodes. Each node includes a processing element, called an agent, that retrieves and updates local management information based on requests from the management stations. The agent also notifies management stations when significant events occur. Management information about the nodes is stored as a collection of managed objects in a database called the Management Information Base (MIB). SNMP communicates management information between the management stations and the agents.

The Windows Management Instrumentation (WMI) SDK includes the following components to support SNMP:

  • Class, instance, and event providers that seamlessly integrate the modeling and manipulation of SNMP information into WMI. For additional information, see SNMP Providers. These providers map MIB object values to property values in instances of Common Information Model (CIM) classes. For more information on how this mapping is done, see Mapping SNMP to the CIM Schema.
  • An SNMP information module compiler that compiles native SNMP schema information into the format used by CIM. For additional information, see SNMP Information Module Compiler.

For a list of documents that provide more information on SNMP, see Additional Reading on SNMP.


Additional Reading on SNMP

The documents listed in the following topics provide additional information about SNMP.


Internet Engineering Task Force Documents

The following tables list Internet Engineering Task Force (IETF) Request for Comments (RFC) describing SNMPv1 and SNMPv2C. All of these documents can be freely obtained from ftp://ds.internic.net/rfc.

SNMPv1 Documents

RFC number | Title and author
RFC 1155 | Rose, M., and K. McCloghrie. "Structure & Identification of Management Information for TCP/IP-based Internets." May 1990.
RFC 1157 | Case, J., M. Fedor, M. Schoffstall, and J. Davin. "A Simple Network Management Protocol." May 1990.
RFC 1212 | Rose, M., and K. McCloghrie. "Concise MIB Definitions." March 1991.
RFC 1213 | McCloghrie, K., and M. Rose. "Management Information Base for Network Management of TCP/IP-based Internets: MIB-II." March 1991.
RFC 1215 | Rose, Marshall, ed. "A Convention for Defining Traps for Use with SNMP." March 1991.

SNMPv2C Documents

RFC number | Title and author
RFC 1901 | Case, J., K. McCloghrie, M. Rose, and S. Waldbusser. "Introduction to Community-based SNMPv2." January 1996.
RFC 1902 | Case, J., K. McCloghrie, M. Rose, and S. Waldbusser. "Structure of Management Information for Version 2 of the Simple Network Management Protocol." January 1996.
RFC 1903 | Case, J., K. McCloghrie, M. Rose, and S. Waldbusser. "Textual Conventions for Version 2 of the Simple Network Management Protocol." January 1996.
RFC 1904 | Case, J., K. McCloghrie, M. Rose, and S. Waldbusser. "Conformance Statements for Version 2 of the Simple Network Management Protocol." January 1996.
RFC 1905 | Case, J., K. McCloghrie, M. Rose, and S. Waldbusser. "Protocol Operations for Version 2 of the Simple Network Management Protocol." January 1996.
RFC 1906 | Case, J., K. McCloghrie, M. Rose, and S. Waldbusser. "Transport Mappings for Version 2 of the Simple Network Management Protocol." January 1996.
RFC 1907 | Case, J., K. McCloghrie, M. Rose, and S. Waldbusser. "Management Information Base for Version 2 of the Simple Network Management Protocol." January 1996.
RFC 1908 | Case, J., K. McCloghrie, M. Rose, and S. Waldbusser. "Coexistence between Version 1 and 2 of the Internet-standard Network Management Framework." January 1996.


SNMP Publications

The following list contains a selection of commercial publications on SNMP.

  • Rose, Marshall T. The Simple Book: An Introduction to Network Management. 2d ed. Prentice Hall, 1994.
  • Stallings, William. SNMP, SNMPv2 and CMIP: The Practical Guide to Network Management Standards. Addison Wesley, 1993.
  • Hein, Mathias, and David Griffiths. SNMP Versions 1 and 2: Simple Network Management Protocol Theory & Practice. Thomson Computer Press, 1995.
  • Perkins, David. Understanding SNMP MIBs. Prentice Hall, 1996.
  • Feit, Dr. Sidnie M. SNMP: A Guide to Network Management. McGraw-Hill, 1995.


Scripting API

The scripting API for Windows Management Instrumentation (WMI) allows you to develop script and Microsoft® Visual Basic® applications that you can use to view information about managed objects or to control managed objects. WMI provides scripting support for the following languages:

  • Visual Basic
  • Visual Basic for Applications
  • Visual Basic Scripting Edition (VBScript)
  • Microsoft® JScript®

This section contains the following topics:

  • About the Scripting API

    This topic describes the scripting API and how it is organized.

  • Using the Scripting API

    This topic provides specific information about the scripting API, and shows how you can use it to develop applications.

  • Scripting API for WMI

    This is an alphabetical reference that lists all the objects that you can create with the scripting API, and it lists the methods, properties, qualifiers, and events of the scripting API.

  • WMI Scripting API Constants

    This lists all the constants that you may need when using the scripting API.

For more information on scripting, visit the Microsoft scripting Web site at: http://msdn.microsoft.com/scripting/. This site contains detailed information on VBScript and JScript.


About the Scripting API

The scripting API for Windows Management Instrumentation (WMI) is a set of objects consisting of properties, methods, and events that you can use to develop script and Microsoft® Visual Basic® applications that view information about or control managed objects. To help you get started, the following sections discuss:

  • Document conventions

    A description of the syntax that is used in these documents.

  • Scripting Object Model

    A graphical representation of the scripting API object model.


Document Conventions

The scripting API reference uses the following document conventions:

  • Parameter types are defined using a prefix: b (Boolean), str (string), i (integer), obj (Automation object), var (Variant).
  • Optional parameters are placed in square brackets with their default values shown by assignment.
  • In the case of object parameters, the characters after the "obj" prefix indicate the type of object expected:
    • Object for an SWbemObject type object.
    • WbemObjectSet for an SWbemObjectSet type object.
    • ObjectPath for an SWbemObjectPath type object.
    • WbemNamedValueSet for an SWbemNamedValueSet type object.
    • WbemServices for an SWbemServices type object.
    • WbemLocator for an SWbemLocator type object.
    • WbemMethod for an SWbemMethod type object (for example, SWbemMethodSet.Item).
    • WbemProperty for an SWbemProperty type object (for example, SWbemPropertySet.Item).
    • WbemQualifier for an SWbemQualifier type object (for example, SWbemQualifierSet.Item).
    • WbemPropertySet for an SWbemPropertySet type object (for example, SWbemObject.Properties_).
    • WbemQualifierSet for an SWbemQualifierSet type object (for example, SWbemObject.Qualifiers_).
    • WbemMethodSet for an SWbemMethodSet type object (for example, SWbemObject.Methods_).
    • WbemEventSource for an SWbemEventSource type object (for example, SWbemServices.ExecNotificationQuery).
    • WbemPrivilegeSet for an SWbemPrivilegeSet type object.
    • WbemPrivilege for an SWbemPrivilege type object.

For example, the following code describes a Something method of an SWbemServices object:

objWbemObjectSet = objWbemServices.Something(
  strParam,
  [iFlags=0],
  [objWbemNamedValueSet=null]
);

This method returns an SWbemObjectSet object and takes three parameters, only the first of which is mandatory. The first parameter is a string, the second is an optional integer (with a default value of zero), and the third is an optional SWbemNamedValueSet (with a default value of null).


Scripting Object Model

The following diagram shows you how scripting objects relate to each other.


Using the Scripting API

This section provides specific information about the scripting API, and shows how you can use it to develop applications. These topics are discussed:

  • Object creation

    Shows how you can create objects directly in Microsoft® Visual Basic®, Visual Basic Scripting Edition (VBScript), Microsoft® Jscript®, and HTML and ASP Web pages.

  • Collections

    Shows some of the objects that support collections, and how to use these objects with Visual Basic, VBScript, and JScript.

  • Object creation and monikers

    Shows how you can create objects, and set specific security settings using monikers.

  • Direct access

    Demonstrates how you can read and set the Common Information Model (CIM) properties or execute CIM methods as if they were automation properties and methods of SWbemObject.

  • Error handling

    Discusses run-time errors and the scripting API.

  • Using the WMI Scripting Type Library

    Introduces you to the Windows Management Instrumentation (WMI) Scripting Type Library, and how to use it from your development platform.

  • WMI Scripting Security Issues

    Shows you how to read and set security settings when developing applications with the scripting API. This topic also discusses security issues associated with developing scripting applications for the Web.

  • Configuration Settings for the Scripting API

    Shows you how to change the configuration settings the scripting API.

  • Making an Asynchronous Call Using the Scripting API

    Shows you how to use asynchronous methods in your applications.

  • Using Escape Characters and WMI Scripting
  • Scripting Examples

    Lists a collection of sample programs that show you how to perform simple tasks using the scripting API.


Object Creation

For the following interfaces of the WMI scripting API, direct object creation is supported using the specified ProgID.

Interface | ProgID | CLASSID
SWbemLocator | WbemScripting.SWbemLocator | 76A64158-CB41-11d1-8B02-00600806D9B6
SWbemLastError | WbemScripting.SWbem.LastError | C2FEEEAC-CFCD-11D1-8B05-00600806D9B6
SWbemObjectPath | WbemScripting.SWbemObjectPath | 5791BC26-CE9C-11D1-97BF-0000F81E849C
SWbemNamedValueSet | WbemScripting.SWbemNamedValueSet | 9AED384E-CE8B-11D1-8B05-00600806D9B6
SWbemSink | SWbemScripting.SWbemSink | 75718C9A-F029-11d1-A1AC-00C04FB6C223

The mechanism by which an object is created depends on the programming language being used.

Visual Basic and VBScript Support for Object Creation

In Visual Basic or VBScript, object creation is supported using the CreateObject call. For example

Set locator = CreateObject("WbemScripting.SWbemLocator")

JScript Support for Object Creation

In JScript, object creation is supported using the ActiveXObject call. For example

var locator = new ActiveXObject("WbemScripting.SWbemLocator");

ASP Example

<OBJECT RUNAT=Server PROGID=WbemScripting.SWbemLocator ID=MyLocator></OBJECT>

Also, you can use the Server.CreateObject function provided by Active Server Pages (ASP), passing it the same PROGID.

HTML Example

<OBJECT ID="MyLocator" CLASSID="CLSID:76A64158-CB41-11d1-8B02-00600806D9B6"></OBJECT>


Collections

A collection is a standard automation concept that provides a uniform interface to a set of objects over which you can perform iteration. Manipulation of collections using a specific programming language usually is carried out using native features of that language.

This simplifies the task of dealing with objects that contain other objects. You can use well-known paradigms to access collections rather than use each object supporting a different interface.

The WMI API for scripting provides a number of interfaces that conform to the collection paradigm. In each case, the elements of the collection can be identified (by the Item() method) using a suitable string.

Collection | Element | Item() Accepts:
SWbemObjectSet | SWbemObject | Object path
SWbemPropertySet | SWbemProperty | Property name
SWbemQualifierSet | SWbemQualifier | Qualifier name
SWbemMethodSet | SWbemMethod | Method name
SWbemNamedValueSet | SWbemNamedValue | Value name
SWbemPrivilegeSet | SWbemPrivilege | Privilege name

Visual Basic and VBScript Support for Collections

In Visual Basic or VBScript, collections are accessed using the "For Each member in collection" mechanism. For example:

'Here MyDiskProperties is an SWbemPropertySet,
'and each Property is an SWbemProperty
For Each Property in MyDiskProperties
    WScript.Echo Property.Name
Next

JScript Support for Collections

In JScript, collections are accessed using the enumerator mechanism. For example:

// Here myDiskProperties is an SWbemPropertySet,
// and each p is an SWbemProperty
var e = new Enumerator (myDiskProperties);
for (;!e.atEnd();e.moveNext ())
{
    var p = e.item ();
    WScript.Echo (p.Name);
}


Removing Items from Collections

You can remove items from collections using the Remove method. If you attempt to remove more than one item in a collection, you may find that some items are not removed. You cannot iterate a collection while removing items because when you remove an element from a collection, the collection pointer is moved on to the next element. You may see this problem when removing items with the SWbemPropertySet.Remove or SWbemQualifierSet.Remove methods. A solution to this problem is to copy all of the names into a temporary array and then delete the elements using the array.

Note Properties and qualifiers cannot be removed from class instances or derived classes with inherited properties. Such deletion attempts will raise an error and the property or qualifier will not be removed, rather it will be reset to its default value. In the case of a derived class with inherited properties, the inherited property will not be removed and will be reset to default value of the property in the parent class.

A code sample is shown below that demonstrates how to remove properties.

Sub Remove_ClassPropertiesAndQualifiers()
 '****************************************************************
 '* Name : Remove_ClassPropertiesAndQualifiers
 '* Purpose : This example creates a test class that contains some
 '* properties and qualifiers that are iterated and removed.
 '****************************************************************
    Dim props()
    Dim quals()
    Dim services
    Dim objClass
    Dim objInstance
    Dim objProperty
    On Error Resume Next

    Set services = GetObject _
          ("WinMgmts:{impersonationLevel=impersonate}!/root/default")
    Set objClass = services.Get("")              ' Create a new class
    objClass.Path_.Class = "TestClass"           ' Name the new class
    Set objProperty = _
    objClass.Properties_.Add("keyprop", wbemCimtypeString)
    objProperty.Qualifiers_.Add "key", True                ' Make key
    Set objProperty = _
    objClass.Properties_.Add("prop1", wbemCimtypeString) ' Add a prop
    Set objProperty = _
    objClass.Properties_.Add("prop2", wbemCimtypeString) ' Add a prop
    Set objProperty = _
    objClass.Properties_.Add("prop3", wbemCimtypeString) ' Add a prop

    objClass.Qualifiers_.Add "qual1", "qual1" '  Add a few qualifiers
    objClass.Qualifiers_.Add "qual2", "qual2" '         to this class
    objClass.Qualifiers_.Add "qual3", "qual3"
    objClass.Qualifiers_.Add "qual4", "qual4"
    objClass.Qualifiers_.Add "qual5", "qual5"

    objClass.Put_                                ' Save the new class

    Set objClass = services.Get("TestClass")     '      Get the class

     ' ******************* Remove Class Qualifiers ******************

    ReDim quals(objClass.Qualifiers_.Count - 1)  ' Dimenson the array

    i = 0
    For Each objQ In objClass.Qualifiers_   '  Fill an array with the
        quals(i) = objQ.Name                ' names of the qualifiers
        i = i + 1
    Next

    For Each qualName In quals          ' Use the array to remove the
       Err.Clear                        '   qualifiers from the class
       If qualName <> "CIMTYPE" Then
          MsgBox " Qualifier [" & qualName & "] value = " & _
                   objClass.Qualifiers_(qualName).Value
          objClass.Qualifiers_.Remove qualName     ' remove qualifier
          If Err.Number = 0 Then
             MsgBox " Qualifier [" & qualName & _
                    "] Removed Successfully!"
          Else
             MsgBox "Unable to remove qualifier " & _
                     qualName, vbCritical
             MsgBox "Error " & Err.Number & vbNewLine & _
                     Err.Description, vbCritical
             MsgBox " Qualifier [" & qualName & "] value = " & _
                      objInstance.Qualifiers_(qualName).Value
             Err.Clear
          End If
       End If
    Next

    ' ********************** Remove Properties **********************
    ReDim props(objClass.Properties_.Count - 1)  ' Dimenson the array
    i = 0

    For Each objP In objClass.Properties_   '  Fill an array with the
        props(i) = objP.Name                ' names of the properties
        i = i + 1
    Next
    For Each propName In props
       MsgBox "Removing: " & propName
       objClass.Properties_.Remove propName
       If Err.Number = 0 Then
          MsgBox " Property Removed Successfully!"
       Else
          MsgBox "Unable to remove property " & propName, vbCritical
          MsgBox "Error " & Err.Number & vbNewLine & _
                  Err.Description, vbCritical
          Err.Clear
       End If
    Next

    objClass.Put_                    ' Save the changes to the class
End Sub


Object Creation and Monikers

In Common Object Model (COM), a moniker is standard mechanism for encapsulating the location and binding of another COM object. The textual representation of a moniker is called a display name.

The WMI API for scripting allows you to create SWbemObject and SWbemServices objects in a concise manner using moniker display names. This is provided as a more simple alternative to the mechanism of first creating an SWbemLocator object and explicitly connecting to WMI using additional method calls to obtain the interface that you need.

The moniker display name is simply a human-readable string that acts as a name for a WMI namespace, or a WMI class or instance. The format of this string is very similar to that of a standard WMI object path (see Object Paths). A moniker has the following parts:

  • The prefix "WinMgmts:" (mandatory)
  • A security settings component (optional)
  • A WMI object path component (optional)

The following pseudo-BNF describes moniker syntax. Sections shown in bold type indicate elements that are specific to the current release of WMI for Microsoft® Windows® 2000.

wmiMoniker : "winmgmts:" securitySetting ["[" localeSetting "]"] ["!" objectPath]
| "winmgmts:" "[" localeSetting "]" ["!" objectPath]
| "winmgmts:" [objectPath]

localeSetting : "locale" <ows> "=" <ows> localeID

localeID : a value of the form "ms_xxxx" where xxxx is a hex LCID value e.g. "ms_409".

objectPath : a valid WMI Object Path

securitySetting : "{" <ows> authAndImpersonSettings [<ows> "," <ows> privilegeOverrides]<ows> "}" <ows>
| "{" <ows> privilegeOverrides <ows> "}"

authAndImpersonSettings :
authenticationLevel
| impersonationLevel
| authority
| authenticationLevel <ows> "," <ows> impersonationLevel [<ows> "," <ows> authority]
| authenticationLevel <ows> "," <ows> authority [<ows> "," <ows> impersonationLevel]
| impersonationLevel <ows> "," <ows> authenticationLevel [<ows> "," <ows> authority]
| impersonationLevel <ows> "," <ows> authority [<ows> "," <ows> authenticationLevel]
| authority <ows> "," <ows> impersonationLevel [<ows> "," <ows> authenticationLevel]
| authority <ows> "," <ows> authenticationLevel [<ows> "," <ows> impersonationLevel]
authority : "authority" <ows> "=" <ows> authorityValue
authorityValue : Any valid WMI authority string e.g. "kerberos:mydomain\server" or "ntlmdomain:mydomain". Note that backslashes need to be escaped in JScript.
authenticationLevel : "authenticationLevel" <ows> "=" <ows> authenticationValue

authenticationValue : "default" | "none" | "connect" | "call" | "pkt" | "pktIntegrity" | "pktPrivacy"

impersonationLevel : "impersonationLevel" <ows> "=" <ows> impersonationValue

impersonationValue : "anonymous" | "identify" | "impersonate" | "delegate"

privilegeOverrides : "(" <ows> privileges <ows> ")"

privileges : privilege [<ows> "," <ows> privileges <ows>]*

privilege : ["!"] privilegeName

privilegeName : "CreateToken" | "PrimaryToken" | "LockMemory" | "IncreaseQuota"
| "MachineAccount" | "Tcb" | "Security" | "TakeOwnership"
| "LoadDriver" | "SystemProfile" | "SystemTime"
| "ProfileSingleProcess" | "IncreaseBasePriority"
| "CreatePagefile" | "CreatePermanent" | "Backup" | "Restore"
| "Shutdown" | "Debug" | "Audit" | "SystemEnvironment" | "ChangeNotify"
| "RemoteShutdown" | "Udock" | "SyncAgent" | "EnableDelegation"

Note All string literals are case-insensitive.

The "!" prefix on a privilege indicates that the privilege is to be disabled; omission of this prefix implies that the privilege is to be enabled.

The following moniker specifies the SWbemServices object that represents the namespace Root\Default, with impersonation on and the privilege wbemPrivilegeDebug (SeDebugPrivilege) enabled, and the privilege wbemPrivilegeSecurity (SeSecurityPrivilege) disabled.

winmgmts:{impersonationLevel=impersonate,(debug,!security)}!root\default

Object Path Component

The following default assignments are allowed when specifying the object path:

  • The server may be omitted from the object path, in which the local server is assumed.
  • The namespace may be omitted from the object path, in which case the default namespace is assumed. This is determined by the value of the registry key HKEY_LOCAL_MACHINE\Software\Microsoft\WBEM\Scripting\Default Namespace the default value of which is root\cimv2.
  • A class or instance can also be specified, in which case the returned object is a CIM Object rather than a Services Object.

Note It is not permissible to omit the namespace but specify the server, if a class or instance is also specified.

Here are some examples of valid moniker display names.

WinMgmts:

This identifies the default namespace on the local computer. An SWbemServices object is returned.

WinMgmts://myServer

This identifies the default namespace on the server. An SWbemServices object is returned.

WinMgmts://myServer/root/cimv2

This identifies the Root/Cimv2 namespace on the server myServer. An SWbemServices object is returned.

WinMgmts:root/cimv2

This identifies the Root/Cimv2 namespace on the local server. An SWbemServices object is returned.

WinMgmts:{impersonationLevel=impersonate}!//myServer/root/cimv2:Win32_LogicalDisk

This identifies the class Win32_LogicalDisk in the namespace Root/Cimv2 on the server myServer. An SWbemObject object is returned.

WinMgmts:{impersonationLevel=impersonate}!root/cimv2:Win32_LogicalDisk

This identifies the class Win32_LogicalDisk in the namespace Root/Cimv2 on the local server. An SWbemObject object is returned.

WinMgmts:{impersonationLevel=impersonate}!Win32_LogicalDisk

This identifies the class Win32_LogicalDisk in the default namespace on the local server. An SWbemObject object is returned.

WinMgmts:{impersonationLevel=impersonate}!//myServer/root/cimv2:Win32_LogicalDisk="C:"

This identifies the instance of Win32_LogicalDisk corresponding to drive C: in the namespace Root/Cimv2 on the server myServer. An SWbemObject object is returned.

WinMgmts:{impersonationLevel=impersonate}!root/cimv2:Win32_LogicalDisk="C:"

This identifies the instance of Win32_LogicalDisk corresponding to drive C: in the namespace Root/Cimv2 on the local server. An SWbemObject object is returned.

WinMgmts:{impersonationLevel=impersonate}!Win32_LogicalDisk="C:"

This identifies the instance of Win32_LogicalDisk corresponding to drive C: in the default namespace on the local server. An SWbemObject object is returned.

WinMgmts:{impersonationLevel=impersonate, (Debug)}

This moniker sets the impersonation level to impersonate and sets the Microsoft® Windows NT®/Windows 2000 privilege SE_DEBUG.

WinMgmts:{impersonate,(Debug,!RemoteShutdown)}

This moniker sets the impersonation level to impersonate and sets the Windows NT/Windows 2000 privilege SE_DEBUG and revokes the Windows NT/Windows 2000 privilege SE_SHUTDOWN.

WinMgmts:[locale=ms_409]!root/wmi:myclass

This moniker retrieves American English localized descriptions for the the class myclass from the root/wmi namespace.

Winmgmts:{impersonationLevel=impersonate,authority=kerberos:mydomain\server} !root/default:__cimomidentification=@

This moniker requests Kerberos authentication using the principal mydomain\server.

Winmgmts:{impersonationLevel=impersonate,authority=ntlmdomain:mydomain} !root/default:__cimomidentification=@

This moniker requests NTLM authentication using the domain mydomain.

The following VBScript example demonstrates how to combine security and locale parameters in a moniker

'*****************************************************************
'   Name    :  Moniker.vbs
'
'   Purpose :  This example shows how to set various
'              parameters in a moniker.
'****************************************************************

Set myobj = GetObject("WINMGMTS:" _
            & "{impersonationLevel=impersonate," _
            & "authenticationLevel=pktPrivacy," _
            & "authority=ntlmdomain:mydomain," _
            & "(Debug,!RemoteShutdown)}" _
            & "[locale=ms_409]" _
            & "!\\RBURNS\ROOT\CIMV2:Win32_LogicalDisk=""C:""")

wscript.echo "File system = " & myobj.filesystem

Visual Basic and VBScript Support for Display Names

In Visual Basic or VBScript, objects can be created using moniker display names using the GetObject mechanism. For example:

GetObject("WinMgmts:{impersonationLevel=impersonate}!Win32_Service=""ALERTER""")

uses monikers as a concise alternative to:

Set Locator = CreateObject("WbemScripting.SWbemLocator")' Get locator object
Set Service = Locator.ConnectServer       ' Log on to namespace
service.Security_.ImpersonationLevel = wbemImpersonationLevelImpersonate         ' Set impersonation level
Set objinstance = Service.Get("Win32_Service=""ALERTER""")
'get an instance.

JScript Support for Display Names

In Jscript, objects can be created using moniker display names using the GetObject mechanism. For example:

var AlerterService = GetObject("WinMgmts:Win32_Service=""ALERTER""");

uses monikers as a concise alternative to:

var Locator = CreateObject("WbemScripting.SWbemLocator");
var Service = Locator.ConnectServer ();
var AlerterService = Service.Get("Win32_Service=""ALERTER""");

Note Although monikers provide more direct access to objects, in certain circumstances, repeated use of monikers may be less efficient than the equivalent code that explicitly connects to WMI. If application performance is a consideration, you may wish to consider using the alternative mechanisms.

It is not possible to use the GetObject function provided by VBScript and JScript when running scripts embedded within an HTML page, as Microsoft® Internet Explorer disallows the use of this call for security reasons.

See Also

Setting the DCOM Authentication Level for the Scripting API

Setting the DCOM Impersonation Level for the Scripting API

Setting Privileges for the Scripting API


Direct Access

Direct access allows you to access the CIM properties of a CIM/WMI class or instance directly on an SWbemObject, rather than through the property collection of that object. It also allows you to execute methods on that object in the native style of the programming language rather than using the SWbemServices.ExecMethod call. Direct Access allows you to treat CIM properties and methods as if they were automation properties and methods of SWbemObject.

Visual Basic and VBScript Support for Direct Property Access

Using the dot notation, you can get the VolumeName property of an instance Win32_LogicalDisk by the following means:

VolumeName = MyDisk.VolumeName

instead of

VolumeName = MyDisk.Properties_("VolumeName")

Chaining of objects is also acceptable. To access a property of an object that is embedded in another object, you can use the syntax:

value = MyComputer.MyDisk.VolumeName

For properties that have array values, the array subscript notation is also supported:

valueOfElement = MyDisk.MyArrayProperty(3)

JScript Support for Direct Property Access

Using the dot notation, you can get the VolumeName property of an instance Win32_LogicalDisk by the following means:

var VolumeName = MyDisk.VolumeName;

instead of

var VolumeName = MyDisk.Properties_("VolumeName");

Chaining of objects is also acceptable. To access a property of an object that is embedded in another object, you can use the syntax:

var value = MyComputer.MyDisk.VolumeName;

For properties that have array values, the array subscript notation is also supported:

var valueOfElement = MyDisk.MyArrayProperty[3];

Visual Basic and VBScript Support for Direct Method Invocation

To directly invoke a method that starts a backup on a method provider on a remote computer, use the following syntax:

Set Instance =   GetObject("WinMgmts:Win32_NTEventlogFile.Name=""C:\\WINNT351\\system32\\config\\AppEvent.Evt""")

result = Instance.BackupEventLog("c:\appevt.bak")

JScript Support for Direct Method Invocation

To directly invoke a method that starts a backup on a method provider on a remote computer, use the following syntax:

instance = GetObject("WinMgmts:Win32_NTEventlogFile.Name=""C:\\WINNT351\\system32\\config\\AppEvent.Evt""");

var result instance.BackupEventLog("c:\appevt.bak");

Note If you use this approach to execute a WMI method that requires output parameters, you need to be aware that JScript does not support the use of output parameters in method calls. If your WMI method uses output parameters, then you will need to invoke the method using the using ExecMethod on a SWbemServices object instead.


Error Handling

If a call to WMI through the WMI API for scripting causes an error, the error information can be accessed using the native error mechanisms of the scripting language.

Visual Basic and VBScript Support for Error Handling

In Visual Basic or VBScript error handling is supported using the Err object. The Description property of this object will contain a localized human-readable description of the error. The Number property is set to the HRESULT returned by the scripting API. The Source property is set to a string that identifies the object that raised the error.

JScript Support for Error Handling

In JScript version 5.0, the try...catch mechanism is supported to allow error handling using the Exception object. The description property of this object will contain a localized human-readable description of the error. The number property is set to the HRESULT returned by the scripting API. Earlier versions of JScript do not support this error-handling capability


Using the WMI Scripting Type Library

To use the scripting API for WMI with Visual Basic and Microsoft® Visual InterDev®, you must add the WMI scripting type library to your projects list of available references.

You can use the following procedure to make the integrated development environment (IDE) aware of the WbemScripting type library.

To add the WMI Scripting type library to the project references:

  1. Select References from the Project menu.
  2. In the Available References dialog box, check Microsoft WBEM Scripting V1.0 Library or Microsoft WMI Scripting V1.1 Library (whichever appears).
  3. If no suitable option appears in the Available References list, add it by using the Browse button in the References dialog box. The Browse button opens an Add Reference dialog box that enables you to locate the WbemScripting type library. The WbemScripting type library resides in the file Wbemscrp.tlb in the Wbem installation directory.
  4. Select the file and click Open. Microsoft WBEM Scripting V1.0 Library or Microsoft WMI Scripting V1.1 Library appears on the references list. Make sure you check the box next to this item in the list.

Using the type library with Microsoft Windows Scripting Host

You can reference items in the type library from WSH files using the <REFERENCE/> tag. The following example shows how to create a reference to the WMI scripting type library in a WSH file:

<JOB id="MyJob">
<REFERENCE object="WbemScripting.SWbemLocator" version="1.1"/>
<SCRIPT language="VBScript">
    .
    .
    .
</SCRIPT>
</JOB>


Making an Asynchronous Call Using the Scripting API

Many of the methods in the scripting API for WMI are available in two forms, synchronous and asynchronous. Programs that call synchronous methods generally cannot continue or respond to user input until the synchronous call is complete. To prevent this from happening, most of the synchronous methods allow you to specify a iFlags parameter of wbemFlagReturnImmediately that instructs the call to return immediately even if the results are not available.

Asynchronous methods return immediately after being called. Thus, your program can continue doing other things. When the original call is complete, it calls the OnCompleted event of an object sink in your program and executes whatever code you have placed there to process the result of the call. Use asynchronous methods for any call that would normally take a long time to complete, such as a complex query or event notification, and your program will be more responsive.

Note You can use asynchronous calls within HTML pages but not from server side ASPs.

To make an asynchronous call in Microsoft Visual Basic

  1. In the General Declarations section of your code, declare an object sink of type SWbemSink using the WithEvents keyword.
    Dim WithEvents sink As SWbemSink
  2. In a subroutine on your form, declare an object of type SwbemLocator and create an object of type SWbemSink.
    Dim loc As New SWbemLocator
Set sink = New SWbemSink
  3. Log on to WMI and set the impersonation level:
    Set services = loc.ConnectServer ' log on
services.Security_.ImpersonationLevel = wbemImpersonationLevelImpersonate

    For more information on impersonation, see Setting the DCOM Impersonation Level for the Scripting API.

  4. If you are making multiple asynchronous calls using the same object sink, be sure to provide an object of type SWbemNamedValueSet for the objWbemAsyncContext parameter so you can identify the source of the call.
    Dim cntxt As Object
Set cntxt = New SWbemNamedValueSet ' create a new named value set
cntxt.Add "AsyncId", "0"  'add a named value to identify the call
  5. Call the asynchronous method and provide your object sink as the first parameter.
    services.ExecQueryAsync sink, "SELECT * FROM win32_process",,,,cntxt
  6. Place the code that processes the information returned from the asynchronous call in the appropriate event of your implementation of the SWbemSink object sink. There are four events defined for SWbemSink. OnObjectReady is triggered when an asynchronous call returns an object. Place code to process instances or classes returned from asynchronous calls such as ExecQueryAsync to process objects as they are delivered. For example, if you wanted to place the results of a call to ExecQueryAsync in a listbox you could place the following code in the OnObjectReady event:
    Private Sub sink_OnObjectReady(ByVal objWbemObject As WbemScripting.ISWbemObject, ByVal objWbemAsyncContext As WbemScripting.ISWbemNamedValueSet)

    Set cntxt_item = objWbemAsyncContext.Item("AsyncId")
    If cntxt_item.Value = 0 Then 'check to see what async method
                                 'triggered this event.
        List1.AddItem (objWbemObject.Name)
    End If
End Sub

Place code that will finish up an asynchronous operation in the OnCompleted event.

Private Sub sink_OnCompleted(ByVal iHResult As WbemScripting.WbemErrorEnum, ByVal objWbemErrorObject As WbemScripting.ISWbemObject, ByVal objWbemAsyncContext As WbemScripting.ISWbemNamedValueSet)

    MsgBox ("Asynchronous operation complete")
End Sub

You may want to examine the iHresult parameter returned by the OnCompleted event. This parameter will tell you if the asynchronous call was successful, or if an error occurred. In the event of success, the iHresult will be equal to zero. Any other value may indicate an error and you should check the values in the error object that will be returned in the objWbemErrorObject parameter.

Note You do not need to create a WMI error object when there is an error as you do with synchronous methods. One will be passed back to you in the objWbemErrorObject parameter.

To make an asynchronous call from Visual Basic Scripting Edition

  1. Declare a service object and a sink object
    Dim service
Dim sink
  2. Create a subroutine for each event your asynchronous event may trigger. Place code in these subroutines to handle each event as it is received.
    Sub SINK_OnCompleted(iHResult, objErrorObject, objAsyncContext)
    WScript.Echo "Asynchronous operation is done."
End Sub

Sub SINK_OnObjectReady(objObject, objAsyncContext)
    WScript.Echo (objObject.Name)
End Sub

    You may want to examine the iHresult parameter returned by the OnCompleted event. This parameter will tell you if the asynchronous call was successful, or if an error occurred. In the event of success, the iHresult will be equal to zero. Any other value may indicate an error and you should check the values in the error object that will be returned in the objErrorObject parameter.

  3. Log on to WMI and get a services object.
    Set service = GetObject("winmgmts:")
  4. Create the object sink.
    Set sink = WScript.CreateObject("WbemScripting.SWbemSink","SINK_")
  5. Set the impersonation level.
    service.Security_.ImpersonationLevel = 3
  6. Make an asynchronous call and pass your sink as a parameter.
    service.InstancesOfAsync sink, "Win32_process"
  7. Make a call that prevents the script from ending before all the events are received. A simple way to do this is to use a Windows Scripting Host Echo command.
    WScript.Echo "Waiting for instances."

When you execute this script you may see the first instance return before the message "Waiting for events", or you may see it afterwards. This is the nature of asynchronous processing. If you close the "Waiting for events" message box too soon, you may not see all the instances.

To cancel an asynchronous call

  1. You can cancel an asynchronous call by invoking the Cancel method. All the asynchronous calls associated with this sink object will be canceled. Thus, you may wish to use separate sinks for asynchronous operations that need to be independent.
  2. You should release the object sink by assigning it to Nothing.

The following example demonstrates how to cancel an asynchronous call.

objwbemsink.Cancel()
set objwbemsink= Nothing

Note It is not enough to assign this sink to Nothing to cancel an unwanted asynchronous operation. You must also call the Cancel method to make WMI discontinue the operation and free the associated resources. This is particularly important with asynchronous operations that may take a long time to complete, such as queries, or operations that may never complete, such as ExecNotificationQueryAsync.

For more examples that show how to make asynchronous calls from Visual Basic, VBScript, JScript, and within HTML, see Scripting Examples.


Configuration Settings for the Scripting API

There are several registry-based configuration values for the scripting API. Enable for ASP Configuration Setting.

Default Namespace Configuration Setting.

You can use the WMI Control application to change these setting or set permissions for WMI users. The Help file built into the WMI Control application documents how to use this control. See the topic, "To Change the WMI Scripting Settings" for information about modifying the registry keys associated with scripting.

To execute the WMI Control

To execute the application from Windows 2000, select the Start/Run menu item, type in Wmimgmt.msc, and press ENTER.

To execute the application from Windows 95/98 or Windows NT version 4.0, select the Start/Run menu item, type Wbemcntl.exe, and press ENTER.


Enable for ASP Configuration Setting

The enable for ASP registry key is used only with Windows NT 4.0. This key determines how the scripting API will behave when it is called on an impersonated thread. If you set the registry value to zero (0), the API will reject any operation on an impersonated thread. See Enable for ASP Registry Key for more information about this setting.

To change the enable for ASP registry key using the WMI Control Application

  1. Start the WMI Control application.
  2. Click the Advanced tab.
  3. Select the checkbox next to Allow scripting access to WMI services from ASP.


Default Namespace Configuration Setting

The Default Namespace registry key lets you specify which namespace will be used by the scripting API unless otherwise specified. The Default Namespace registry key is used on all supported Windows platforms:

  • Windows NT 4.0 Service Pack 4 or later
  • Windows 2000
  • Windows 98
  • Windows 95 OSR2

To change the WMI scripting settings using the WMI Control Application

  1. Start the WMI Control application.
  2. Click the Advanced tab.
  3. Under Default namespace for scripting, click Change.
  4. In the Browser for Namespace dialog box, select a different default namespace as a target for your scripts.


WMI Scripting Security Issues

When developing scripts for WMI, be sure to consider these security issues:

  • Setting the DCOM Impersonation level for the Scripting API
  • Setting the DCOM Authentication Level for the Scripting API
  • Setting Privileges for the Scripting API
  • Using Kerberos or NTLM authentication with the scripting API
  • Developing Scripting Applications for the Web


Setting the DCOM Impersonation Level for the Scripting API

When you make calls to the scripting API, it is sometimes necessary to set the Distributed COM (DCOM) impersonation level that WMI will use. If the impersonation level you use is not sufficient, a provider may refuse the request or provide incomplete information. If you do not specifically set the impersonation level in either a moniker or by setting SWbemSecurity.ImpersonationLevel on a securable object, the current release of WMI sets the default impersonation level to wbemImpersonatonLevelImpersonate. Previous versions of WMI set the default impersonation level to wbemImpersonationLevelIdentify.

DCOM supports four levels of impersonation.

Name | Value | Moniker name | Meaning
wbemImpersonationLevelAnonymous | 1 | Anonymous | Hides the credentials of the caller. Calls to WMI may fail with this impersonation level.
wbemImpersonationLevelIdentify | 2 | Identify | Allows objects to query the credentials of the caller. Calls to WMI may fail with this impersonation level.
wbemImpersonationLevelImpersonate | 3 | Impersonate | Allows objects to use the credentials of the caller. This is the recommended impersonation level for WMI Scripting API calls.
wbemImpersonationLevelDelegate | 4 | Delegate | Allows objects to permit other objects to use the credentials of the caller. This impersonation, which will work with WMI Scripting API calls but may constitute an unnecessary security risk, is supported only under Windows 2000.

If the impersonation is not set to wbemImpersonatonLevelImpersonate or wbemImpersonationLevelDelegate, calls to the Scripting API for WMI may fail with an error code of wbemErrAccessDenied (hexadecimal 0x80041003). There are two ways to specify the impersonation level of an API call: using monikers and using the security object, Security_.

Monikers

If you are using monikers, you can simply specify this parameter as part of the moniker. When setting the impersonation level as part of a moniker, you need to remove the wbemImpersonationLevel prefix from the constant name. For example, to set the authentication level to Impersonate in a moniker, you would specify Impersonate, not wbemImpersonationLevelImpersonate. The following example shows how to set the impersonation level in Visual Basic:

Set Service = GetObject("winmgmts:{impersonationLevel=impersonate}!root\cimv2")

or

Set Service = GetObject("winmgmts:root\cimv2")
Service.Security_.ImpersonationLevel = 3

You can set the impersonation level when using monikers to log on to WMI and get an instance of a class. The next example shows how to get an instance of the Microsoft® Win32® process that has a process handle of zero.

set object = GetObject("winmgmts:{impersonationLevel=impersonate}!root\cimv2:Win32_Process.Handle='0'")

You can see more examples of monikers at Object Creation and Monikers..

Security_ Object

The other way you can set the impersonation level is from the security object Security_, which is a property of these objects:

SWbemServices, SWbemObject, SWbemObjectSet, SWbemEventSource, SWbemObjectPath and SwbemLocator.

Note The Security_ property of SWbemObjectPath is there for formatting purposes and not for intrinsic security support. You can use this property to inspect and define the security components of a moniker, but these properties do not grant security attributes to the SWbemObjectPath object.

Security_, a SWbemSecurity type of security object, has three properties: Privileges, AuthenticationLevel, and ImpersonationLevel. When you set the properties of this object, the security settings are passed on to descendants of the original object. This means that you can set the impersonation level of an SWbemServices object after logging on to WMI and API; calls using this object or objects created from it (such as objects of type SWbemObject) will succeed. Here's an example:

Dim loc As New SWbemLocator
Dim WbemObjectSet As SWbemObjectSet

Set services = loc.ConnectServer       'default log on
services.Security_.ImpersonationLevel = wbemImpersonationLevelImpersonate
Set WbemObjectSet = services.InstancesOf("Win32_process")
For Each process In WbemObjectSet
    MsgBox process.Name
Next

The enumeration succeeds because the objWbemObjectSet object inherits the wbemImpersonationLevelImpersonate impersonation level from the parent object, services.

Note The impersonation level required for WMI applications depends on the provider that is servicing these requests. Consult the documentation of the provider you are using to determine the exact impersonation level required.


Setting the DCOM Authentication Level for the Scripting API

When you make calls to the WMI Scripting API, you can set the DCOM authentication level that WMI will use. The following table lists the authentication levels.

Name | Value | Moniker name | Meaning
wbemAuthenticationLevelDefault | 0 | Default | WMI uses the default Windows Authentication setting.
wbemAuthenticationLevelNone | 1 | None | Uses no authentication.
WbemAuthenticationLevelConnect | 2 | Connect | Authenticates the credentials of the client only when the client establishes a relationship with the server.
WbemAuthenticationLevelCall | 3 | Call | Authenticates only at the beginning of each call when the server receives the request.
WbemAuthenticationLevelPkt | 4 | Pkt | Authenticates that all data received is from the expected client.
WbemAuthenticationLevelPktIntegrity | 5 | PktIntegrity | Authenticates and verifies that none of the data transferred between client and server has been modified.
WbemAuthenticationLevelPktPrivacy | 6 | PktPrivacy | Authenticates all previous impersonation levels and encrypts the argument value of each remote procedure call.

Changes to the authentication property of WMI objects should be thought of as a request for DCOM to modify the authentication associated with a WMI object. In some cases these requests may not be honored by the operating system and the change will not take place. Such failures do not raise an error so you should check the value after you change the authentication level to see if the call was successful. An example of this would be an attempt to set the authentication level for a SWbemServices object with a connection to a local computer to the value WbemAuthenticationLevelPktIntegrity. Because local connections always have an authentication level of wbemAuthenticationLevelPkgPrivacy, the following example will fail to set the authentication level.

Set objservices = GetObject _

("WinMgmts:{impersonationLevel=impersonate}!/root/cimv2")

objservices.Security_.AuthenticationLevel = wbemAuthenticationLevelPktIntegrity

Setting Authentication levels

There are two ways to specify the authentication level of an API call: using monikers and using the security object, Security_.

Monikers

If you are using monikers, you can simply specify this parameter as part of the moniker. When setting the authentication level as part of a moniker, you need to remove the WbemAuthenticationLevel prefix from the constant name. For example, to set the authentication level to Connect in a moniker, you would specify Connect, not WbemAuthenticationLevelConnect. Here are some examples of setting the authentication level in a moniker to pktPrivacy.

Set Service = GetObject("winmgmts:{impersonationLevel=impersonate,authenticationLevel=pktPrivacy}!root/cimv2")

Set Service = GetObject("winmgmts:{authenticationLevel=pktPrivacy}!root\cimv2")

Security_ Object

The other way you can set the authentication level is from the security object called Security_, which is a property of these objects:

SWbemServices SWbemObject SWbemObjectSet SWbemEventSource SWbemObjectPath SwbemLocator

Note The Security_ property of SWbemObjectPath is there for formatting purposes and not for intrinsic security support. You can use this property to inspect and define the security components of a moniker, but these properties do not grant security attributes to the SWbemObjectPath object.

When using the DCOM authentication level, PktPrivacy, the parameter value of remote procedure calls is encrypted for synchronous calls to the scripting API. When using asynchronous methods, only the initial call is encrypted. The data returned to your client application by asynchronous methods will not be encrypted, even if you use PktPrivacy DCOM authentication.

You can see more examples of monikers at Object Creation and Monikers..


Setting Privileges for the Scripting API

When using the WMI Scripting API to perform certain tasks such as examining the Windows NT/Windows 2000 security log or requesting that the operating system shut down, you may need to set Windows NT/Windows 2000 privileges. You can set these privileges from the Privileges property of a SWbemSecurity object or with a moniker.

To set Windows NT/Windows 2000 privileges in Visual Basic

  1. Create an object of type SwbemLocator.
    Dim objwbemLocator As New SWbemLocator
  2. Add the new privilege to the Security_ object.
    objwbemLocator.Security_.Privileges.Add wbemPrivilegeDebug, True
  3. Log on to WMI and get a services object.
    Set service = objwbemLocator.ConnectServer

The services object inherits the wbemPrivilegeDebug privilege.

Alternatively, you could set this privilege using a Windows NT/Windows 2000 privilege string and the SWbemPrivilegeSet.AddAsString method. For example:

objwbemLocator.Security_.Privileges.AddAsString ("SeDebugPrivilege")

Monikers

When setting privileges as part of a moniker, you need to remove the wbemPrivilege prefix from the constant name. For example, to set the debug privilege in a moniker, you would specify Debug not wbemPrivilegeDebug. For example:

Set Service = GetObject("winmgmts:{impersonationLevel=impersonate, (Debug)}")

Revoking and Resetting Privileges

You may want to revoke a specific privilege and set another. To revoke a privilege as part of a moniker, add the "!" prefix to the privilege name. The following example sets the SeDebugPrivilege privilege and revokes the SeRemoteShutdownPrivilege privilege:

Set Service = GetObject("winmgmts:{impersonate,(Debug,!RemoteShutdown)}")

Changing Privileges on Different Windows Platforms

When working with privileges, it is crucial to consider the fundamental differences in how different versions of Windows handle changes to privileges. If you are developing an application that will only be used on Windows 2000 platforms, you can set or revoke privileges at any time. If your application needs to be portable for use on Windows NT 4.0 platforms, you must set the privileges either

  • On the SWbemLocator object, through which you make the first call to ConnectServer in your application.
  • As part of the moniker, which you pass to the first GetObject call in your application.

You can set privileges on Windows 95 platforms, but these settings will have no effect.

On Windows NT 4.0 platforms, privilege changes can only be made on the process token. Application developers should take this into account when their script is hosted by a generic application such as Internet Explorer or Internet Information Services (IIS) as the privilege changes will apply to the entire process from the point that the call is made on a WMI scripting object that has privilege settings.

You only need to set up privileges when accessing WMI on your computer. When accessing a remote host, DCOM RPC takes care of privileges automatically

You can consult the documentation or schema for the specific provider you are using to find out what privileges are required.

An SWbemPrivilegeSet object is a set of privilege override requests for a particular object, which WMI will attempt to enforce when making API calls with that object. An SWbemPrivilegeSet object does not define the privileges available to the current user or process.

For a complete list of privileges, see WbemPrivilegeEnum, Windows NT/Windows 2000 Privilege Strings


Using Kerberos or NTLM Authentication with the Scripting API

You can connect to WMI from the scripting API using either standard NTLM authentication or with Kerberos authentication. You can use a moniker to specify what type of authentication will be used or you can specify authentication in the strAuthority parameter to the SWbemLocator.ConnectServer method.

If the strAuthority parameter begins with the string "kerberos:", it is assumed to refer to a Kerberos principal name and Kerberos authentication will be used. If the strAuthority parameter begins with the string "ntlmdomain:", NTLM authentication will be used.

You can use the authority part of a moniker to specify what type of authentication will be used to connect to WMI. To use Kerberos authentication when using a moniker include the string "authority=kerberos:" followed by the principal name. To use NTLM authentication "authority=ntlmdomain:" followed by the NTLM domain name.

Note The authority parameter can only be used with connections to remote WMI servers. If you attempt to set the authority as part of a moniker or with a call to SWbemLocator.ConnectServer for a local WMI connection, the connection attempt will fail.

The following moniker requests Kerberos authentication using the principal mydomain\server.

winmgmts:{impersonationLevel=impersonate,authority=kerberos:mydomain\server} !root/default:__cimomidentification=@

The following moniker requests NTLM authentication using the domain mydomain.

winmgmts:{impersonationLevel=impersonate,authority=ntlmdomain:mydomain} !root/default:__cimomidentification=@

If you do not specify a value for the authority field when connecting to a remote system, the operating system will negotiate with DCOM to determine whether NTLM or Kerberos authentication will be used.


Developing Scripting Applications for the Web

This topic covers some security issues that you need to be aware of when writing scripts for Web pages.

  • Access Denied Error when Connecting

    This topic covers a problem you may have connecting to WMI from Active Server Pages (ASP).

  • Connecting to WMI from ASP

    This topic covers user credentials and ASP pages.

  • Enable for ASP Registry Key

    This topic discusses an important setting associated with impersonation and ASP.

  • GetObject and HTML This topic covers an important restriction to when you can use the GetObject function.


Access Denied Error When Connecting

WMI may have difficulty connecting to a namespace when running a script from an ASP page. This is because IIS configures ASP pages to run in the context of a special account with a name derived from your computer name. The user accounts set up by IIS are not always recognized by WMI. There are several solutions to this problem.

  1. To grant access to WMI, you can use the WMI Control application (Wbemcntl.exe) on the user account created by IIS.
  2. You can change the security configuration in IIS to use Windows NT/Windows 2000 Challenge/Response rather than Anonymous Access. The identity of the client running the browser will then be passed through to WMI.
  3. You can change the IIS account used for anonymous access to another account that is recognized by WMI.


Connecting to WMI from ASP

If you need to specify the credentials of a domain account when connecting to WMI from an ASP pages, the connection to WMI must be made using SWbemLocator.ConnectServer rather than by using a moniker and a GetObject call. The strUser and strPassword parameters to the ConnectServer method must specify valid credentials for the domain account.

ASP pages cannot connect to WMI using the impersonation credentials of Internet Explorer clients running on Windows NT 4.0. Instead, the credentials used to run IIS will be used if the enable for ASP registry option has been set. For information on the registry key for ASP, see Enable for ASP Registry Key.

If you call the ConnectServer method with default user credentials, or if the moniker and GetObject call are used, your application will attempt to connect to WMI using the credentials that were used to run IIS and will only succeed if these credentials are valid for accessing WMI.

For example, when IIS is run using the LocalSystem account and WMI is not on the same host as IIS, the default credentials will always fail because the LocalSystem account cannot be used to log in to a remote server. If WMI and IIS are resident on the same host, such a configuration would succeed if both services were running using the LocalSystem account. In this case, either IIS would need to be run using an account which could be used to access WMI, or explicit credentials must be passed to the ConnectServer method specifying a valid domain account that can access WMI.

Kerberos and IE5

If you are using Kerberos authentication and Internet Explorer version 5.0, ASP pages may not work correctly if the security settings are set with all permissions options set to low safety and all other options set to enabled in conjunction with the "Automatic logon with current username and password" option. You should use the default security settings when using Kerberos authentication to connect to an ASP page.

Kerberos and IIS

If you are using Kerberos authentication and IIS, some ASP scripts that require an impersonation level of delegate may not work if you use medium or high security settings for the virtual directories. You should set the security setting to low for virtual directories if your scripts require the delegation impersonation level.


Enable for ASP Registry Key

The following registry key value is added during the self-registration of Wbemdisp.dll:

HKLM\Software\Microsoft\WBEM\Scripting\Enable for ASP

This key value is a DWORD value that is only used on Windows NT 4.0. It determines how the scripting API will behave when it is called on an impersonated thread. If you set the registry value to 0, the API will reject any operation on an impersonated thread.

This is necessary because on Windows NT 4.0 impersonation characteristics on an intermediate server cannot be transferred to another server by the Distributed Component Object Model (DCOM). For example, when server-side script is run in an ASP page by IIS, the client, which is Internet Explorer, requests impersonation with IIS. For Windows NT 4.0, this impersonation cannot be transferred to WMI. Instead, WMI will receive the request under the guise of the user running IIS.

To avoid the misleading impression that such calls into the ASP are truly impersonated, the API will reject operations on impersonated threads unless the registry value previously defined is set to a non-zero value. In that case, the API will execute under the guise of the account used to run the IIS service.

You must set this key to a non-zero value in order for server-side ASP to work correctly.

Note Once you set this key, the scripting API will have all of the permissions of the IIS user (and not the Internet Explorer client), and any operations will be audited to that user. Therefore, when enabling the flag, administrators need to remember this. Administrators should always use appropriate IIS security mechanisms to secure network access to the ASPs.

The preferred method for manipulating the enable for ASP key is the WMI Control application (Wbemcntl.exe). See the topic "To change the WMI scripting settings" in the help file named Wbemcntl.chm for information about modifying the registry keys associated with scripting.

Note This registry key is sometimes reset to 0 when you upgrade WMI. You should check this registry key after upgrading WMI.

Changes to this registry key only take affect on initialization of the WMI Scripting API. Therefore, you may need to restart the IIS service in order for the change to be effective.


GetObject and HTML

You cannot use the GetObject function provided by VBScript and JScript when running scripts embedded within an HTML page. Internet Explorer disallows the use of this call because of security reasons.


Using Escape Characters and WMI Scripting

WMI Scripting methods often use object paths that can be difficult to construct because they contain embedded quote and backslash characters. This problem becomes more difficult when you are specifying an object path as part of a query because you may get an invalid query error for simple queries that appear to be correct. The key to constructing valid object path strings is knowing how to escape the quote and backslash characters. The rules for creating valid object paths are simple

  • You can use a single quote within a WQL query to delimit a string value.

  • You should escape backslashes in WQL queries with another backslash
    •

  • If your string value contains double quotes you should escape them with another double quote.
    •

Here are some examples of WQL queries that contain escape characters. The first example demonstrates how to use single quotes.

Set myobj = GetObject("WinMgmts:{impersonationLevel=impersonate}" & _
                         "!Win32_LogicalDisk='C:'")

The next example demonstrates how to escape backslashes and quotes.

Set objOpsys = _
             GetObject("winmgmts:{impersonationLevel=impersonate}") _
             .ExecQuery("SELECT * FROM Win32_OperatingSystem " & _
                        "WHERE Name=" & _
                        """Microsoft Windows 2000 Professional|" & _
                        "C:\\WINNT|\\Device\\Harddisk0\\Partition1""")


Scripting Examples

The following list of examples shows you how you can use the scripting API with Visual Basic and VBScript.

Name | Description
Creating Association Classes and Embedded Objects with the Scripting API | Demonstrates how to create embedded objects and association classes.
Creating a Share With the Scripting API | Creates a share for a file and sets up the users that may access it.
SWbemServices.SubclassesOf Examples | Demonstrates how to use the SWbemServices.SubclassesOf method.
SWbemServices.SubclassesOfAsync Examples | Demonstrates how to use the SWbemServices.SubclassesOfAsync method.
SWbemServices.InstancesOfAsync Examples | Demonstrates the use of SWbemServices.InstancesOfAsync in Visual Basic, VBScript, and within an HTML page, using JScript.
SWbemServices.Delete Examples | Shows how to create, save, and delete a class.
SWbemServices.DeleteAsync Examples | Shows how to asynchronously create, save, and delete a class.
SWbemServices.Security_ Examples | Demonstrates how to change security settings.
SWbemObject.ExecMethod_ Examples | Demonstrates how to execute a CIM method.
SWbemServices.ExecNotificationQuery Examples | Demonstrates how to receive events semi-synchronously.
SWbemServices.ExecNotificationQueryAsync Examples | Demonstrates how to receive events asynchronously.
ASP Examples | Shows how to use the scripting API in ASP pages.
SWbemServices.Get and SWbemObject.Put_ Examples | Shows how to create a new class and save it in Visual Basic and from an HTML page, using VBScript.


Creating Association Classes and Embedded Objects with the Scripting API

The following example creates a class, a class with an embedded object, and an association class. Instances of embedded objects are stored in composite objects as properties of type CIM_OBJECT. To determine the class of an embedded object in an instance of a composite class, you need to examine the CIMTYPE qualifier of the CIM_OBJECT. The object references in an association class are stored in properties of type CIM_REFERENCE. To determine the actual object paths, you need to examine the CIMTYPE qualifier of the CIM_REFERENCE type properties.

'********************************************************************
'  Name    :  cmd_embobj_Click
'
'  Purpose :  This example creates a composite class that contains
'             an embedded instance of another class. This class also
'             creates an association class that associates the class
'             with the composite class.
'********************************************************************

Private Sub cmdembobj_Click()
Dim services As SWbemServices
Dim objClass As SWbemObject
Dim objInstance As SWbemObject
Dim objProperty As SWbemProperty

   On Error GoTo ErrorHandler         ' Enable error-handling routine
   Set services = GetObject _
          ("WinMgmts:{impersonationLevel=impersonate}!/root/default")

  '*************   Create a new class                   *************
   Set objClass = services.Get("")               ' Create a new class
   objClass.Path_.Class = "EmbeddedClass"        ' Name the new class
   Set objProperty = _
       objClass.Properties_.Add("keyprop", wbemCimtypeString)
   objProperty.Qualifiers_.Add "key", True                  'Make key
   objClass.Put_                                 ' Save the new class

   Set objClass = services.Get("EmbeddedClass")
   Set objInstance = objClass.SpawnInstance_     ' Create an instance
   objInstance.keyprop = "key1"                  '        Set the key
   objInstance.Put_                              '  Save the instance

   '*************  Create a composite class             *************
   Set objClass = services.Get("")               ' Create a new class
   objClass.Path_.Class = "CompositeClass"       ' Name the new class
   Set objProperty = _
       objClass.Properties_.Add("keyprop", wbemCimtypeString)
   objProperty.Qualifiers_.Add "key", True       '           Make key
                                           'Add embedded obj property
   Set objProperty = _
       objClass.Properties_.Add("EmbObj", wbemCimtypeObject, False)
   objClass.Put_                                 ' Save the new class

   '*************  Create a composite class instance    *************
   Set objClass = services.Get("CompositeClass")
   Set objInstance = objClass.SpawnInstance_
   objInstance.keyprop = "key2"                         ' set the key
   Set objInstance.EmbObj = services.Get("EmbeddedClass=""key1""")
   objInstance.Put_                                'save the instance

   '*************  Create an association class          *************
   Set objClass = services.Get("")               ' Create a new class

   objClass.Path_.Class = "RefClass"             ' Name the new class
   objClass.Qualifiers_.Add "Association", True  ' Make association
   Set objProperty = objClass.Properties_.Add _
       ("EbdclassRef", wbemCimtypeReference, False)    ' Add ref prop
   objProperty.Qualifiers_.Add "key", True                  'make key
   objProperty.Qualifiers_.Add "CimType", "ref:EmbeddedClass"
   Set objProperty = objClass.Properties_.Add _
                    ("CmpstclassRef", wbemCimtypeReference, False)
   objProperty.Qualifiers_.Add "key", True                  'make key
   objProperty.Qualifiers_.Add "CimType", "ref:CompositeClass"
   objClass.Put_                                 ' save the new class

   '*************  If no error then notify user if success **********
   If Err.Number = 0 Then
      MsgBox "Classes created successfully", vbInformation, "Success"
   End If

Exit Sub                                      ' Exit to avoid handler

ErrorHandler:                                ' Error-handling routine
     MsgBox "Error number: " & Str(Err.Number) _
          & vbNewLine & "Description: " & Err.Description, vbCritical
Exit Sub
End Sub


SWbemServices.SubclassesOf Examples

The SWbemServices.SubclassesOf method returns a collection of subclasses of a specified class. Shown below are examples for Microsoft Visual Basic and Visual Basic Scripting Edition.

Microsoft Visual Basic Example

'*******************************************************************
'   Name    :  cmd_classes_get_Click
'
'   Purpose :  This example fills a list box with the subclasses of
'              Cim_ComputerSystem when a command button is clicked.
'********************************************************************

Private Sub cmd_classes_get_Click()

    Dim colWbemObjectSet As SWbemObjectSet
    Dim objWbemLocator As SWbemLocator
    Dim objWbemObject As SWbemObject
    Dim objWbemServices As SWbemServices

    Set objWbemLocator = New SWbemLocator

    ' Connects to the WMI on the local computer.
    Set objWbemServices = objWbemLocator.ConnectServer

    Set colWbemObjectSet = _
          objWbemServices.SubclassesOf("Cim_ComputerSystem")

    For Each objWbemObject In colWbemObjectSet

        lst_subclasses.AddItem (objWbemObject.Path_.RelPath)

    Next objWbemObject

    Set objWbemLocator = Nothing

End Sub

Visual Basic Scripting Edition Example

For each instance in GetObject("winmgmts:").subclassesof("Cim_ComputerSystem")
   wscript.echo instance.Path_.RelPath
Next


SWbemServices.SubclassesOfAsync Examples

These examples demonstrate SWbemServices.SubclassesOfAsync.

Microsoft Visual Basic Example

This example asynchronously displays the subclasses of the class "Cim_ComputerSystem". The SWbemSink.OnObjectReady event checks the value in the context object objwbemNamedValueSet to see what asynchronous call triggered this event. If you have multiple asynchronous calls using the same sink, you can use different values in objwbemNamedValueSet and execute the appropriate code in this event.

Private Sub SubclassesAsync_Click()
    Dim services As SWbemServices
    Dim objwbemNamedValueSet As SWbemNamedValueSet

    Set sink = New SWbemSink
    Set services = _
      GetObject("winmgmts:{impersonationLevel=impersonate}")
    Set objwbemNamedValueSet = New SWbemNamedValueSet ' context object
    objwbemNamedValueSet.Add "sinkname", "SubclassesOfAsync"'
    services.SubclassesOfAsync sink, "Cim_ComputerSystem" _
       , , , objwbemNamedValueSet

End Sub

Private Sub sink_OnObjectReady(ByVal objWbemObject As WbemScripting.ISWbemObject, ByVal objWbemAsyncContext As WbemScripting.ISWbemNamedValueSet)
  Dim objwbemNamedValue As SWbemNamedValue

  Set objwbemNamedValue = objWbemAsyncContext.Item("sinkname")
  If objwbemNamedValue.Value = "SubclassesOfAsync" Then
    MsgBox (objWbemObject.Path_.RelPath)
  End If
  Set objWbemObject = Nothing

Private Sub sink_OnCompleted(ByVal iHResult As WbemScripting.WbemErrorEnum, ByVal objWbemErrorObject As WbemScripting.ISWbemObject, ByVal objWbemAsyncContext As WbemScripting.ISWbemNamedValueSet)

    MsgBox "Asynchronous call complete"
End Sub

Visual Basic Scripting Edition Example

This example demonstrates asynchronous calls in scripts.

Dim service
Dim sink

Sub SINK_OnCompleted(iHResult, objErrorObject, objAsyncContext)
    WScript.Echo "Asynchronous operation is done."
End Sub

Sub SINK_OnObjectReady(objObject, objAsyncContext)
    WScript.Echo (objObject.Path_.RelPath)
End Sub

Set service = GetObject("winmgmts:")

Set sink = WScript.CreateObject("WbemScripting.SWbemSink","SINK_")

service.Security_.ImpersonationLevel = 3

service.SubclassesOfAsync sink, "Cim_ComputerSystem"

WScript.Echo "Waiting for subclasses."


SWbemServices.InstancesOfAsync Examples

Microsoft Visual Basic Example

Private Sub InstancesAsync_Click()
Set sink2 = New SWbemSink
Dim service As SWbemServices
Set service = GetObject("winmgmts:")

service.Security_.ImpersonationLevel = wbemImpersonationLevelImpersonate
service.InstancesOfAsync sink2, "WIN32_Process"

End Sub

Private Sub sink2_OnCompleted(ByVal iHResult As WbemScripting.WbemErrorEnum, ByVal objWbemErrorObject As
WbemScripting.ISWbemObject, ByVal objWbemAsyncContext As
WbemScripting.ISWbemNamedValueSet)
    MsgBox "Asynchronous operation is complete."
End Sub

Private Sub sink2_OnObjectReady(ByVal objWbemObject As
WbemScripting.ISWbemObject, ByVal objWbemAsyncContext As
WbemScripting.ISWbemNamedValueSet)

    MyListBox.AddItem (objWbemObject.Name) 'Put the name in a listbox
End Sub

Visual Basic Scripting Edition Example

Dim service
Dim sink

Sub SINK_OnCompleted(iHResult, objErrorObject, objAsyncContext)
    WScript.Echo "Asynchronous operation is done."
End Sub

Sub SINK_OnObjectReady(objObject, objAsyncContext)
    WScript.Echo (objObject.name)
End Sub

Set service = GetObject("WinMgmts:{impersonationLevel=impersonate}")

Set sink = WScript.CreateObject("WbemScripting.SWbemSink","SINK_")

service.instancesOfAsync sink, "WIN32_Process"

WScript.Echo "Waiting for instances."

JScript HTML Example

This sample illustrates the use of the WMI Scripting API within an HTML page, using JScript. It displays the names of the running processes using the asynchronous API. The WMI Scripting objects are instantiated using their CLSIDs and the HTML <OBJECT> tag.

<html>
<!-------------------------------------------------------------------

This sample illustrates the use of the WMI Scripting API within
an HTML page, using JScript.
-------------------------------------------------------------------->

<head>
<title>WMI Scripting HTML Sample - Processes (JScript asynchronous version)</title>

<script FOR="thesink" EVENT="OnCompleted(hResult, pErrorObject, pAsyncContext)" LANGUAGE="JScript">
    document.all.info.innerHTML = document.all.info.innerHTML + "COMPLETE!<BR>"
</script>

<script FOR="thesink" EVENT="OnObjectReady(objObject, objAsyncContext)" LANGUAGE="JScript">
    document.all.info.innerHTML = document.all.info.innerHTML + objObject.Name + "<BR>";
</script>

<script    FOR="document" EVENT="onclick()" LANGUAGE="JScript">
    document.all.info.innerHTML = "Processing....<BR>"
           var service = locator.ConnectServer();
    service.Security_.ImpersonationLevel=3;
    service.InstancesOfAsync(thesink, 'Win32_process');
</script>

</head>

<body>

<p>Click in this window to show the processes that are running:
<BR>
<FONT color=red>
<span ID="info">&nbsp;</span>.
</FONT>
<OBJECT classid=CLSID:76A64158-CB41-11D1-8B02-00600806D9B6 id=locator></OBJECT>
<OBJECT classid=CLSID:75718C9A-F029-11d1-A1AC-00C04FB6C223 id=thesink></OBJECT>
</p>
</body>
</html>


SWbemServices.Delete Examples

This example shows how to create, save, and delete a class.

Microsoft Visual Basic Example

Private Sub Delete_Click()

Dim services As SWbemServices
Dim objinstance As SWbemObject
Set services = GetObject("WinMgmts:{impersonationLevel=impersonate}")

   Set objinstance = services.get("")  'create a new class
   objinstance.Path_.Class = "mynewclass" ' Name the new class

   objinstance.Put_ ' save the new class
   services.Delete ("mynewclass") ' Delete this class

End Sub

Visual Basic Scripting Edition Example

Dim service

Set service = GetObject("winmgmts:{impersonationLevel=impersonate}")

Set objwbemobject= service.get("")

objwbemobject.Path_.Class = "MyNewClass"
objwbemobject.put_
service.delete  "MyNewClass"


SWbemServices.DeleteAsync Examples

Visual Basic Scripting Edition Example

Dim service
Dim sink

Sub SINK_OnCompleted(iHResult, objErrorObject, objAsyncContext)
    WScript.Echo "Asynchronous Delete is done."
End Sub

Sub SINK_OnObjectReady(objObject, objAsyncContext)
    WScript.Echo (objObject.name)
End Sub

Set service = GetObject("winmgmts:{impersonationLevel=impersonate}")

Set objwbemobject= service.get("")
Set sink = WScript.CreateObject("WbemScripting.SWbemSink","SINK_")

objwbemobject.Path_.Class = "MyNewClass"
objwbemobject.put_
service.deleteAsync Sink, "MyNewClass"

WScript.Echo "Waiting to delete."


SWbemServices.Security_ Examples

These examples show how to set the ImpersonationLevel, AuthenticationLevel, and Privileges properties of a security object. Notice that in the Visual Basic example, the Privileges property is set before the services object is created.

Microsoft Visual Basic Example

Dim Locator As New SWbemLocator
Dim services As SWbemServices
Locator.Security_.Privileges.Add wbemPrivilegeDebug, True
Set services = Locator.ConnectServer
services.Security_.ImpersonationLevel = wbemImpersonationLevelImpersonate
services.Security_.AuthenticationLevel = wbemAuthenticationLevelPkt

Visual Basic Scripting Edition Example

Dim service
Dim objwbemObjectSet
Dim instance

Set Service = GetObject("winmgmts:{impersonationLevel=impersonate, _
AuthenticationLevel=Pkt,(Debug)}")
set objwbemObjectSet = service.InstancesOf("Win32_LogicalDisk")

For each instance in objwbemObjectSet
     WScript.Echo (instance.name)
next


SWbemObject.ExecMethod_ Examples

These examples execute the CIM method "Create" of the class "Win32_Process". This method starts the "Calculator" program as a new process.

Microsoft Visual Basic Example

This example sets up the input parameters and then executes SWbemObject.ExecMethod_.

    Dim process As SWbemObject
    Dim method As SWbemMethod
    Dim inParam As SWbemObject
    Dim outParam As SWbemObject

    Set process = GetObject("winmgmts:{impersonationLevel=impersonate}!Win32_Process")

    Set method = process.Methods_("Create")
    Set inParam = method.inParameters.SpawnInstance_()
    inParam.CommandLine = "calc.exe"
    Set outParam = process.ExecMethod_("Create", inParam)

    If outParam.returnValue = 0 Then
        MsgBox ("Method executed successfully")
    Else
      MsgBox ("Method failed")
    End If

Visual Basic Scripting Edition Example

This is similar to the example above except that it executes the method directly without using SWbemObject.ExecMethod_.

On Error Resume Next

Set process = GetObject("winmgmts:{impersonationLevel=impersonate}"&_
                        "!Win32_Process")

If (process.Create("calc.exe", Null, Null, processid)) = 0 Then
    wscript.echo "method executed successfully"
Else
    wscript.echo "Method failed"
End If

If Err <> 0 Then
    WScript.echo Err.Description, "0x" & Hex(Err.Number)
End If

Win32Shutdown Method Example

The second example shows how to use the Win32Shutdown method of the Win32_OperatingSystem class. Unlike the previous example, this method must be executed on an instance of the class.

On Error Resume Next

Set os = _
GetObject("winmgmts:{impersonationLevel=impersonate,(Shutdown)}"& _
          "!/root/cimv2:Win32_OperatingSystem.Name=" & _
          """Microsoft Windows 2000 Professional|"& _
          "C:\\WINNT|\\Device\\Harddisk0\\Partition1""")

Ianswer = MsgBox("Shut Down Windows? -Warning- Save data first!", _
                  vbYesNoCancel, "Shut Down")
If Ianswer = 6 Then 'If Yes shut down
   Status = os.Win32Shutdown(5)

   If Err <> 0 Then
    wscript.echo Hex(Err.Number), Err.Description, Err.Source
   Else
       If outParam.returnValue = 0 Then
          wscript.echo ("Method executed successfully")
       Else
          wscript.echo ("Method failed")
       End If
   End If
Else

   wscript.echo "Operation canceled"

End If

Visual Basic Scripting Edition HTML Example

This sample illustrates the use of SWbemObject.ExecMethod_ within an HTML page, using VBScript. The WMI Scripting objects are created using their CLSIDs and the HTML <OBJECT> tag.

<html>

<!--------------------------------------------------------------------

This sample illustrates the use of SWbemObject.ExecMethod_

--------------------------------------------------------------------->

<head>
<title>WMI Scripting HTML Sample - Run Calculator (VBScript synchronous version)</title>
<script LANGUAGE="VBScript">
Sub window_onload()
    Set Service = Locator.ConnectServer()
    Service.Security_.ImpersonationLevel=3
    Set objinstance = service.get("Win32_Process")
    Set method = objinstance.Methods_("Create")
    Set inParam = method.InParameters.SpawnInstance_()
    inParam.CommandLine = "calc.exe"
    Set outParam = objinstance.ExecMethod_("Create", inParam)

    If outParam.returnValue = 0 Then
        document.all.info.innerHTML = "Executed successfully."
    Else
        document.all.info.innerHTML = "Failed!."
    End If
End Sub
</script>
</head>

<body>
<p>
The Method&nbsp;
<FONT color=red>
<span ID="info">&nbsp;</span>
</FONT>
<object ID="Locator" CLASSID="CLSID:76A64158-CB41-11D1-8B02-00600806D9B6"></object>
</p>
</body>
</html>


SWbemServices.ExecNotificationQuery Examples

This example demonstrates ExecNotificationQuery, the only semi-synchronous method in the scripting API.

Microsoft Visual Basic Example

This example will wait for 30 seconds for a Windows NT/Windows 2000 event to take place. If no event takes place within 30 seconds, it will display a message that there were no events.

Private Sub Enotification_Click()
Dim services As SWbemServices
Dim WbemEventSource As SWbemEventSource
Dim strQuery As String
Dim ObjEvent As SWbemObject

    On Error Resume Next
    Set services = GetObject("winmgmts:{impersonationLevel=impersonate}")
    strQuery = "SELECT * FROM __instancecreationevent " & _
               "WHERE TargetInstance ISA 'Win32_NTLogEvent'"

    Set WbemEventSource = services.ExecNotificationQuery(strQuery)
    Set ObjEvent = WbemEventSource.NextEvent(30000)  ' Wait 30 seconds

    If Err <> 0 Then
        If Err.Number = wbemErrTimedout Then      ' The call timed out
            MsgBox ("There were no events")
        Else
             MsgBox (Err.Number & " " & Err.Description)
        End If
    Else
        MsgBox (ObjEvent.TargetInstance.Message)   ' Display the event
    End If
    End Sub

Visual Basic Scripting Edition Example

This example is similar to the example above, but polls for events using SWbemEventSource.NextEvent and will wait indefinitely for a Windows NT/Windows 2000 event to take place. This program will stop waiting for events with some versions of Windows Scripting Host if you close the "waiting for events" dialog box. Newer versions of Windows Scripting Host will process the events after you click OK.

On Error Resume Next
Set events = GetObject("winmgmts:{impersonationLevel=impersonate}") _
                       .ExecNotificationQuery("SELECT * FROM "    & _
                       "__instancecreationevent WHERE "           & _
                       "targetinstance isa 'Win32_NTLogEvent'")

If Err <> 0 Then
    WScript.Echo Err.Description, Err.Number, Err.Source
End If

' Note this next call will wait indefinitely
' A timeout can be specified
' Events may be processed after you click OK
WScript.Echo "Waiting for events..."

Do
    Set NTEvent = events.NextEvent
    If Err <> 0 Then
        WScript.Echo Err.Number, Err.Description, Err.Source
        Exit Do
    Else
        WScript.Echo NTEvent.TargetInstance.Message
        Exit Do
    End If
Loop

WScript.Echo "finished"


SWbemServices.ExecNotificationQueryAsync Examples

Microsoft Visual Basic Example

Dim WithEvents sink As SWbemSink

Private Sub ExecNoteAsync_Click()

    Dim services As SWbemServices
    Dim strQuery As String
    Dim cntxt As SWbemNamedValueSet
    Set sink = New SWbemSink
    Set services = GetObject("winmgmts:{impersonationLevel=impersonate}")
    strQuery = "SELECT * FROM __InstanceCreationEvent "& _
                "WHERE targetinstance ISA 'Win32_NTLogEvent'"
    Set cntxt = New SWbemNamedValueSet
    cntxt.Add "sinkname", "ExecNoteAsync"
    services.ExecNotificationQueryAsync sink, strQuery, , , , cntxt
    MsgBox "This program will asynchronously process NTLogEvent events."

End Sub

Private Sub sink_OnObjectReady(ByVal objWbemObject As WbemScripting.ISWbemObject, ByVal objWbemAsyncContext As WbemScripting.ISWbemNamedValueSet)
  On Error GoTo ErrorHandler
    Dim cntxt_item As WbemScripting.SWbemNamedValue

    Set cntxt_item = objWbemAsyncContext.Item("sinkname")

    If cntxt_item.Value = "ExecNoteAsync" Then
        MsgBox " Got event: " & objWbemObject.TargetInstance.Message
    End If

    Set objWbemObject = Nothing

    Exit Sub                                   ' Exit to avoid handler

ErrorHandler:
    MsgBox "Error number: " & Str(Err.Number) & vbNewLine & "Description: " & Err.Description, vbCritical
End Sub

Visual Basic Scripting Edition Example

This example will wait indefinitely for a Windows NT/Windows 2000 event to take place. You can run this program in the background and a message will appear when there is an event. Note that if you close the "Waiting for events" dialog box, the program will stop waiting for events.

Sub SINK_OnObjectReady(objObject, objAsyncContext)
    WScript.Echo (objObject.TargetInstance.Message)
End Sub

Set services = GetObject("WinMgmts:{ImpersonationLevel=impersonate,AuthenticationLevel=Pkt}")

Set sink = WScript.CreateObject("WbemScripting.SWbemSink","SINK_")

services.ExecNotificationQueryAsync sink, _
"select * from __instancecreationevent where targetinstance isa 'Win32_NTLogEvent'"

WScript.Echo "Waiting for events"


SWbemServices.Get and SWbemObject.Put_ Examples

Microsoft Visual Basic Example

Private Sub get_Click()
   Set service = GetObject("winmgmts:{impersonationLevel=impersonate}")
    Set objinstance = service.get("")
    objinstance.Path_.Class = "mynewclass"
    objinstance.Put_
    MsgBox ("The object name is :" & objinstance.Path_.RelPath)
End Sub

Visual Basic Scripting Edition HTML Example

This sample illustrates the use of SWbemObject.Put_ within an HTML page, using Visual Basic Scripting Edition. This sample adds a new class called mynewclass and saves it using the SWbemObject.Put_ method. The class name is displayed on the page from the path_.relpath property. The WMI Scripting objects are instantiated using their CLSIDs and the HTML <OBJECT> tag

<html>
<!------------------------------------------------------------------
 This sample illustrates the use of the WMI Scripting API within
 an HTML page, using VBScript.
-------------------------------------------------------------------->

<head>
<title>WMI Scripting HTML Sample - Add a new class (VBScript synchronous version)</title>
<script LANGUAGE="VBScript">
Sub window_onload
Set Service = Locator.ConnectServer()
Service.Security_.ImpersonationLevel=3

Set objinstance = service.get("")
        objinstance.Path_.Class = "mynewclass"
        objinstance.Put_

document.all.info.innerText = objinstance.Path_.RelPath

end sub
</script>
</head>

<body>

<p>The name of the new class is <span ID="info">unknown </span>.
<object ID="Locator" CLASSID="CLSID:76A64158-CB41-11D1-8B02-00600806D9B6">
</object>
</p>
</body>
</html>


ASP Examples

JScript ASP Example

This sample illustrates the use of the WMI Scripting API within an ASP, using JScript. It displays information in a table for each disk on the local host.

To run this sample

  1. Place it in a directory accessible to your Web server
  2. Ensure that the registry value: HKEY_LOCAL_MACHINE\Software\Microsoft\WBEM\Scripting\Enable for ASP is set to 1.
<%@ LANGUAGE="JSCRIPT"%>
<html>
<!-------------------------------------------------------------------------
This sample displays information in a table
for each disk on the local host.
---------------------------------------------------------------------------->

<head>
<title>WMI Scripting ASP Sample - Disk Information (JScript Version)</title>
</head>

<body>
<%
    // Connect to the default namespace (root/cimv2)
    // on the local host
    var Locator = new ActiveXObject ("WbemScripting.SWbemLocator");
    var Service = Locator.connectserver ();

    // Retrieve the logical disk class
    var Disk = Service.Get ("Win32_LogicalDisk");
    var Path = Disk.Path_;

    // Enable impersonation before we retrieve
    // the Disk instances otherwise access will
    // be denied
    Disk.Security_.impersonationLevel = 3;
    var Disks = new Enumerator (Disk.Instances_());
%>

<p>Path of object is <%=Path.DisplayName%></p>

<table BORDER="1">
  <tr>
    <th>Name</th>
    <th>Volume Name</th>
    <th>Volume Serial Number</th>
  </tr>
<%
    for (;!Disks.atEnd ();Disks.moveNext ())
    {
        var DiskInstance = Disks.item();
%>
  <tr>
    <td><%=DiskInstance.Name%>
</td>
    <td><%=DiskInstance.VolumeName%>
</td>
    <td><%=DiskInstance.VolumeSerialNumber%>
</td>
  </tr>
<%
    }
%>
</table>
</body>
</html>

VBScript ASP Example

This sample illustrates the use of the WMI Scripting API within an ASP, using VBScript. It displays information in a table for each disk on the local host.

To run this sample

  1. Place it in a directory accessible to your Web server
  2. Ensure that the registry value: HKEY_LOCAL_MACHINE\Software\Microsoft\WBEM\Scripting\Enable for ASP is set to 1.
<%@ LANGUAGE="VBSCRIPT"%>
<html>
<!---------------------------------------------------------
 This sample displays information in a table
for each disk on the local host.

---------------------------------------------------------->

<head>
<title>WMI Scripting ASP Sample - Disk Information (VBScript version)</title>
</head>

<body>
<%
    on error resume next

    ' Connect to the default namespace (root/cimv2)
    ' on the local host
    Set Locator = CreateObject("WbemScripting.SWbemLocator")
    Set Service = locator.connectserver

    if Err = 0 then

        'Retrieve the logical disk class
        Set Disk = Service.Get ("Win32_LogicalDisk")
        Set Path = Disk.Path_

        ' Enable impersonation before we retrieve
        ' the Disk instances otherwise access will
        ' be denied
        Disk.Security_.impersonationLevel = 3
        Set Disks = Disk.Instances_
%>

<p>Path of object is <%=Path.DisplayName%></p>

<table BORDER="1">
  <tr>
    <th>Name</th>
    <th>Volume Name</th>
    <th>Volume Serial Number</th>
  </tr>
<%
    for each DiskInstance in Disks
%>
  <tr>
    <td><%=DiskInstance.Name%>
</td>
    <td><%=DiskInstance.VolumeName%>
</td>
    <td><%=DiskInstance.VolumeSerialNumber%>
</td>
  </tr>
<%
        Next
%>
</table>
<%
    Else
%>

<table>
  <tr>
    <td>Error - <%=Err.description%>, <%=Err.number%>, <%=Err.Source%></td>
  </tr>
</table>
<%
    End If
%>
</body>
</html>


WMI Scripting Reference

The Windows Management Instrumentation (WMI) reference for scripting provides the definitions for the scripting API for WMI. This reference provides information for developers who are writing applications using Microsoft® Visual Basic®, Visual Basic for Applications, Visual Basic Scripting Edition (VBScript), and Microsoft® JScript®.

The following table describes WMI objects and how they are used.

Object | Description
SWbemEventSource | Used to retrieve events in conjunction with SWbemServices.ExecNotificationQuery.
SWbemLastError | Used to provide extended error information when there is an error.
SWbemLocator | Used to obtain an SWbemServices object that can access WMI on a particular host machine.
SWbemMethod | Used to contain a single Common Information Model (CIM) method definition.
SWbemMethodSet | Used to access a collection of objects of type SWbemMethod.
SWbemNamedValue | Used to contain a single named value.
SWbemNamedValueSet | Used to access a collection of objects of type SWbemNamedValue items.
SWbemObject | Used to contain and manipulate a single CIM object class or instance.
SWbemObjectPath | Used to generate and validate an object path.
SWbemObjectSet | Used to access a collection of objects of type SWbemObject.
SWbemPrivilege | Used to set or clear a privilege.
SWbemPrivilegeSet | Used to access a collection of objects of type SWbemPrivilege.
SWbemProperty | Used to contain a single CIM property.
SWbemPropertySet | Used to access a collection of objects of type SWbemProperty.
SWbemQualifier | Used to contain a single CIM qualifier.
SWbemQualifierSet | Used to access a collection of objects of type SWbemQualifier.
SWbemSecurity | Used to manage security settings such as Distributed Component Object Model (DCOM) Privilege, AuthenticationLevel, and ImpersonationLevel.
SWbemServices | Used to create, update, and retrieve instances or classes.
SWbemSink | Used by client applications to receive the results of asynchronous operations and event notifications.


WMI ADSI Extension

[This is preliminary documentation and subject to change.]

The Windows Management Instrumentation (WMI) Active Directory Service Interface extension extends computer objects exposed by the Microsoft® Active Directory™ Service Interfaces (ADSI). The WMI extension only extends computer objects found in the LDAP namespace on Microsoft® Windows® 2000 computers.

The extension adds properties and methods to ADSI computer objects. You can use these properties and methods to identify these computer objects in WMI. You can then use WMI to manage the computer objects.

Note that as an alternative to using ADSI and this extension, you can use the WMI Directory Services Provider to manage the Active Directory.

For information on ADSI extensions, see the Active Directory SDK documentation on the Microsoft Developer Network (MSDN™) Web site at http://msdn.microsoft.com.

The WMI ADSI extension documentation contains the following sections:

  • About the WMI ADSI Extension
  • Using the WMI ADSI Extension


About the WMI ADSI Extension

[This is preliminary documentation and subject to change.]

You can use Microsoft® Active Directory™ Service Interfaces (ADSI) to perform queries to find computer objects contained in the Active Directory. Before you can use WMI to manage those computer objects, the Directory Service (DS) computer object name must be converted into an object path that WMI can use. The WMI ADSI extension does this for you. The WMI ADSI extension maps DS Computer class objects to WMI Win32_ComputerSystem class objects.

The WMI ADSI extension is exposed through the IWMIExtension interface. This interface contains the object path, a method that returns the WMI computer object, and a method that returns the service's interface. You can use the service's interface to perform other WMI operations. For more information on how to use the WMI ADSI extension exposed through this interface, see Using the WMI ADSI Extension.


Using the WMI ADSI Extension

[This is preliminary documentation and subject to change.]

The Windows Management Instrumentation (WMI) Active Directory Service Interfaces (ADSI) extension is useful when you are locating objects in the Microsoft® Active Directory™ and using the search results to manage objects in WMI. A typical use of the extension would be applying changes across all computers in an organizational unit.

The WMI ADSI extension is self-registering. It registers itself according to ADSI extension rules that extend the computer objects in the LDAP ADSI namespace.

This section contains information on the following topics:

  • Getting an Object with GetWMIObject
  • Getting a Service with GetWMIServices
  • Getting the WMI Object Path


Getting an Object with GetWMIObject

[This is preliminary documentation and subject to change.]

The GetWMIObject method returns the Win32_ComputerSystem instance identified by the DS computer object. You can then use this object to call its methods or to perform read and write operations on its properties.

The following examples show how to call GetWMIObject. In both examples you must replace the bracketed information found in the Active Directory query with your own information. For example, if the name of your computer is MYCOMPUTER, you would replace CN=<computer name> with CN=MYCOMPUTER.

The following example uses Microsoft® Visual Basic® to call the GetWMIObject method:

Dim ADSObject As IADs
Dim WMIObject As SWbemObject

' Query Active Directory for your computer.
Set ADSObject = GetObject("LDAP://CN=<computer name>,CN=Computers,DC=<domain>,DC=<company>,DC=com")

Set WMIObject = ADSObject.GetWMIObject
Debug.Print "Status=" + WMIObject.Status

The following example uses Microsoft® Visual C++® to call the GetWMIObject method:

    IADs            *pComputer = NULL;
    IWMIExtension   *pWMI = NULL;
    ISWbemObject    *pObj = NULL;

    wchar_t Obj[80] = L"LDAP://CN=<computer name,CN=Computers,DC=<domain>,DC=<company>,DC=com";

    CoInitialize (NULL);

    //Query Active Directory to get your computer.
    HRESULT hRes = ADsGetObject( Obj, IID_IADs, (void**)&pComputer );

    //Get the WMI ADSI extension interface on this object.
    hRes = pComputer->QueryInterface ( IID_IWMIExtension, (void**)&pWMI );

    //Use the extension to get the WMI object.
    hRes = pWMI->GetWMIObject(&pObj);

    //Print the object
    BSTR strObjText;
    hRes = pObj->GetObjectText_(0, &strObjText);
    wprintf(L"%s\n", strObjText);
    SysFreeString(strObjText);

    //Cleanup
    pObj->Release();
    pWMI->Release();
    pComputer->Release();


Getting a Service with GetWMIServices

[This is preliminary documentation and subject to change.]

The GetWMIServices method returns a WMI services object for the cimv2 namespace. You can then use this object to get other objects in the namespace, execute methods, and invoke WMI queries.

The following examples show how to call GetWMIServices. In both examples you must replace the bracketed information found in the Active Directory query with your own information. For example, if the name of your computer is MYCOMPUTER, you would replace CN=<computer name> with CN=MYCOMPUTER.

The following example uses Microsoft® Visual Basic® to call the GetWMIServices method:

Dim ADSObject   As IADs
Dim WMIServices As SWbemServices
Dim WMIObject   As SWbemObject

' Query Active Directory for your computer.
Set ADSObject = GetObject("LDAP://CN=<computer name>,CN=Computers,DC=<domain>,DC=<company>,DC=com")

Set WMIServices = ADSObject.GetWMIServices
Set WMIObject = WMIServices.Get("Win32_LogicalDisk.DeviceID=""C:""")

Debug.Print "FileSystem=" + WMIObject.FileSystem

The following example uses Microsoft® Visual C++® to call the GetWMIServices method:

    IADs            *pComputer = NULL;
    IWMIExtension   *pWMI = NULL;
    ISWbemServices  *pSvc = NULL;
    ISWbemObject    *pObj = NULL;

    wchar_t Obj[80] = L"LDAP://CN=<computer name,CN=Computers,DC=<domain>,DC=<company>,DC=com";

    CoInitialize (NULL);

    //Query Active Directory to get your computer.
    HRESULT hRes = ADsGetObject( Obj, IID_IADs, (void**)&pComputer );

    //Get the WMI ADSI extension interface on this object.
    hRes = pComputer->QueryInterface ( IID_IWMIExtension, (void**)&pWMI );

    //Use the extension to get a WMI services object.
    hRes = pWMI->GetWMIServices(&pSvc);

    BSTR  strObjPath = SysAllocString(L"Win32_LogicalDisk.DeviceID=\"C:\"");
    hRes = pSvc->Get(strObjPath, NULL, NULL, &pObj);
    SysFreeString(strObjPath);

    //Print the object
    BSTR strObjText = NULL;
    hRes = pObj->GetObjectText_(0, &strObjText);
    wprintf(L"%s\n", strObjText);
    SysFreeString(strObjText);

    //Cleanup
    pObj->Release();
    pSvc->Release();
    pWMI->Release();
    pComputer->Release();


Getting the WMI Object Path

[This is preliminary documentation and subject to change.]

The WMIObjectPath property contains a moniker that is the object path to the WMI computer object. The WMI extension sets the property value when the ADSI object is instantiated (for Visual Basic users) or when you query the DS object for the IWMIExtension interface (for C users). The following moniker is an example of a WMI object path for a computer object named MYCOMPUTER:

"WINMGMT:{impersonationLevel=impersonate}!//MYCOMPUTER/root/cimv2:Win32_ComputerSystem.Name='MYCOMPUTER'".

The following examples display the WMIObjectPath property value. In both examples you must replace the bracketed information found in the Active Directory query with your own information. For example, if the name of your computer is MYCOMPUTER, you would replace CN=<computer name> with CN=MYCOMPUTER.

The following example uses Microsoft® Visual Basic® to display the WMIObjectPath property:

Dim ADSObject   As IADs

' Query Active Directory for your computer.
Set ADSObject = GetObject("LDAP://CN=<computer name>,CN=Computers,DC=<domain>,DC=<company>,DC=com")

Debug.Print "WMI Object Path: " + ADSObject.WMIObjectPath

The following example uses Microsoft® Visual C++® to display the WMIObjectPath property:

    IADs            *pComputer = NULL;
    IWMIExtension   *pWMI = NULL;

    wchar_t Obj[80] = L"LDAP://CN=<computer name,CN=Computers,DC=<domain>,DC=<company>,DC=com";

    CoInitialize (NULL);

    //Query Active Directory to get your computer.
    HRESULT hRes = ADsGetObject( Obj, IID_IADs, (void**)&pComputer );

    //Get the WMI ADSI extension interface on this object.
    hRes = pComputer->QueryInterface ( IID_IWMIExtension, (void**)&pWMI );

    //Use the get_function of WMIObjectPath to get the property value
    //from WMIObjectPath.
    BSTR  strObjectPath;
    hRes = pWMI->get_WMIObjectPath(&strObjectPath);
    wprintf(L"WMIObjectPath: %s\n", strObjectPath);
    SysFreeString(strObjectPath);

    //Cleanup
    pWMI->Release();
    pComputer->Release();


Programming Basics for WMI Applications

Windows Management Instrumentation (WMI) applications are standard executable files (.exe files) and Microsoft® Windows NT®/Microsoft® Windows® 2000 services that use information supplied by a provider or by WMI. WMI applications make requests for information or services through the WMI application programming interface (API), either directly or indirectly, using access methods. For example, a Web browser can be written using the Microsoft® ActiveX® controls that are supplied with the WMI software development kit (SDK) to display information about one or more managed objects. An inventory application can use the Open Database Connectivity (ODBC) driver to access a database containing management data for a local network.

All WMI applications share many of the same tasks. Some of the most common tasks that all WMI applications share include:

  • Using the methods of the IUnknown interface.
  • Working with output parameters.
  • Connecting a client application to WMI.
  • Handling errors.
  • Installing providers.
  • Making asynchronous calls.
  • Making semisynchronous calls.

In addition, many WMI applications perform other tasks depending on their feature set. Optional application tasks include:

  • Creating namespaces.
  • Creating base classes.
  • Creating derived classes.
  • Creating instances.
  • Deleting instances.
  • Using queries.
  • Enumerating objects.
  • Calling methods.
  • Retrieving class definitions.
  • Updating instances.
  • Moving instances.


IUnknown Interface Basics

The IUnknown interface is the base interface for all Component Object Model (COM) interfaces exposed by COM objects. The COM objects implemented by Windows Management Instrumentation (WMI), WMI providers, and event consumers expose one or more interfaces specified in the WMI API. For example, WMI class providers implement a COM object that includes the IWbemProviderInit and IWbemServices interfaces.

IUnknown manages the lifespan of the COM object and handles client requests for access. To manage the COM object's lifespan, IUnknown maintains what is known as a reference count. The reference count is a tally of the number of active clients of a particular interface. Only when all of the reference counts for all of the interfaces exposed by a COM object reach zero can the object be deleted and its memory safely freed. The methods that support lifespan management are:

  • AddRef
  • Release

The third method of IUnknown, QueryInterface, is used to handle client access to COM objects. Clients gain access to a COM object by retrieving a pointer to one of the interfaces implemented by the object. To gain access to a particular interface, a client calls QueryInterface and sets the riid parameter to the identifier of the desired interface.

If this interface is not implemented by the COM object, QueryInterface returns the error code E_NOINTERFACE. If the interface is implemented by the object, QueryInterface calls AddRef to increment the reference count and returns a pointer to the interface in the ppv parameter.

Whenever a calling application receives an interface pointer as an output parameter to a method, the calling application must call the interface's AddRef method before calling any of the other methods, unless otherwise noted. Receiving an interface pointer through QueryInterface is an exception to this rule because QueryInterface automatically calls AddRef as part of its implementation.

Whenever a user of an interface is finished with that interface, it must call Release.

Because that AddRef and Release are not required to return accurate values, applications that call these methods should not use the return values to determine whether the COM object is still valid, except in certain debugging situations where the behavior of the threads is under control. Due to the concurrent use of objects by multiple threads, the reference count can easily be altered while it is being examined.


Output Parameter Basics

Windows Management Instrumentation (WMI) observes the standard Component Object Model (COM) rules for passing input and output parameters. Observing the rules for output parameters is especially important because failing to observe them can result in memory leaks and unpredictable behavior.

If a method returns an interface pointer to its caller in an output parameter, it is the caller's responsibility to release the pointer when it is no longer needed. This is done by using the pointer to call the Release method. Because the Release method is part of the IUnknown interface and every interface in the WMI API derives from IUnknown, the Release method is universally available for interface pointers.

For example, if an application calls the IWbemClassObject::GetPropertyQualifierSet method, a pointer to the IWbemQualifierSet interface is passed in the contents of the ppQualSet output parameter. The pointer can be released by calling IWbemQualifierSet::Release as is shown in the following sample:

IWbemQualifierSet* pSet;
pObject->GetPropertyQualifierSet(strPropName, &pSet);

// Use the pointer to manipulate qualifiers.
if(pSet != NULL)
{
  // Release the pointer to the IWbemQualifierSet interface.

  pSet->Release();      // Don't use pSet anymore!
  }

If an interface pointer is returned in an output parameter through the QueryInterface method, a call to the IUnknown::AddRef method has been made implicitly. The recipient of the interface pointer should not make an additional AddRef call. A call to IUnknown::Release must be made when the interface pointer is no longer needed, regardless of how the pointer was obtained. If a method that would have returned an interface pointer returns an error code, the original value of the parameter is not altered in any way. That is, it is not set to NULL because of an error.

If an output parameter of type VARIANT is received, the recipient must eventually call the Automation function VariantClear on the returned parameter. The parameter of the type VARIANT should not have an initial value prior to this call. This can be achieved by initializing a new VARIANT with the Automation function VariantInit or by clearing a previous VARIANT with VariantClear. If the method that would have returned a parameter of the type VARIANT returns an error, the original value of the parameter of the type VARIANT is not altered. It is not set to NULL because of an error.

Always call VariantInit to initialize a parameter of the type VARIANT. When finished using VARIANT data that is returned by a method, call VariantClear.

If an output parameter of type BSTR is received, the recipient must eventually call the Automation function SysFreeString on the returned string. The BSTR parameter should not have an initial value prior to the call; it should be set to point to NULL. Alternately, a previously active BSTR variable may be reused after a call to SysFreeString to de-allocate the memory it is currently using. SysFreeString must never be called on a pointer with a random value. If a method that would have returned a BSTR output parameter returns an error code, then the original contents of the string pointer is left unmodified. It is not set to point to NULL.


Installing a Provider

An application installs a provider by registering the classes that the provider supports and by registering the provider itself. Providers typically supply one or more Managed Object Format (MOF) files that contain relevant classes. Applications must place these MOF files in a local directory and run the MOF compiler (Mofcomp.exe) to compile them. For information about running the MOF compiler, see MOF Compiler.

Once installed, a provider cannot be changed dynamically. Windows Management Instrumentation (WMI) must be restarted for such a change to take effect. For example, suppose an instance provider called EmailProvider has been installed to supply instances of the class EmailClass. An application can issue the following query to receive instances of EmailClass:

select * from EmailClass

If an application subsequently replaces the provider either by updating the class identifier (CLSID) property in EmailProvider's registered instance of the __Win32Provider system class or by changing the DLL to which the CLSID is pointing in the registry, no change takes effect until WMI is terminated and restarted.

For information about provider registration, see Registering a Provider.


Connecting a Client Application to WMI

Before a client application can issue requests using the Windows Management Instrumentation (WMI) API, it must successfully connect to WMI. To begin the connection process, an application makes calls to the Component Object Model (COM) functions CoInitializeEx and CoInitializeSecurity. Then COM function CoCreateInstance is used to retrieve a pointer to the IWbemLocator interface. With this pointer, an application calls the IWbemLocator::ConnectServer method to connect to WMI.

The following code fragment that shows the connection process can become the basis of many simple WMI-based applications:

int main(int argc, char **argv)
{
   HRESULT hres;
   hres =  CoInitializeEx(0, COINIT_MULTITHREADED); // Initialize COM.
  if (FAILED(hres))
  {
     printf("Failed to initialize COM library\n");
     return 1;                  // Program has failed.
  }

   hres =  CoInitializeSecurity(NULL, -1, NULL, NULL,
        RPC_C_AUTHN_LEVEL_CONNECT,
        RPC_C_IMP_LEVEL_IDENTIFY,
        NULL, EOAC_NONE, 0
        );

  if (FAILED(hres))
  {
     printf("Failed to initializesecurity\n");
     CoUninitialize();
     return 1;                  // Program has failed.
  }
    IWbemLocator *pLoc = 0;

    hres = CoCreateInstance(CLSID_WbemLocator, 0,
        CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *) &pLoc);

    if (FAILED(hres))
    {
        printf("Failed to create IWbemLocator object.\n");
        CoUninitialize();
        return 1;     // Program has failed.
    }

    IWbemServices *pSvc = 0;

    // Connect to the Root\Default namespace with the current user.
    hRes = pLoc->ConnectServer(
            _bstr_t(L"ROOT\\DEFAULT"),
            NULL,
            NULL,
            0,
            NULL,
            0,
            0,
            &pSvc
            );

    if FAILED(hres))
    {
        printf("Could not connect. Error code = 0x%X\n", hRes);
        CoUninitialize();
        return 1;      // Program has failed.
    }

    printf("Connected to WMI\n");

    // Set the proxy so that impersonation of the client occurs.
    CoSetProxyBlanket(pSvc,
       RPC_C_AUTHN_WINNT,
       RPC_C_AUTHZ_NONE,
       NULL,
       RPC_C_AUTHN_LEVEL_CALL,
       RPC_C_IMP_LEVEL_IMPERSONATE,
       NULL,
       EOAC_NONE
       );

// Use the IWbemServices pointer to make requests of WMI.
// …

    // Cleanup
    // ========

    pSvc->Release();
    pLoc->Release();
    CoUninitialize();

    return 0;   // Program successfully completed.
}

Note When connecting to WMI on a remote Microsoft® Windows® 95 system from a Microsoft® Windows NT®/Windows 2000 system, there are two issues to consider:

  • If the local system is supplying credentials (your user name and password) to a domain that it is not a member of, you may notice that synchronous enumerations and queries may take much longer to process.
  • If you provide credentials in the process of connecting to WMI, the logon process fails and you get an error indicating the RPC server is unavailable.


Setting Security in Applications

Some Windows Management Instrumentation (WMI) clients may have to adjust Distributed Component Object Model (DCOM) security settings to allow WMI to make calls to their interface methods and to be able to use remote interface pointers. In particular, this affects applications that communicate remotely with WMI on a Microsoft® Windows® 95/98 computer using share-level security, applications that receive the results of an operation asynchronously, and clients that specify the identity of a specific user.

Remoted asynchronous client calls into WMI often specify a callback function. These callbacks are not subject to client DCOM security settings. WMI clients can specify that they require operations to be authenticated or encrypted when calling into WMI by using standard DCOM procedures, such as IClientSecurity. However, clients should be aware that when the requested operation is to be performed asynchronously, only the request is subject to the specified security settings. The asynchronous responses to the request will not be affected by the requested settings.

For example one can specify that IWbemServices.GetObject("MyBankBalance") and its response use encryption over the wire, but one cannot specify that the responses to IWbemServices.GetObjectAsync("MyBankBalance") use encryption.

Applications can configure DCOM at the process level and at the interface level.

For more information about WMI security, see Security and Authentication.


Setting Process Level Security

Applications that export interfaces for WMI to call may set process level security. The following two types of applications fall in this category:

  • Applications that make asynchronous calls
  • Applications that register as event consumers

By default, a client requires at least "connect" level authentication (RPC_AUTHN_LEVEL_CONNECT). However, because WMI runs under the LocalSystem account and does not have a network identity, it fails when it tries to make calls to an application's remote interface.

There are two solutions for this problem. The first and only solution for a client implemented as a DLL is to implement its sink in a separate process. For information about this solution and using the IUnsecuredApartment interface, see Security Considerations with Asynchronous Calls.

The second and easier choice for applications implemented as executable files (.exe files) is to lower the authentication level required. This can be done by making either of the following two calls immediately after the call to the COM function CoInitializeEx:

  • A call to the COM function CoInitializeSecurity:
    HRESULT hr = CoInitialize(NULL);
hr = CoInitializeSecurity(NULL, -1, NULL, NULL,
       RPC_C_AUTHN_LEVEL_NONE, RPC_C_IMP_LEVEL_IMPERSONATE,
       NULL, EOAC_NONE, 0);
  • A call to the WMI SDK helper function InitializeSecurity:
    HRESULT hr = CoInitialize(NULL);
hr = InitializeSecurity(RPC_C_AUTHN_LEVEL_NONE, RPC_C_IMP_LEVEL_IMPERSONATE);

Note You can call InitializeSecurity with any of the authentication and impersonation levels that are available to CoInitializeSecurity.


Setting Interface Level Security

Client applications connect to WMI using an identity. An initial identity is established when an application calls the IWbemLocator::ConnectServer method to connect to WMI and obtain the pointer to the IWbemServices interface. This identity is based on the values specified in the user, password, and authority parameters to the call. All three of these parameters can be NULL to indicate the currently logged-on user, or non-NULL to indicate a specific user and domain. As a convenience, ConnectServer allows the user name to be of the form "domain\user".

When the application uses the IWbemServices pointer returned from ConnectServer to retrieve a new out-of-process pointer, by default this pointer has the identity of the current process and not the identity of the IWbemServices pointer. The result can be an access-denied error code, such as E_ACCESSDENIED. To avoid the error, applications must set the identity to be used with the new pointer.

For example, the IWbemServices::CreateInstanceEnum method returns a pointer to the IEnumWbemClassObject interface for enumerating instances. If an identity was sent to ConnectServer, then that must also be done for the IEnumWbemClassObject interface. The following out-of-process interfaces are affected:

  • IEnumWbemClassObject
  • IWbemCallResult
  • IWbemServices

When WMI is running on a remote Windows 95/98 computer that has share-level security, the default authentication levels are too high, causing remote calls to fail.

To determine if a Windows 95/98 computer is using share-level security

  1. Right-click on the Network Neighborhood icon.
  2. Click Properties.
  3. Click the Access Control tab.

Either the COM function CoSetProxyBlanket or the WMI SDK helper function SetInterfaceSecurity can be used to prevent this situation and to set interface security appropriately.

ConnectServer automatically lowers the authentication level of the IWbemServices interface pointer. You can use a helper function, IsAuthenticated, to determine if the level was lowered.

The following pseudocode shows how to set interface security using the SDK helper functions SetInterfaceSecurity and IsAuthenticated. Because source code for these helper functions is supplied with the WMI SDK, they can be used as a guide should you want to call the COM functions directly.

HRESULT hr = CoInitialize(NULL);
hr = InitializeSecurity(false);       // Lower authentication level.

IWbemServices  pServices = NULL;
IEnumWbemClassObject pEnum = NULL;
pLocator->ConnectServer(bstrNamespace, bstrUser, bstrPassword, NULL,
    0, bstrAuthority, NULL, &pServices);

// Determine if the call is to a share-level box.
// IsAuthenticated returns false for a share-level box.

bool bAuthenticated = IsAuthenticated(pServices);
pServices->CreateClassEnum(NULL, 0, NULL, &pEnum);

// Either set the identity to what was passed to ConnectServer or
// lower the value.

SetInterfaceSecurity(pEnum, bstrUser, bstrPassword, bstrAuthority,
    bAuthenticated);

// Now the pEnum pointer is ready to use.

Note The source code for SetInterfaceSecurity and IsAuthenticated can be found in the \Samples\Vc\Utillib subdirectory of the WMI SDK installation. To use these functions, include the Wbemsec.h header file and add the Wbemsec.cpp file to the project.


Error Handling for Applications

When an error occurs with Windows Management Instrumentation (WMI), WMI sends error messages to the Microsoft® Windows NT®/Microsoft® Windows® 2000 Event Log service. Windows NT/Windows 2000 applications should check these event logs to help determine the cause of the error.

Errors that applications receive from WMI API method calls can be either specific to WMI or to the Distributed Component Object Model (DCOM). For example, when a remote connection fails, a method returns DCOM-specific error codes. The DCOM rule is that if the most significant bit is set, the code is an error; otherwise, it is a status code. For example, the DCOM error code 0x800706BA, or "Server Unavailable," is common if the connection to the remote computer is lost during a remote method call. DCOM-specific errors can be returned from any WMI interface except IWbemContext, IWbemClassObject, and IWbemQualifierSet.

Client applications must follow COM rules when checking status and error return codes. Applications that are clients of WMI can retrieve error information about operations completed with any of the asynchronous IWbemServices methods or methods from any of the other interfaces in the WMI API.

To access the error information, applications can call the COM function GetErrorInfo immediately after an error is indicated by an interface method, including by any of the IWbemCallResult methods called during the processing of a semisynchronous call. GetErrorInfo returns an error information object, a COM object that supports the IErrorInfo interface. To examine this object, an application needs to call the IErrorInfo::QueryInterface method and specify IID_IWbemClassObject for the riid parameter. QueryInterface returns an instance of a WMI class, typically __ExtendedStatus.

If errors occur during the processing of an asynchronous operation, the error information object is delivered with the IWbemObjectSink::SetStatus method. This object cannot be delivered through GetErrorInfo because there is no way to know when, or on which thread, such an asynchronous call is made.

The error handling code in a client application should look something like the following sample:

HRESULT hRes = SomeMethod;

// Check for specific error and/or status codes.
if (hRes == WBEM_E_NOT_FOUND)
{
// Processing to handle specific error code
}
else if hRes == WBEM_S_DUPLICATE_OBJECTS
{
// Processing to handle specific success code
}
else if (FAILED(hRes))
{
// All other cases, including errors specific to DCOM
}

// Otherwise, the call succeeded.


Making an Asynchronous Call

Making an asynchronous call can increase the performance of a management application by allowing it to proceed with other tasks while requests are pending and results are delivered through another thread. Windows Management Instrumentation (WMI) applications can make asynchronous calls using many of the methods of the IWbemServices interface. The IWbemServices interface supports both the synchronous and asynchronous versions of several methods. Applications can recognize the asynchronous version of an IWbemServices method by the appearance of the Async suffix in its name, as shown in the following table.

Operation | Synchronous method | Asynchronous method
Enumerating classes | CreateClassEnum | CreateClassEnumAsync
Enumerating instances | CreateInstanceEnum | CreateInstanceEnumAsync
Deleting classes | DeleteClass | DeleteClassAsync
Deleting instances | DeleteInstance | DeleteInstanceAsync
Calling a method | ExecMethod | ExecMethodAsync
Registering for events | ExecNotificationQuery | ExecNotificationQueryAsync
Issuing a query | ExecQuery | ExecQueryAsync
Retrieving a class definition or instance | GetObject | GetObjectAsync
Updating a class | PutClass | PutClassAsync
Updating an instance | PutInstance | PutInstanceAsync

When an application calls an asynchronous method, the method returns immediately with the WBEM_S_NO_ERROR success code. The application can proceed with other tasks while waiting for the operation to complete. WMI reports back to the application by calling methods in the application's IWbemObjectSink interface implementation. All applications that make asynchronous calls must implement the IWbemObjectSink interface. Temporary event consumers also implement IWbemObjectSink to receive notifications of events.

Applications can receive notification of intermediate status by setting the lFlags parameter in the asynchronous call to WBEM_FLAG_SEND_STATUS. Intermediate status is reported when the lFlags parameter of IWbemObjectSink is set to WBEM_STATUS_PROGRESS. For more information about IWbemObjectSink, see its reference documentation and Implementing IWbemObjectSink.

The following code fragment shows how to make an asynchronous query. The application calls the IWbemServices::ExecQueryAsync method, passing a pointer to its IWbemObjectSink implementation, or sink. Eventually, one or more data objects that represent instances of classes from the query's result set are returned through a call to the IWbemObjectSink::Indicate method.

// Set input parameters to ExecQueryAsync.
BSTR QueryLang = SysAllocString(L"WQL");
BSTR Query = SysAllocString(L"select * from MyClass");

// Create IWbemObjectSink object and set pointer.
QuerySink *pSink = new QuerySink;

// Call ExecQueryAsync.
HRESULT hRes = pSvc->ExecQueryAsync (QueryLang, Query, 0,
                 NULL, pSink);

// Check for errors.
if (hRes)
{
    printf("ExecQueryAsync failed with = 0x%X\n", hRes);
    delete pSink;
    return ERROR;
}

As soon as ExecQueryAsync completes with the code WBEM_S_NO_ERROR, WMI begins delivering result objects to the sink through IWbemObjectSink::Indicate. The final status of the call is provided through another IWbemObjectSink method, SetStatus. After WMI calls SetStatus to report the final status, it calls the IWbemObjectSink::Release method multiple times to release all of its pointers to the IWbemObjectSink object. Some applications may want to implement the sink with an initial reference count of 1. This allows the application to make the final call to Release and have more control over the lifetime of their objects.

Note If a client application passes the same sink interface in two different overlapping asynchronous calls, WMI does not guarantee the order of the callback. Client applications making overlapping asynchronous calls should either pass different sink objects, or else serialize their calls.

Applications always have to call the Component Object Model (COM) function CoInitializeSecurity during their initialization phase. If they do not do so before making an asynchronous call, WMI releases the application's sink without ever calling IWbemObjectSink::SetStatus. For more information about making the CoInitializeSecurity call, see Connecting a Client Application to WMI.


Implementing IWbemObjectSink

The IWbemObjectSink interface is used by WMI to report progress and status information about an asynchronous operation or an event notification. Applications making asynchronous calls and temporary consumers registering for events implement an object that exposes an implementation of IWbemObjectSink. The following class definition is an example of how to declare an IWbemObjectSink, or sink, object. Notice that no CLSID or class factory (that is, implementation of IClassFactory) is necessary.

class QuerySink : public IWbemObjectSink
{
  // Declare the reference count for the object.
  LONG m_lRef;

public:
  QuerySink() { m_lRef = 0; }
 ~QuerySink();

  // IUnknown methods
  virtual ULONG STDMETHODCALLTYPE AddRef();
  virtual ULONG STDMETHODCALLTYPE Release();
  virtual HRESULT STDMETHODCALLTYPE QueryInterface
            (REFIID riid, void** ppv);

  // IWbemObjectSink methods
  virtual HRESULT STDMETHODCALLTYPE Indicate(
          /* [in] */ long lObjectCount,
          /* [size_is][in] */ IWbemClassObject __RPC_FAR *__RPC_FAR
             *apObjArray
          );
  virtual HRESULT STDMETHODCALLTYPE SetStatus(
          /* [in] */ long lFlags,
          /* [in] */ HRESULT hResult,
          /* [in] */ BSTR strParam,
          /* [in] */ IWbemClassObject __RPC_FAR *pObjParam
          );
};

The implementations of the three IUnknown methods are standard. AddRef increments the reference count for the sink object; Release decrements it. If the count is zero after being decremented, the sink object is deleted. This is a standard COM reference count rule. Applications must never delete their sink object without verifying that its reference count has reached zero.

ULONG QuerySink::AddRef()
{
    return InterlockedIncrement(&m_lRef);
}

ULONG QuerySink::Release()
{
    long lRef = InterlockedDecrement(&m_lRef);
    if(lRef == 0)
        delete this;
    return lRef;
}

QueryInterface returns pointers to interfaces exposed by an object. Because the IWbemObjectSink interface is the only interface exposed by this sink, the following implementation of QueryInterface returns the error code E_NOINTERFACE if the caller requests anything else.

HRESULT QuerySink::QueryInterface(REFIID riid, void** ppv)
{
    if (riid == IID_IUnknown || riid == IID_IWbemObjectSink)
    {
        *ppv = (IWbemObjectSink *) this;
        AddRef();
        return S_OK;
    }
    else return E_NOINTERFACE;
}

WMI calls the IWbemObjectSink::Indicate method to report information relating to an asynchronous operation. Indicate has two parameters: an array of pointers and a count of the number of pointers in the array. When used with an asynchronous operation such as a data query, the pointers in the array point to data objects such as instances of a class. When used to receive event notifications, each object in the array represents a separate event. In either case, the objects are accessible through the IWbemClassObject interface.

It is important that the implementation of Indicate be fast. Indicate should quickly process the objects included in the array and return. If extensive processing is required, determine which of the objects are affected and copy them. If the affected objects are events, use a different thread to handle the processing for each event.

The following code sample shows a typical implementation of the Indicate method:

HRESULT QuerySink::Indicate(long lObjCount, IWbemClassObject **pArray)
{
  // Loop through the array, examining the objects.

  for (long i = 0; i < lObjCount; i++)
  {
         IWbemClassObject *pTemp = pArray[i];

          // Use the object.
  }

  return WBEM_S_NO_ERROR;
}

WMI calls SetStatus to communicate information to the consumer or the client application. After a consumer calls the IWbemServices::ExecNotificationQueryAsync method to register for events, WMI calls SetStatus to report any errors pertaining to the registration.

For the other asynchronous calls that an application can make, SetStatus reports three types of status information: intermediate status, final status, and errors. Intermediate status is reported only if the lFlags parameter of the asynchronous method call was set to WBEM_FLAG_SEND_STATUS. Intermediate status values include those following.

Status value | Description
WBEM_STATUS_COMPLETE | The operation was complete. The hResult parameter contains the error code, and the pObjParam parameter contains NULL or an error object. The strParam parameter contains NULL or, for a call to the IWbemServices::PutInstanceAsync method, the path of the object being updated.
WBEM_STATUS_PROGRESS | The HIWORD of the hResult parameter contains the upper bound on the total amount of progress for the operation. The LOWORD of the hResult parameter contains the amount of progress that has been made so far (for example, "12 out of 200"). The strParam parameter contains NULL or a human-readable message.

This code fragment shows how to structure an implementation of SetStatus:

HRESULT QuerySink::SetStatus(
            /* [in] */ long lFlags,
            /* [in] */ HRESULT hResult,
            /* [in] */ BSTR strParam,
            /* [in] */ IWbemClassObject __RPC_FAR *pObjParam
    )
{
  printf("QuerySink::SetStatus hResult = 0x%X\n", hResult);

  return WBEM_S_NO_ERROR;
}


Security Considerations with Asynchronous Calls

All of the Distributed COM (DCOM) security rules that typically apply to providers implementing objects also apply to applications making asynchronous calls. This is because these applications must implement a COM object called a sink object to expose the methods of the IWbemObjectSink interface. For more information about the DCOM security rules, see the DCOM security topics in the Platform SDK.

An application making asynchronous calls needs to inform DCOM that it allows WMI to invoke the methods of its sink. Because WMI is running as a service under the LocalSystem account and has no network privileges, the only way that an application can grant WMI permission to call its IWbemObjectSink methods is to also grant all other applications and services permission.

There are two options that client applications have for granting permissions. The first option is to call the COM function CoInitializeSecurity with the dwAuthnLevel parameter set to RPC_C_AUTHN_LEVEL_NONE. The application does so immediately after COM has been initialized with a first-time call to either the COM function CoInitialize or CoInitializeEx. The CoInitializeSecurity call must be made before any out-of-process calls are made.

This option is simple, but it cannot work for every client process. Calling CoInitializeSecurity disables security checks for all objects hosted in the client process. If the client hosts any sensitive objects, using the CoInitializeSecurity approach creates a security hole. Therefore, this option is only possible for client processes that do not host any sensitive objects, such as processes whose sole purpose is to communicate with WMI.

Another problem with the CoInitializeSecurity option is that it can be used only by a client that controls its process. This is because the CoInitializeSecurity call must be made immediately after the process has started. For example, a Microsoft® ActiveX® control does not control its process. Because controls are loaded into their container's process, they do not have the option of establishing process-wide security settings. By the time these controls are loaded, it is usually already too late.

DLLs also should not change process-wide security settings. If a DLL did change these settings, it might interfere with other controls loaded into the same process and possibly create security holes.

The second option is to implement the sink in a separate process that can call CoInitializeSecurity according to the first option. To help clients take advantage of this option, WMI provides a separate process, Unsecapp.exe. Hosting a sink in the Unsecapp.exe process is accomplished with the IUnsecuredApartment interface.

The IUnsecuredApartment interface option makes sense for client applications that cannot or should not use the CoInitializeSecurity approach. This interface allows client applications to create a dedicated process for hosting their IWbemObjectSink implementations. This dedicated process calls CoInitializeSecurity to grant WMI permission without facing any of the difficulties that can arise when the main process makes the call. After initialization, the dedicated process communicates information back to the main process locally.

To create a dedicated process, call the COM function CoCreateInstance as follows:

IUnsecuredApartment* pUnsecApp = NULL;
CoCreateInstance(CLSID_UnsecuredApartment, NULL,
  CLSCTX_LOCAL_SERVER, IID_IUnsecuredApartment,
  (void**)&pUnsecApp);

Calling CoCreateInstance starts Unsecapp.exe if it is not already running. This application receives the asynchronous calls on behalf of the client process and forwards them to the client's sink.

To make an asynchronous call using Unsecapp.exe, use the following sequence of operations (error checking has been omitted for brevity):

  1. Instantiate the sink object:
    CMySink* pSink = new CMySink;
pSink->AddRef();
  2. Create a "stub" for the sink, a wrapper produced from the object. Call the wrapper's IUnknown::QueryInterface method and request a pointer to its IWbemObjectSink interface:
    IUnknown* pStubUnk = NULL;
pUnsecApp->CreateObjectStub(pSink, &pStubUnk);

IWbemObjectSink* pStubSink = NULL;
pStubUnk->QueryInterface(IID_IWbemObjectSink, (void **)
  &pStubSink);
pStubUnk->Release();
  3. Release the sink object pointer, because the stub now owns it:
    pSink->Release();
  4. Use this stub in any asynchronous call and release any local reference count for it:
    pServices->CreateInstanceEnumAsync(strClassName, 0, NULL,
    pStubSink);
pStubSink->Release();

Do not release the pStubSink pointer until it can be determined with certainty that the asynchronous call does not need to be canceled. It is important not to wait to release pStubSink until the pointer to the sink (pSink) is released by WMI because that creates a circular reference count, with both objects staying in memory forever. A good place to release the stub pointer is in the IWbemObjectSink::SetStatus call, made by WMI to report that the original asynchronous call has completed.

Note that because the same pointer must be used to cancel a call as was used to issue the call, a cancellation looks like this:

pServices->CancelAsyncCall(pStubSink);

When the client application is ready to shut down, make the following call before uninitializing COM:

pUnsecApp->Release();

For more information about CoInitializeSecurity and its parameters, see the COM documentation in the Platform SDK.


Canceling an Asynchronous Operation

To cancel the processing of an asynchronous operation before it has reported a final status, an application calls IWbemServices::CancelAsyncCall. CancelAsyncCall cancels asynchronous processing by immediately releasing the application's IWbemObjectSink pointer. It is guaranteed that the application's IWbemObjectSink pointer is released before CancelAsyncCall returns.

If SetStatus has not been called on the application's sink by the time CancelAsyncCall is processed, WMI calls SetStatus on that sink with WBEM_E_CALL_CANCELLED as the value for the hResult parameter.

Note, however, that timing and the nature of an asynchronous operation can affect whether the operation is truly canceled. Only lengthy queries are likely to be successfully canceled before they have completed. Faster operations such as asynchronous deletions or modifications typically complete before a CancelAsyncCall can be made. CancelAsyncCall attempts to cancel the current operation, but sometimes all that can be done is to release the IWbemObjectSink pointer.

Using a wrapper object implementing the IUnsecuredApartment interface to host the IWbemObjectSink implementation presents some additional complications when canceling an asynchronous call. Because the application must pass the same pointer to CancelAsyncCall that was passed in the original asynchronous call, the application must hold on to the wrapper object until it becomes clear that cancellation is not required. For more information, see Security Considerations with Asynchronous Calls.

Note You may not call CancelAsyncCall from within a sink.


Making a Semisynchronous Call

Semisynchronous processing is a compromise between synchronous processing and asynchronous processing, providing some of the advantages and eliminating the disadvantages of each technique. One disadvantage of synchronous processing is that the caller's thread is blocked until the call completes. This blockage can cause a lengthy delay in processing time. The disadvantages of asynchronous processing are:

  • Callers must implement the IWbemObjectSink interface.
  • Multiple threads are used.
  • It can be hard to control the flow of information back to the caller.

Large result sets from queries, for example, can take a considerable amount of time to deliver, forcing the caller to spend significant system resources to handle the delivery.

Semisynchronous processing solves both the thread blockage and uncontrolled delivery problems by polling a special status object that implements the IWbemCallResult interface. IWbemCallResult is used to determine the state of a call.

Semisynchronous processing can be used by applications to improve the speed and efficiency of three types of operations:

  • Queries
  • Enumerations
  • Event notifications

Every synchronous method of IWbemServices has a semisynchronous mode that is invoked when the caller sets the lFlags parameter to the WBEM_FLAG_RETURN_IMMEDIATELY flag. WBEM_FLAG_RETURN_IMMEDIATELY can be combined with other flags that are valid for the particular method. For example, the WBEM_FLAG_FORWARD_ONLY flag should also be set for all calls that return enumerators. Setting these flags in combination saves time, space, and improves responsiveness.

Calls such as those to the IWbemServices::CreateClassEnum and IWbemServices::ExecQuery methods return enumerators; these enumerators can be polled for the results of the call. No other parameters are needed. A call such as one to the IWbemServices::GetObject method does not return an enumerator and requires the ppCallResult parameter to be set to a valid pointer to obtain the results of the call. Setting ppCallResult to NULL when the WBEM_FLAG_RETURN_IMMEDIATELY flag is specified results in the call returning the error code WBEM_E_INVALID_PARAMETER.

For example, to take advantage of semisynchronous object deletion, an application calls the IWbemServices::DeleteInstance method with the appropriate flag settings and a non-NULL pointer in the ppCallResult parameter. The IWbemCallResult pointer must be set in ppCallResult because DeleteInstance does not return an enumerator. DeleteInstance returns immediately with ppCallResult set to a valid IWbemCallResult pointer. The application can periodically call the IWbemCallResult::GetCallStatus method until it returns the code WBEM_S_NO_ERROR. The final status of the original call is available in the GetCallStatus output parameter plStatus.

To obtain the enumerated objects, an application can call either the IEnumWbemClassObject::Next or IEnumWbemClassObject::NextAsync method. Next returns objects synchronously; NextAsync returns objects through the caller's IWbemObjectSink::Indicate method. When all of the objects have been returned, the caller's IWbemObjectSink::SetStatus method is called to report the completion of the operation.

To take advantage of semisynchronous processing in an operation that returns an enumerator, an application:

  • Makes the synchronous call with lFlags set to WBEM_FLAG_RETURN_IMMEDIATELY. For example, to issue a query, an application calls the IWbemServices::ExecQuery method.
  • Either repeatedly calls IEnumWbemClassObject::Next to retrieve the objects in batches or IEnumWbemClassObject::NextAsync to request the results in small groups asynchronously.

With the application calls NextAsync, the uCount parameter should be set to the number of objects to be returned in the group and the pSink parameter should point to an implementation of the IWbemObjectSink interface. The IEnumWbemClassObject::NextAsync call is nonblocking and returns immediately. In the background, Windows Management Instrumentation (WMI) begins to deliver the requested number of objects by calling IWbemObjectSink::Indicate. It then stops, waiting for another NextAsync call. NextAsync places the number of objects actually returned in the lObjectCount parameter and the objects themselves in the ppObjArray parameter. When the last object has been delivered, WMI calls IWbemObjectSink::SetStatus to report a final status.

If the entire result set is not needed, an application should release the enumerator by calling the IEnumWbemClassObject::Release method. Calling this Release method results in WMI canceling its delivery of any remaining objects.

The following code sample shows how to make a semisynchronous call to IWbemServices::GetObject:

void GetObjSemiSync(IWbemServices *pSvc)
{

    IWbemCallResult *pCallRes = 0;
    IWbemClassObject *pObj = 0;

    HRESULT hRes = pSvc->GetObject(_bstr_t(L"MyClass=\"AAA\""), 0,
        0, 0, &pCallRes
        );

    if (hRes || pCallRes == 0)
        return;

    while (1)
    {
        LONG lStatus = 0;
        HRESULT hRes = pCallRes->GetCallStatus(5000, &lStatus);
        if (lStatus == 0)
            break;

        // Do something else
    }

    hRes = pCallRes->GetResultObject(5000, &pObj);
    if (hRes)
    {
        pCallRes->Release();
        return;
    }

    pCallRes->Release();

    // Use the object.

    // ...

    // Release it.
    // ===========

    pObj->Release();    // Release objects we don't own.

}


Creating a Namespace

Namespaces are used in Windows Management Instrumentation (WMI) to differentiate among the groups of classes and instances that represent particular managed environments. Because the components in a managed environment are defined by the classes and instances in a schema, each new schema or schema version requires a new namespace. For example, the Root\Cimv2 namespace contains the classes and instances defined in the Microsoft® Win32® schema.

Namespaces are represented in WMI by the __Namespace system class and classes that derive from this system class. The __Namespace class has a single property called Name, which must be unique within the scope of the parent namespace. The Name property must be set to a string that begins with a letter. All other characters in the string can be letters, digits, or underscores. All characters are case-insensitive.

Namespaces can be created using the Managed Object Format (MOF) language or the WMI API. To create a new namespace using the MOF language, create an instance of the __Namespace system class as follows:

instance of __Namespace
{
    Name = "MyNamespace";
};

The namespace called MyNamespace is created within the current namespace. To create a namespace within a specific namespace other than the current one, use the #pragma namespace directive prior to the instance declaration. The next example shows how to create a namespace as a sibling to the Root\Cimv2 namespace:

#pragma namespace("\\\\.\\Root\\Cimv2")

instance of __Namespace
{
    Name = "MyNamespace";
};

To create a namespace using the WMI API

  1. Call the IWbemServices::GetObject method to retrieve an IWbemClassObject pointer for the __Namespace system class.
  2. Call the IWbemClassObject::SpawnInstance method to define an instance of the __Namespace system class.
  3. Call the IWbemClassObject::Put method to set the Name property of the __Namespace instance.
  4. Call the IWbemServices::PutInstance method to create the namespace. The pInst parameter should point to the new instance.


Creating a Base Class

Applications can create classes using either the Managed Object Format (MOF) language or the Windows Management Instrumentation (WMI) API. To create a class with MOF, see Declaring Classes.

Applications perform the following tasks to create a new base class with the WMI API:

  1. Retrieve a definition for the new class by calling the IWbemServices::GetObject method with the strObjectPath parameter set to NULL.
  2. Establish a name for the class by setting the __CLASS system property with a call to the IWbemClassObject::Put method.
  3. Create the key property or properties by calling IWbemClassObject::Put. Because properties marked as keys or indices cannot be changed after a class has been created, it is important to specify key and index properties by creating the properties and adding the appropriate Key and Indexed qualifiers before creating the class using the IWbemServices::PutClass or IWbemServices::PutClassAsync method.
  4. Attach the Key standard qualifier to the key property by first calling the IWbemClassObject::GetPropertyQualifierSet method and then the IWbemQualifierSet::Put method.
  5. Create the other properties of the class with IWbemClassObject::Put.
  6. Save the new class by calling IWbemServices::PutClass. All of the desired properties of the class must be specified before making the call to PutClass.

The following sample shows how to implement these tasks. This sample creates a class called Example. The pSvc pointer is an IWbemServices pointer obtained from a prior call to the IWbemLocator::ConnectServer method to connect to WMI. Some of the error-checking code is omitted for clarity.

void CreateClass(IWbemServices *pSvc)
{
  IWbemClassObject *pNewClass = 0;
  IWbemContext *pCtx = 0;
  IWbemCallResult *pResult = 0;

  // Get a class definition.
  // ============================
  HRESULT hRes = pSvc->GetObject (0, 0, pCtx, &pNewClass, &pResult);
  VARIANT v;
  VariantInit(&v);

  // Create the class name.
  // ============================
  V_VT(&v) = VT_BSTR;
  V_BSTR(&v) = SysAllocString(L"Example");
  BSTR Class = SysAllocString(L"__CLASS");
  pNewClass->Put(Class, 0, &v, 0);
  SysFreeString(Class);
  VariantClear(&v);

  // Create the key property.
  // ============================
  BSTR KeyProp = SysAllocString(L"Index");
  pNewClass->Put(KeyProp, 0, NULL, CIM_STRING);

  // Attach Key qualifier to mark the "Index" property as the key.
  // ============================
  IWbemQualifierSet *pQual = 0;
  pNewClass->GetPropertyQualifierSet(KeyProp, &pQual);
  SysFreeString(KeyProp);

  V_VT(&v) = VT_BOOL;
  V_BOOL(&v) = VARIANT_TRUE;
  BSTR Key = SysAllocString(L"Key");

  pQual->Put(Key, &v, 0);   // Flavors not required for Key
  SysFreeString(Key);

  pQual->Release();   // No longer need the qualifier set for "Index"
  VariantClear(&v);

  // Create other properties.
  // ============================
  V_VT(&v) = VT_BSTR;
  V_BSTR(&v) = SysAllocString(L"<default>");
  BSTR OtherProp = SysAllocString(L"OtherInfo");
  pNewClass->Put(OtherProp, 0, &v, CIM_STRING);
  SysFreeString(OtherProp);
  VariantClear(&v);

  OtherProp = SysAllocString(L"IntVal");
  pNewClass->Put(OtherProp, 0, NULL, CIM_SINT32);  // NULL is default
  SysFreeString(OtherProp);

  // Register the class with WMI
  // ============================
  hRes = pSvc->PutClass(pNewClass, 0, pCtx, &pResult);
  pNewClass->Release();
}


Creating a Derived Class

Creating a derived class is similar to creating a base class. The main difference is that before the derived class is created, its parent class must be located, as shown in the following fragment. The class Example2 is created as a subclass to the Example class created in the topic Creating a Base Class.

void CreateDerivedClass(IWbemServices *pSvc)
{
  IWbemClassObject *pNewDerivedClass = 0;
  IWbemClassObject *pExampleClass = 0;
  IWbemContext *pCtx = 0;
  IWbemCallResult *pResult = 0;

  BSTR PathToClass = SysAllocString(L"Example");
  HRESULT hRes = pSvc->GetObject(PathToClass, 0, pCtx,
    &pExampleClass, &pResult);
  SysFreeString(PathToClass);

  if (hRes != 0)
    return;

  pExampleClass->SpawnDerivedClass(0, &pNewDerivedClass);
  pExampleClass->Release();  // Don't need the superclass any more

  VARIANT v;
  VariantInit(&v);

  // Create the class name.
  // =====================

  V_VT(&v) = VT_BSTR;
  V_BSTR(&v) = SysAllocString(L"Example2");
  BSTR Class = SysAllocString(L"__CLASS");
  pNewDerivedClass->Put(Class, 0, &v, 0);
  SysFreeString(Class);
  VariantClear(&v);

  // Create another property.
  // =======================
  BSTR OtherProp = SysAllocString(L"OtherInfo2");
  // No default value
  pNewDerivedClass->Put(OtherProp, 0, NULL, CIM_STRING);
  SysFreeString(OtherProp);

  // Register the class with Windows Management Instrumentation (WMI).
  // ============================
  hRes = pSvc->PutClass(pNewDerivedClass, 0, pCtx, &pResult);
  pNewDerivedClass->Release();
}

New properties are created initially using the IWbemClassObject::Put method. The pVal parameter is a VARIANT pointer that points to either a property value or NULL. If pVal points to NULL, the type of the property is indicated by the vtType parameter. This parameter is set to one of the Common Information Model (CIM) type constants such as CIM_SINT32 and CIM_STRING. This is always required during property creation.

To define a property that has strongly typed references to other objects

  • The Put parameter vtType must be set to CIM_REFERENCE.
  • The Cimtype standard qualifier must be attached to the property. The value of the qualifier must be set to the appropriate CIM data type for the property.
  • The value of the Cimtype qualifier must indicate the class that the reference can point to by including a string of the following format:
    REF:ClassName

For example, if the derived class requires an object reference property that refers to instances of the Win32_LogicalDisk class, attach the Cimtype qualifier to the property when the class definition is created. In the following sample, the object reference property is called MyReferenceProperty. A call is made to the IWbemClassObject::GetPropertyQualifierSet method to retrieve a pointer to the IWbemQualifierSet interface. The IWbemQualifierSet::Put method is used to attach the Cimtype qualifier to the MyReferenceProperty property.

BSTR RefProp = SysAllocString(L"MyReferenceProperty");
IWbemQualifierSet *pQual = 0;
pNewClass->GetPropertyQualifierSet(RefProp, &pQual);

VARIANT v;
VariantInit(&v);
V_VT(&v) = VT_BSTR;
V_BSTR(&v) = SysAllocString(L"REF:Win32_LogicalDisk");
BSTR QualName = SysAllocString(L"CIMTYPE");
pQual->Put(QualName, WBEM_FLAVOR_FLAG_PROPAGATE_TO_INSTANCE, &v);

Embedded object properties are similar to object references. However, the vtType parameter for an embedded object property must be CIM_OBJECT rather than CIM_REFERENCE, and the Cimtype standard qualifier must be set to "object:ClassName".

After the derived class has been created, an application cannot:

  • Change its superclass.
  • Add or remove properties.
  • Change property types.
  • Add or remove Key or Indexed qualifiers.
  • Add or remove Singleton, Dynamic, or Abstract qualifiers.


Creating an Instance

There are four main steps to creating an instance of an existing class:

  1. Retrieve the definition of the existing class by calling the IWbemServices::GetObject or IWbemServices::GetObjectAsync method. These methods return a pointer to the IWbemClassObject interface that provides access to the class definition.
  2. Create the new instance by calling the IWbemClassObject::SpawnInstance method.
  3. Set values for any properties that do not inherit the values defined for the class by calling the IWbemClassObject::Put method. Each instance of a class inherits all of the properties that are defined for the class, but each can specify different property values.
  4. Save the instance by calling the IWbemServices::PutInstance or IWbemServices::PutInstanceAsync method.

If the existing class has a key property, an application can either set it to NULL or to a value that is guaranteed to be unique. If the key property is set to NULL and is a string, PutInstance or PutInstanceAsync internally generates a globally unique identifier (GUID) and assigns this GUID to the key property. Specifying NULL for a key property allows an application to create an instance with 100 percent certainty that the new instance will not overwrite any previous instance.

As an option, an instance can define additional qualifiers that are not defined for the class. These qualifiers can be defined for the instance or for a particular property of the instance and do not need to appear in the class declaration.

An instance can also specify different values for qualifiers defined for the class, but only if the qualifiers have set their qualifier flavor to EnableOverride. Class qualifiers with flavors set to DisableOverride cannot be modified or deleted in any way. For more information about how and when qualifier values can be overridden, see Qualifier Flavors.

Applications gain access to the set of qualifiers defined for a class by calling the IWbemClassObject::GetQualifierSet method. This method returns an IWbemQualifierSet interface pointer that can be used to retrieve, add, delete, or modify a specified qualifier.

The following code creates an instance of the Example class:

void CreateInstance (IWbemServices *pSvc)
{
    IWbemClassObject *pNewInstance = 0;
    IWbemClassObject *pExampleClass = 0;
    IWbemContext *pCtx = 0;
    IWbemCallResult *pResult = 0;

    // Get the class definition.
    BSTR PathToClass = SysAllocString(L"Example");
    HRESULT hRes = pSvc->GetObject(PathToClass, 0, pCtx,
                 &pExampleClass, &pResult);
    SysFreeString(PathToClass);

    if (hRes != 0)
       return;

    // Create a new instance.
    pExampleClass->SpawnInstance(0, &pNewInstance);
    pExampleClass->Release();  // Don't need the class any more

    VARIANT v;
    VariantInit(&v);

    // Set the Index property (the key).
    V_VT(&v) = VT_BSTR;
    V_BSTR(&v) = SysAllocString(L"IX100");

    BSTR KeyProp = SysAllocString(L"Index");
    pNewInstance->Put(KeyProp, 0, &v, 0);
    SysFreeString(KeyProp);
    VariantClear(&v);

    // Set the IntVal property.
    V_VT(&v) = VT_I4;
    V_I4(&v) = 1001;

    BSTR Prop = SysAllocString(L"IntVal");
    pNewInstance->Put(Prop, 0, &v, 0);
    SysFreeString(Prop);
    VariantClear(&v);

    // Other properties acquire the 'default' value specified
    // in the class definition unless otherwise modified here.

    // Write the instance to Windows Management Instrumentation (WMI).
    hRes = pSvc->PutInstance(pNewInstance, 0, pCtx, &pResult);
    pNewInstance->Release();

}

After the instance has been created, it has a relative path of Example.Index="IX100." The full path is dependent on the namespace in which the instance was created but might typically be \Root\Default. In that case, the full path is: \\.\Root\Default:Example.Index="IX100".

There are several restrictions regarding operations on existing instances. An application cannot:

  • Change the superclass of the class to which the instance belongs.
  • Add or remove properties.
  • Change property types.
  • Add or remove Key or Indexed qualifiers.
  • Add or remove Singleton, Dynamic, or Abstract qualifiers.


Deleting an Instance

To delete an instance of a base or derived class, an application calls either the IWbemServices::DeleteInstance or IWbemServices::DeleteInstanceAsync method. The former call deletes the instance synchronously; the latter asynchronously. To take advantage of asynchronous processing, an application must implement the IWbemObjectSink interface. The results of the deletion are returned through this interface.

In the case that the instance is static, the instance is simply deleted from the Common Information Model (CIM) repository. However, with dynamic instances backed by providers, the processing is more complex. When an application deletes a dynamic instance of a derived class, Windows Management Instrumentation (WMI) calls the IWbemServices::DeleteInstanceAsync method of the following providers:

  • The provider responsible for the class that owns the instance
  • The providers responsible for every superclass of the class that owns the instance
  • The providers responsible for every subclass of the class that owns the instance

The success of the deletion depends on the topmost nonabstract class for the original instance. The topmost nonabstract class is the child class of an abstract parent. If the provider for any topmost nonabstract class succeeds, the operation succeeds. For more information, see the Remarks section of the IWbemServices::DeleteInstance topic.


Using Queries

Queries are WMI Query Language (WQL) statements that can be used by applications to:

  • Retrieve data, such as a class definition or instances of a specified class.
  • Register for event notification.
  • Retrieve schema information.

A prior understanding of WQL is essential to writing a correct and effective query. A query that is either incorrect, too complex, or inappropriate can cause the query processor to return an error or unexpected results. For a comprehensive guide to WQL, see WMI Query Language.

Applications can submit a query synchronously or asynchronously. Synchronous queries are initiated when an application calls the IWbemServices::ExecQuery method. The application calls the IEnumWbemClassObject::Next method repeatedly to retrieve the query results.

Asynchronous queries are initiated when an application calls the IWbemServices::ExecQueryAsync method. The results of the query are returned at some later point when the application's IWbemObjectSink::Indicate method is called.


Synchronous Queries

There are two methods that are involved in issuing a synchronous query:

  • IWbemServices::ExecQuery
  • IEnumWbemClassObject::Next

The code for enumerating classes and instances is very similar to the code for issuing a synchronous query. Both situations require an enumerator to retrieve results. The enumerator is an implementation of the IEnumWbemClassObject interface.

To retrieve an enumerator for classes, an application calls the IWbemServices:CreateClassEnum method. To retrieve an enumerator for instances, an applications calls the IWbemServices::CreateInstanceEnum method. To retrieve an enumerator for query results, an application calls the IWbemServices::ExecQuery method. ExecQuery returns an IEnumWbemClassObject interface pointer that the application uses to repeatedly call the IEnumWbemClassObject::Next method to retrieve classes or instances in the result set. When all of the data has been returned, the application releases the enumerator by calling the IEnumWbemClassObject::Release method.

The following code sample shows how to issue a synchronous query to retrieve all of the users and groups in Windows Management Instrumentation (WMI):

void ExecQuerySync(IWbemServices *pSvc)
{
    // Query for all users and groups.

    BSTR Language = SysAllocString(L"WQL");
    BSTR Query = SysAllocString(L"select * from __Subject");

    // Initialize the IEnumWbemClassObject pointer.
    IEnumWbemClassObject *pEnum = 0;

    // Issue the query.
    HRESULT hRes = pSvc->ExecQuery(
        Language,
        Query,
        WBEM_FLAG_FORWARD_ONLY,         // Flags
        0,                              // Context
        &pEnum
        );

    SysFreeString(Query);
    SysFreeString(Language);

    if (hRes != 0)
    {
        printf("Error\n");
        return;
    }

    ULONG uTotal = 0;

    // Retrieve the objects in the result set.
    for (;;)
    {
        IWbemClassObject *pObj = 0;
        ULONG uReturned = 0;

        hRes = pEnum->Next(
            0,                  // Time out
            1,                  // One object
            &pObj,
            &uReturned
            );

        uTotal += uReturned;

        if (uReturned == 0)
            break;

        // Use the object.

        // ...

        // Release it.
        // ===========

        pObj->Release();    // Release objects we don't own.
    }

    // All done.
    pEnum->Release();
}


Asynchronous Queries

Before an application can issue an asynchronous query, it must implement an object known as the sink object. The sink object exposes the methods of the IWbemObjectSink interface. IWbemObjectSink has methods for receiving information about an asynchronous operation. For information about implementing this interface, see Implementing IWbemObjectSink.

The following code shows how to make an asynchronous call to issue a query:

void ExecQuery(IWbemServices *pSvc)
{
    // Create a new sink object.
    QuerySink *pSink = new QuerySink;

    // Initialize the query and query language.
    BSTR strQuery = SysAllocString(L"select * from ClassName");
    BSTR strQueryLang = SysAllocString(L"WQL");

    // Issue the query.
    HRESULT hRes = pSvc->ExecQueryAsync(strQueryLang, strQuery, 0,
        NULL, pSink);

    // Clean up.
    SysFreeString(strQuery);
    SysFreeString(strQueryLang);

    if (hRes)
    {
        printf("ExecQueryAsync failed with = 0x%X\n", hRes);
        return;
    }

    printf("Completed.\n");
}

The classes or instances that are requested in the query are delivered in the background to the sink using another thread. The thread that executes the query itself is immediately available for other tasks.


Calling a Method

Windows Management Instrumentation (WMI) allows applications to call methods defined in a class supported by a provider. To retrieve the signature of a method, an application must first get the definition of the class to which the method belongs. Method signatures are only available through a class definition.

To call a method

  1. Declare the following interface pointers:
    Pointer type | Description
    IWbemLocator | Used to connect to WMI
    IWbemServices | Used to make calls to the WMI API
    IWbemClassObject | Used to access the TestMeth class definition.
    IWbemClassObject | Used to access the input parameter class definition.
    IWbemClassObject | Used to access the input parameter.
    IWbemClassObject | Used to access the output parameter.

  2. Declare string variables for the names of the class, method, namespace, and input parameter.
  3. After connecting to WMI, call the IWbemServices::GetObject method to get the definition of the class that includes the method. GetObject returns an IWbemClassObject interface pointer that points to the class definition.
  4. For methods that require input parameters, call the IWbemClassObject::GetMethod method to get the input parameter class object. GetMethod returns an IWbemClassObject pointer that points to the input parameter class.
  5. Use the input parameter class pointer to generate an instance of this class with the IWbemClassObject::SpawnInstance method.
  6. Use the class object pointer returned by SpawnInstance to set the properties that correspond to the input parameters with the IWbemClassObject::Put method.
  7. Call the IWbemServices::ExecMethod or IWbemServices::ExecMethodAsync method to invoke the method. For ExecMethod, any output parameters are returned in the call. For ExecMethodAsync, output parameters are returned through a call to IWbemObjectSink. For more information about asynchronous calls, see Making an Asynchronous Call.

The following Managed Object Format (MOF) syntax defines the TestMeth class that is supported by a method provider called MethProv. TestMeth includes a method called Echo with one input parameter and one output parameter. Both parameters are strings. Echo displays a copy of the input string and then returns its length.

[dynamic: ToInstance, provider("MethProvider")]
class TestMeth
{
  [implemented, static]
  uint32 Echo([IN]string sInArg, [out] string sOutArg);
};

The following sample function shows how to call the Echo method of the TestMeth class. The sample is fairly complete, except that it displays the return value and output string by using the IWbemClassObject::GetObjectText method rather than getting each property individually.

int main(int iArgCnt, char ** argv)
{
    IWbemLocator *pLocator = NULL;
    IWbemServices *pNamespace = 0;
    IWbemClassObject * pClass = NULL;
    IWbemClassObject * pOutInst = NULL;
    IWbemClassObject * pInClass = NULL;
    IWbemClassObject * pInInst = NULL;

    BSTR path = SysAllocString(L"root\\default");
    BSTR ClassPath = SysAllocString(L"TestMeth");
    BSTR MethodName = SysAllocString(L"Echo");
    BSTR ArgName = SysAllocString(L"sInArg");
    BSTR Text;

    // Initialize the Component Object Model (COM) and connect to WMI.

    HRESULT hr = CoInitialize(0);
    hr = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER,
            IID_IWbemLocator, (LPVOID *) &pLocator);
    hr = pLocator->ConnectServer(path, NULL, NULL, NULL, 0, NULL,
            NULL, &pNamespace);

    // Get the class object for the method definition.

    hr = pNamespace->GetObject(ClassPath, 0, NULL, &pClass, NULL);

    // Get the input-argument class object and create an instance.

    hr = pClass->GetMethod(MethodName, 0, &pInClass, NULL);
    hr = pInClass->SpawnInstance(0, &pInInst);

    // Set the property.

    VARIANT var;
    var.vt = VT_BSTR;
    var.bstrVal= SysAllocString(L"hello");
    hr = pInInst->Put(ArgName, 0, &var, 0);
    VariantClear(&var);

    // Call the method.

    hr = pNamespace->ExecMethod(ClassPath, MethodName, 0, NULL,
            pInInst, &pOutInst, NULL);

    // Display the results. Note that the return value is in the
    // property "ReturnValue" and the returned string is in the
    // property "sOutArg".

    hr = pOutInst->GetObjectText(0, &Text);
    printf("\nThe object text is:\n%S", Text);

    // Free up resources.

    SysFreeString(path);
    SysFreeString(ClassPath);
    SysFreeString(MethodName);
    SysFreeString(ArgName);
    SysFreeString(Text);
    pClass->Release();
    pInInst->Release();
    pInClass->Release();
    pOutInst->Release();
    pLocator->Release();
    pNamespace->Release();
    CoUninitialize();
    printf("Terminating normally\n");
    return 0;
}


Retrieving a Class Definition

Applications call the IWbemServices::GetObject or IWbemServices::GetObjectAsync method to retrieve the definition of a class.

Applications should be aware that a single class can have multiple class definitions when one or more class providers are loaded in a namespace. When a class has multiple class definitions, Windows Management Instrumentation (WMI) returns the first definition that it finds and returns the WBEM_S_DUPLICATE_OBJECTS status code.


Enumerating Objects

Windows Management Instrumentation (WMI) provides several different enumeration operations. Applications can enumerate classes, instances, the results of a query, and event notifications. All of these methods return an enumerator, an object that supports the IEnumWbemClassObject interface. IEnumWbemClassObject includes methods that allow the application to enumerate in a forward direction, to skip objects, to begin again at the beginning, and to copy the enumerator.

The following table lists the methods that are used for the different enumeration operations; both the synchronous version and asynchronous version of each method are included.

Operation Method
Enumerating classes IWbemServices::CreateClassEnum
IWbemServices::CreateClassEnumAsync
Enumerating instances IWbemServices::CreateInstanceEnum
IWbemServices::CreateInstanceEnumAsync
Enumerating query results IWbemServices::ExecQuery
IWbemServices::ExecQueryAsync
Enumerating event notifications IWbemServices::ExecNotificationQuery
IWbemServices::ExecNotificationQueryAsync


Increasing Enumeration Performance

When calling the enumeration methods listed above, applications should always set the lFlags parameter to the following combination of flags:

WBEM_FLAG_RETURN_IMMEDIATE | WBEM_FLAG_FORWARD_ONLY

Setting lFlags to WBEM_FLAG_RETURN_IMMEDIATE and WBEM_FLAG_FORWARD_ONLY flags saves space, time, and greatly improves responsiveness. The WBEM_FLAG_RETURN_IMMEDIATE flag requests semisynchronous behavior. The call to create the enumerator returns immediately and the application calls the IEnumWbemClassObject::Next or IEnumWbemClassObject::NextAsync method to retrieve the objects. For information about semisynchronous operations, see Making a Semisynchronous Call.

The WBEM_FLAG_FORWARD_ONLY flag requests an enumerator that cannot be rewound. That is, once the application has traversed the set of objects from the beginning to the end, the enumerator cannot be rewound. Applications can request a forward-only enumerator by setting the lFlags parameter in their call to WBEM_FLAG_FORWARD_ONLY. Setting the WBEM_FLAG_FORWARD_ONLY flag allows WMI to release objects that an application has already retrieved. In situations where the enumeration is large and the application is very fast, using forward-only enumerators with semisynchronous processing allows WMI to hold on to far fewer objects, thereby increasing response time and memory performance significantly.

Whenever possible, avoid using CreateInstanceEnum, and replace it with ExecQuery. Ask for ONLY the properties you need.

Also, WMI has a "post filter" feature, so if a provider sends back instances that don't match the query, WMI will discard these instances. Many providers take advantage of this; when a query is too complex, the provider may fall back to doing an enumeration. "Too complex" means whatever the provider author decides is too complex.

Experiment with various queries to see what gives you the best performance. Queries with WHERE clauses of the form Prop1 < "x" will seldom be efficiently processed, while queries of the form KeyProp1 = "x" will normally be processed efficiently.


Updating an Instance

Applications update an instance by calling either the IWbemServices::PutInstance or IWbemServices::PutInstanceAsync method. The former call deletes the instance synchronously; the latter asynchronously. To take advantage of asynchronous processing, an application must implement the IWbemObjectSink interface. The results of the operation are returned through this interface.

When an application must update an instance that belongs to a class hierarchy, the pInst parameter must point to the instance containing the properties to be modified. That is, consider a target instance that belongs to ClassB. ClassB derives from ClassA, and ClassA defines the property PropA. If an application wants to make a change to the value of PropA in the ClassB instance, it must set pInst to that instance rather than an instance of ClassA.

Application developers should be aware that an update operation on an instance belonging to a class hierarchy might not succeed due to an error involving another class in the hierarchy. Windows Management Instrumentation (WMI) calls the PutInstanceAsync method of each of the providers responsible for the classes from which the class owning the original instance derives. If any of these providers fail, the original update request fails. For more information, see the Remarks section of the IWbemServices::PutInstance topic.

There are two types of update operations for all instances:

  • Those that affect all of the properties in the instance
  • Those that affect only some of the properties

Applications that need to perform partial instance updates must be prepared for these operations to fail with either the WBEM_E_PROVIDER_NOT_CAPABLE or WBEM_E_NOT_SUPPORTED error code. WMI does not support partial update operations, nor do most providers.

To request a partial instance update, an application must include a valid context information in the pCtx parameter. If pCtx is set to NULL, PutInstance or PutInstanceAsync automatically attempts to update all of the properties for the instance. Properties set to VT_NULL can cause the operation to fail when there is no context object, depending on the provider.

To specify valid context information, an application must set the __PUT_EXTENSIONS system context value. System context values are defined by WMI to have specific meanings, set by client applications and supported by instance providers. Illegal usage of these context values can cause a VARIANT type mismatch between the application and the provider.

If no context object is present in the call that contains __PUT_EXTENSIONS, the provider may elect to take a "best effort" approach and try to write whatever properties it can without reporting an error. However, if the __PUT_EXTENSIONS value is present in the context object, the provider is required to obey the semantics of the operation exactly or to fail the call. For more information, see Reporting Access Denials.

An application can set the following system context values to request a partial instance update operation.

System context value | Description
__PUT_EXTENSIONS | A Boolean value that indicates that one or more of the other context values has been specified.
__PUT_EXT_STRICT_NULLS | A Boolean value that requests the forced writing of properties to VT_NULL when appropriate. An error should be generated on failure.
__PUT_EXT_PROPERTIES | An array of strings that contains a list of the properties to be updated.
__PUT_EXT_ATOMIC | A Boolean value that indicates that all updates must succeed or the provider must revert back. There can be no partial success.


Moving an Instance

To move an instance from one class to another, an application must delete it from its original class and then create it in the new class. Windows Management Instrumentation (WMI) does not allow applications to move an instance by creating it in the new class and then updating it with the key of the original instance.

For example, suppose BaseClass is the parent class of SubClass1 and SubClass2. BaseClass is defined as follows:

class BaseClass
{
  [key] sint32 k;
}

An instance of SubClass1 exists with its key property set to 1. It is not valid for an application to call the IWbemServices::PutInstance method with the pInst parameter pointing to an instance of SubClass2 and k set to 1. Doing so causes the instance of SubClass1 to be implicitly deleted. Applications must first explicitly delete the SubClass1 instance before adding the instance of SubClass2.

In essence, once the class of an instance is established, an application can only change it by deleting it and recreating it.

Note WMI does not enforce this policy in the current version.


Clients of a High-Performance Provider

[This is preliminary documentation and subject to change.]

The Windows Management Instrumentation (WMI) High-Performance API (HiPerf API) greatly increases the speed at which WMI clients can obtain information from select high-performance WMI providers. Clients normally issue requests and retrieve data across process boundaries. To cross a process boundary into another address space, the data is marshalled, a relatively slow operation. The WMI Refresher increases data provider and client performance by retrieving data without crossing process boundaries.

If both client and server reside on the same machine, the WMI Refresher loads the HiPerf instance provider in-process to the client and copies data directly from provider objects into client objects. If client and server reside on different machines, the WMI Refresher increases performance by caching objects on the remote machine and transmitting minimal data sets to the client.

The WMI Refresher can also:

  • Automatically reconnect a client to a remote WMI Service if a network error occurs or the remote machine is rebooted
  • Load multiple objects and enumerators, which are provided by the same or different providers
  • Load local and remote objects. With a single call to IWbemRefresher::Refresh, a client can refresh both local and remote objects.


Writing a Client of a High-Performance Provider

[This is preliminary documentation and subject to change.]

This section describes how to write a high-performance application that rapidly determines how much virtual memory a given process uses.

This sample uses the HiPerf provider, Wbemperf.dll, which ships only with Microsoft® Windows® 2000. This provider supplies the performance counters used by the WMI version of the system monitor. The sample code is presented in a logical implementation sequence, followed by the complete listing.

To use the HiPerf interface, the client must first use IWbemLocator::ConnectServer to establish a connection to the winmgmt service on the desired logical machine (namespace). This connection is returned by ConnectServer in the form of an IWbemServices pointer, as is illustrated with this code fragment.

// Get the local locator object
IWbemServices* pNameSpace = NULL;
IWbemLocator* pWbemLocator = NULL;

CoCreateInstance( CLSID_WbemLocator, NULL,
    CLSCTX_INPROC_SERVER, IID_IWbemLocator, (void**) &pWbemLocator
);

// Connect to the desired namespace
bstrNameSpace = SysAllocString( L"\\\\.\\root\\cimv2" );

HRESULT hr = WBEM_S_NO_ERROR;

hr = pWbemLocator->ConnectServer(
    bstrNameSpace,      // NameSpace Name
    NULL,               // UserName
    NULL,               // Password
    NULL,               // Locale
    0L,                 // Security Flags
    NULL,               // Authority
    NULL,               // Wbem Context
    pNameSpace          // Namespace
);

if ( SUCCEEDED( hr ) )
{
    pNameSpace->Release();
}

SysFreeString( bstrNameSpace );
pWbemLocator->Release();

Before refreshing, you need to ensure that security is correctly set on the namespace, because the refresher will use those settings when it communicates with WMI. This setting is especially important in remote namespace scenarios.

// Set namespace security
IUnknown* pUnk = NULL;
g_pNameSpace->QueryInterface( IID_IUnknown, (void**) &pUnk );

CoSetProxyBlanket(
    g_pNameSpace, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL,
    RPC_C_AUTHN_LEVEL_CONNECT, RPC_C_IMP_LEVEL_IMPERSONATE,
    NULL, EOAC_NONE
);

CoSetProxyBlanket(
    pUnk, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL,
    RPC_C_AUTHN_LEVEL_CONNECT, RPC_C_IMP_LEVEL_IMPERSONATE,
    NULL, EOAC_NONE
);

// Cleanup the IUnknown
pUnk->Release();

The client then uses CoCreateInstance to create a WMI Refresher, and requests an IWbemRefresher interface. Using the QueryInterface method of this interface, the client finds the IWbemConfigureRefresher interface of the WMI Refresher.

IWbemRefresher* pRefresher = NULL;
IWbemConfigureRefresher* pConfig = NULL;

// Create a WMI Refresher and get a pointer to the
// IWbemConfigureRefresher interface.
CoCreateInstance( CLSID_IWbemRefresher, NULL,
    CLSCTX_INPROC_SERVER, IID_IWbemRefresher, (void**) &pRefresher
);

pRefresher->QueryInterface(
    IID_IWbemConfigureRefresher,
    (void**) &pConfig
);

To add a single object to the refresher, the client calls the IWbemConfigureRefresher::AddObjectByPath method, giving it the path to the object and the IWbemServices interface, which was obtained above. This call returns an IWbemClassObject interface for the given object.

IWbemClassObject* pObj = NULL;

// Add the instance we want refreshed
pConfig->AddObjectByPath(
    g_pNameSpace,
    "Win32_PerfRawData_PerfProc_Process.Name=\"Winmgmt\",
    0L,
    NULL,
    &pObj,
    NULL
);

The client then calls QueryInterface on the IWbemClassObject interface to obtain the IWbemObjectAccess interface, which represents the client-side mirror template of the object.

    // For quick property retrieval, we will use IWbemObjectAccess
    IWbemObjectAccess*    pAcc = NULL;
    pObj->QueryInterface( IID_IWbemObjectAccess, (void**) &pAcc );

    // We don't need this anymore
    pObj->Release();

Next, the client decides which properties(for example) it wishes to examine, and calls IWbemObjectAccess::GetPropertyHandle method to obtain the handle to each property. After a property handle has been obtained, it can be used for all instances of a particular class. Property handles can also be retrieved from class objects and used to retrieve property values from instance objects.

    // Get a property handle for the VirtualBytes property
    long lVirtualBytesHandle = 0;
    DWORD dwVirtualBytes = 0;

    pAcc->GetPropertyHandle(
        L"VirtualBytes",
        &lVirtualBytesHandle
    );

In a loop, the client first calls IWbemRefresher::Refresh by using the WMI Refresher pointer created in CoCreateInstance above. In this call, the WMI Refresher refreshes the client's object by using data supplied by the provider. The client can then use IWbemObjectAccess methods such as IWbemObjectAccess::ReadDWORD to retrieve the property name, data type, or value by passing it the property handle obtained above. The property information is refreshed each time through the loop.

Note You can add multiple objects, enumerators or both to a WMI Refresher. As a result, if there are any problems updating these objects or enumerators, the IWbemRefresher::Refresh method returns WBEM_S_PARTIAL_RESULTS, indicating that not all data was succesfully refreshed.

Also, if the object or enumerator being refreshed resides on a remote machine and if for example, the connection is lost by the remote machine being rebooted or a network error, the WMI Refresher will automatically try to reconnect to the remote machine. A client can prevent this reconnection by passing the flag, WBEM_FLAG_REFRESH_NO_AUTO_RECONNECT, in its call to the Refresh method on IWbemRefresher.

        // Refresh the object ten times and retrieve the value
        for( int x = 0; x < 10; x++ )
        {
            pRefresher->Refresh( 0L );

            pAcc->ReadDWORD( lVirtualBytesHandle, &dwVirtualBytes );

            printf( "Process is using %lu bytes\n", dwVirtualBytes );

            // Sleep for a second
            Sleep( 1000 );
        }

        // Cleanup all the object
        pAcc->Release();

        // We're done with these too
        pConfig->Release();
        pRefresher->Release();

Note Client applications should not touch their refreshable objects or enumerators during a refresh operation. Because IWbemObjectAccess interface has been optimized for speed, it is not intrinsically thread-safe. To protect objects across threads during IWbemObjectAccess method calls, the client must call the IWbemObjectAccess::Lock and IWbemObjectAccess::Unlock methods.

For best performance, a client should synchronize its threads so that there is no need to lock individual objects. In other words, reducing threads and synchronizing groups of objects for refresh operations provides the best overall performance.


High-Performance Application Code Sample Listing

[This is preliminary documentation and subject to change.]

The following code presents a complete sample application.

// Get the local locator object
IWbemServices* pNameSpace = NULL;
IWbemLocator* pWbemLocator = NULL;

CoCreateInstance( CLSID_WbemLocator, NULL,
    CLSCTX_INPROC_SERVER, IID_IWbemLocator, (void**) &pWbemLocator
);

// Connect to the desired namespace
bstrNameSpace = SysAllocString( L"\\\\.\\root\\cimv2" );

HRESULT hr = WBEM_S_NO_ERROR;

hr = pWbemLocator->ConnectServer(
    bstrNameSpace,      // NameSpace Name
    NULL,               // UserName
    NULL,               // Password
    NULL,               // Locale
    0L,                 // Security Flags
    NULL,               // Authority
    NULL,               // Wbem Context
    pNameSpace          // Namespace
);

if ( SUCCEEDED( hr ) )
{
    // Set namespace security
    IUnknown* pUnk = NULL;
    g_pNameSpace->QueryInterface( IID_IUnknown, (void**) &pUnk );

    CoSetProxyBlanket(
        g_pNameSpace, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL,
        RPC_C_AUTHN_LEVEL_CONNECT, RPC_C_IMP_LEVEL_IMPERSONATE,
        NULL, EOAC_NONE
    );

    CoSetProxyBlanket(
        pUnk, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL,
        RPC_C_AUTHN_LEVEL_CONNECT, RPC_C_IMP_LEVEL_IMPERSONATE,
        NULL, EOAC_NONE
    );

    // Cleanup the IUnknown
    pUnk->Release();

    IWbemRefresher* pRefresher = NULL;
    IWbemConfigureRefreshe* pConfig = NULL;

    // Create a WMI Refresher and get a pointer to the
    // IWbemConfigureRefresher interface.
    CoCreateInstance( CLSID_IWbemRefresher, NULL,
        CLSCTX_INPROC_SERVER, IID_IWbemRefresher,
        (void**) &pRefresher
    );

    pRefresher->QueryInterface( IID_IWbemConfigureRefresher,
        (void**) &pConfig );

    IWbemClassObject* pObj = NULL;

    // Add the instance we want refreshed
    pConfig->AddObjectByPath(
        g_pNameSpace,
        "Win32_PerfRawData_PerfProc_Process.Name=\"Winmgmt\",
        0L,
        NULL,
        &pObj,
        NULL
    );

    // For quick property retrieval, we will use IWbemObjectAccess
    IWbemObjectAccess* pAcc = NULL;
    pObj->QueryInterface( IID_IWbemObjectAccess, (void**) &pAcc );

    // We don't need this anymore
    pObj->Release();

    // Get a property handle for the VirtualBytes property
    long lVirtualBytesHandle = 0;
    DWORD    dwVirtualBytes = 0;

    pAcc->GetPropertyHandle( L"VirtualBytes",
        &lVirtualBytesHandle );

    // Refresh the object ten times and retrieve the value
    for( int x = 0; x < 10; x++ )
    {
        pRefresher->Refresh( 0L );
        pAcc->ReadDWORD( lVirtualBytesHandle, &dwVirtualBytes );

        printf( "Process is using %lu bytes\n", dwVirtualBytes );

        // Sleep for a second
        Sleep( 1000 );
    }

    // Cleanup all the objects
    pAcc->Release();

    // We're done with these too
    pConfig->Release();
    pRefresher->Release();

    pNamespace->Release();
}

SysFreeString( bstrNameSpace );
pWbemLocator->Release();


Adding Enumerators to the WMI Refresher

[This is preliminary documentation and subject to change.]

To add an enumerator to the WMI Refresher from a WMI client, the client calls the IWbemConfigureRefresher::AddEnum method and gives it the paths to the object and the IWbemServices interface. The WMI Refresher then returns a pointer to an IWbemHiPerfEnum interface.

    IWbemHiPerfEnum* pEnum = NULL;
    long lID;

// Add an enumerator to the refresher
pConfig->AddEnum(
    g_pNameSpace, L" Win32_PerfRawData_PerfProc_Process",
    0, NULL, &pEnum, &lID
);
pConfig->Release();

In a loop, the client first calls IWbemRefresher::Refresh. The client then provides an array of IWbemObjectAccess interface pointers to the IWbemHiPerfEnum::GetObjects method. By using these interfaces, the client can then use the IWbemObjectAccess methods to retrieve the property name, data type, or value of each instance of the enumerator. A single-property handle can be passed to each IWbemObjectAccess instance; the client must then call Release to release the interface pointers.

Note In this enumerated case, the first time the client gets the object set, it retrieves property handles from the first object and reuses the handles for the remainder of the refresh operations.

// Get a property handle for the VirtualBytes property
long lVirtualBytesHandle = 0,
lIDProcessHandle = 0;

DWORD dwVirtualBytes = 0,
dwProcessId = 0;

IWbemObjectAccess** apEnumAccess = NULL;
DWORD dwNumObjects = 0;

pAcc->GetPropertyHandle( L"VirtualBytes",
    &lVirtualBytesHandle );

// Refresh the object ten times and retrieve the value
for( int x = 0; x < 10; x++ )
{
    pRefresher->Refresh( 0L );

    DWORD    dwNumReturned = 0;

    pEnum->GetObjects(
        0L, dwNumObjects, apEnumAccess, &dwNumReturned
    );

    // If we weren't big enough, allocate a bigger buffer
    // and retry
    if ( dwNumReturned > dwNumObjects )
    {
       if ( NULL != apEnumAccess )
       {
           delete [] apEnumAccess;
       }

      apEnumAccess = new IWbemObjectAccess*[dwNumReturned];

      pEnum->GetObjects(
          0L, dwNumObjects, apEnumAccess, &dwNumReturned
      );

    }

    // First time through Get the handles
    if ( 0 == x )
    {
        apEnumAccess[0]->GetPropertyHandle( L"VirtualBytes",
            &lVirtualBytesHandle );
        apEnumAccess[0]->GetPropertyHandle( L"IDProcess",
            &lIDProcesssHandle );
    }

    for ( DWORD i = 0; i < dwNumReturned; i++ )
    {
        apEnumAccess[i}->ReadDWORD( lVirtualBytesHandle,
            &dwVirtualBytes );
        apEnumAccess[i}->ReadDWORD( lIDProcessHandle,
            &dwIDProcess );

        printf( "Process ID %lu is using %lu bytes\n",
            dwIDProcess, dwVirtualBytes );

        // Done with the object
        apEnumAccess[i]->Release();
        apEnumAccess[I] = NULL;
   }

   // Sleep for a second
   Sleep( 1000 );
}

delete [] apEnumAccess;

// exit loop here
pEnum->Release();
pRefresher->Release();
g_pNameSpace->Release();

Each time Refresh is called, the number of instances in the enumerator and the data for those instances are refreshed.


Partial-Instance Operations

Partial-instance operations allow you to set or retrieve individual properties of instances of CIM objects. Standard get or put operations retrieve or set all the properties in an instance regardless of size or usefulness. In many cases it is more expensive to retrieve all the properties of an instance than it is to retrieve just a few properties. Providers that support partial-instance operations can be much faster and use less computer resources because they only need to set or retrieve the properties that are required.


About Partial-Instance Operations

You can request partial-instance operations from client applications by setting specific values in context objects passed to calls that retrieve or set the values of class instances. Providers that support partial-instance operations provide class instances based on the values they receive.

Many of the classes in the CimV2 namespace that use the Win32 provider and support partial-instance operations. An example of a class that is optimized for per property operations is the Win32_CDRomDrive class.

Windows Management does not support per property operations on instances which reside in the repository and are not associated with a provider. Partial instance operations are only supported when the instance is supplied by a provider. For example, if you create an instance of a new class and attempt partial instance retrieval or update, Windows Management will retrieve or update the entire instance.

Providers are not required to support per property operations and may:

  • Provide more properties than the client requested.
  • Support per property operations for some classes but not others.
  • Support partial instance retrieval but not partial instance update or visa versa.


Provider Support for Partial Instance Operations

Providers are not required to support partial-instance operations. Providers that support partial instance operations must support all the semantics of each request. If a provider cannot support all the semantics in a request for a partial instance operation the provider must either process a complete instance, or return WBEM_E_UNSUPPORTED_PARAMETER. Suppose, for example, that a provider receives a request for a partial instance update operation that specifies __PUT_EXT_ATOMIC. If the provider supports partial instance update but not the __PUT_EXT_ATOMIC option, the provider must either update the entire instance or return the error WBEM_E_UNSUPPORTED_PARAMETER. The provider must not selectively support only some of the semantics of a request.

Providers that support per property operations must obey the following rules:

  • Providers must reuse the same context objects they receive. Windows Management uses the __GET_EXT_CLIENT_REQUEST named value to prevent deadlocks and removes this value before forwarding the context object to providers.
  • Providers that need to make a reentrant call to Windows Management that does not require partial instance operations should pass the same context object back without any modifications. Windows Management will receive the context object without the __GET_EXT_CLIENT_REQUEST value set and will delete all named values associated with partial instance operations from the context object before passing it to other providers to prevent them from receiving partial-instance gets intended for a different, unrelated object.
  • Providers that need to perform a reentrant partial-instance operation while carrying out a request it must set the missing __GET_EXT_CLIENT_REQUEST and properly clear or modify the properties in the __GET_EXT_PROPERTIES named value before sending the context object back into Windows Management with the reentrant call, since they are acting as clients.
  • Providers must not access the context object once it has been returned to Windows Management during a reentrant call, because the property lists or other values may be modified during reentrancy by other providers. Providers are only permitted to examine or modify the context object for the duration of the IWbemServices call that they implement. Once the call reenters or returns to Windows Management, the context object must not be accessed.


Using Partial Instance Operations

You can use partial instance operations with the COM API for WMI or the Scripting API for WMI. In either case you request partial instance operations by setting named values that are passed in the context parameter in calls that get or set the properties of CIM instances. Notice that the named values that are used in partial-updates always begin with a double underscore.


Partial Instance Retrieval

Client applications request partial-instance retrieval in get operations by specifying a context object containing Named Values Used in Partial Instance Retrieval Operations.

Client applications can request partial-instance retrieval operations by creating a context object and adding the named values __GET_EXTENSIONS and __GET_EXT_CLIENT_REQUEST, followed by either __GET_EXT_KEYS_ONLY or __GET_EXT_PROPERTIES. If the named value __GET_EXT_PROPERTIES is present, it should contain an array of strings that specify the names of the properties you want to retrieve.

You can then pass this context object in the context parameter of the methods that retrieve CIM objects.

The following sections show how to retrieve partial instances using the COM API for WMI and the Scripting API for WMI.


Retrieving Partial Instances Using the WMI Scripting API

You can request per property get operations from client applications that use the WMI Scripting API by setting up a SWbemNamedValueSet context object and adding the named values that describe what kind of partial instance operation you want. You can then pass this context object in the objwbemNamedValueSet parameter of the following methods:

  • SWbemServices.Get
  • SWbemServices.GetAsync
  • SWbemServices.InstancesOf
  • SWbemServices.InstancesOfAsync

For more information about the named values you can use with partial-instance get operations, see Named Values Used in Partial Instance Retrieval Operations.

Providers that support partial instance retrieval may return more properties than the client requests without returning the complete instance. The following example demonstrates this behavior by retrieving a limited number of properties from the Win32 provider class Win32_LogicalDisk. Although only 3 properties are requested, 9 of the 35 properties of this instance are actually returned.

Private Sub Get_Partial_Instance()
'*******************************************************************
'  Name    :  Get_Partial_Instance
'
'  Purpose :  This example shows how to get a partial instance
'             using context object and the Win32 Provider

'********************************************************************

Dim objservices As SWbemServices
Dim objInstance As SWbemObject
Dim inotnullprops As Integer
Dim objwbemNamedValueSet As SWbemNamedValueSet
aryProperties = Array("Caption", "Description", "DeviceId")

   On Error GoTo ErrorHandler         ' Enable error-handling routine
   Set objservices = GetObject _
          ("WinMgmts:{impersonationLevel=impersonate}!/root/cimv2")

  '*************       Create Named Value Set           *************
   Set objwbemNamedValueSet = _
       CreateObject("WbemScripting.SWbemNamedValueSet")
   objwbemNamedValueSet.Add "__GET_EXTENSIONS", True
   objwbemNamedValueSet.Add "__GET_EXT_CLIENT_REQUEST", True
   objwbemNamedValueSet.Add "__GET_EXT_PROPERTIES", aryProperties

 '*************     Perform partial instnance retrieval *************
   Set objInstance = objservices.Get _
         ("Win32_LogicalDisk.DeviceId=""C:""", , objwbemNamedValueSet)

 '*************     Count the properties returned       *************
    For Each Prop In objInstance.Properties_
      If Not IsNull(Prop.Value) Then
         inotnullprops = inotnullprops + 1
         MsgBox (Prop.name)
      End If
   Next Prop
MsgBox ("There were " & Str(inotnullprops) & " retrieved")
Set objwbemNamedValueSet = Nothing
Set objservices = Nothing
Set objInstance = Nothing
Exit Sub                                      ' Exit to avoid handler

ErrorHandler:                                ' Error-handling routine
     MsgBox "Error number: " & Str(Err.Number) _
          & vbNewLine & "Description: " & Err.Description, vbCritical
Exit Sub

End Sub


Retrieving Partial Instances Using the COM API for WMI

You can request partial instance retrieval operations from client applications that use the WMI COM API by setting up a IWbemContext context object and adding the named values that describe what kind of partial instance operation you want. You can then pass this context object in the pCtx parameter of the following methods

  • IWbemServices::GetObject
  • IWbemServices::GetObjectAsync
  • IWbemServices::CreateInstanceEnum
  • IWbemServices::CreateInstanceEnumAsync

For more information about the named values you can use with partial-instance get operations, see Partial-instance Named Values

The following example retrieves an instance of Win32_LogicalDisk the standard way and then performs a partial instance retrieval by requesting only the caption property of this class instance.

#include <stdio.h>
#include <comdef.h>
#include <wbemidl.h>

void main(void)
{
    HRESULT hr;
    _bstr_t bstrNamespace;
    IWbemLocator *pWbemLocator = NULL;
    IWbemServices *pServices = NULL;
    IWbemClassObject *pDrive = NULL;

    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);

    CoInitializeSecurity(NULL, -1, NULL, NULL,
                         RPC_C_AUTHN_LEVEL_CONNECT,
                         RPC_C_IMP_LEVEL_IMPERSONATE,
                         NULL, EOAC_NONE, 0);

    hr = CoCreateInstance(CLSID_WbemLocator, NULL,
                          CLSCTX_INPROC_SERVER, IID_IWbemLocator,
                          (void**) &pWbemLocator);
    if( FAILED(hr) )
    {
        CoUninitialize();
        printf("failed CoCreateInstance\n");
        return;
    }

    bstrNamespace = L"root\\cimv2";
    hr = pWbemLocator->ConnectServer(bstrNamespace, NULL, NULL, NULL,
                                     0, NULL, NULL, &pServices);
    if( FAILED(hr) )
    {
        pWbemLocator->Release();
        CoUninitialize();
        printf("failed ConnectServer\n");
        return;
    }
    pWbemLocator->Release();
    printf("Successfully connected to namespace\n");

    BSTR bstrPath = SysAllocString(L"Win32_LogicalDisk.DeviceID=\"C:\"");
   // *************************************************************//
   // Perform a full instance retrieval
   // *************************************************************//
    hr = pServices->GetObject(bstrPath,
                              0,0, &pDrive, 0);
    if( FAILED(hr) )
    {
        pServices->Release();
        CoUninitialize();
        printf("failed GetObject\n");
        return;
    }
    // Display the object
    BSTR  bstrDriveObj;
    hr = pDrive->GetObjectText(0, &bstrDriveObj);
    printf("%S\n\n", bstrDriveObj);

    pDrive->Release();
    pDrive = NULL;

   // *************************************************************//
   // Perform a partial instance retrieval
   // *************************************************************//

    IWbemContext  *pctxDrive; // Create context object
    hr = CoCreateInstance(CLSID_WbemContext, NULL,
                          CLSCTX_INPROC_SERVER, IID_IWbemContext,
                          (void**) &pctxDrive);
    if (FAILED(hr))
    {
        pServices->Release();
        pDrive->Release();
        CoUninitialize();
        printf("create instance failed for context object\n");
        return;
    }

    VARIANT  vExtensions;
    VARIANT  vClient;
    VARIANT  vPropertyList;
    VARIANT  vProperty;
    SAFEARRAY  *psaProperties;
    SAFEARRAYBOUND saBounds;
    LONG  lArrayIndex = 0;

    // Add named values to the contex object.
    VariantInit(&vExtensions);
    V_VT(&vExtensions) = VT_BOOL;
    V_BOOL(&vExtensions) = VARIANT_TRUE;
    hr = pctxDrive->SetValue(_bstr_t(L"__GET_EXTENSIONS"), 0, &vExtensions);
    VariantClear(&vExtensions);

    VariantInit(&vClient);
    V_VT(&vClient) = VT_BOOL;
    V_BOOL(&vClient) = VARIANT_TRUE;
    hr = pctxDrive->SetValue(_bstr_t(L"__GET_EXT_CLIENT_REQUEST"), 0, &vClient);
    VariantClear(&vClient);
    // Create an array of properties to return
    saBounds.cElements = 1;
    saBounds.lLbound = 0;
    psaProperties = SafeArrayCreate(VT_BSTR, 1, &saBounds);

    // Add the caption property to the array
    VariantInit(&vProperty);
    V_VT(&vProperty) = VT_BSTR;
    V_BSTR(&vProperty) = _bstr_t(L"Caption");
    SafeArrayPutElement(psaProperties, &lArrayIndex, V_BSTR(&vProperty));
    VariantClear(&vProperty);

    VariantInit(&vPropertyList);
    V_VT(&vPropertyList) = VT_ARRAY | VT_BSTR;
    V_ARRAY(&vPropertyList) = psaProperties;
    // put the array in the named value __GET_EXT_PROPERTIES
    hr = pctxDrive->SetValue(_bstr_t(L"__GET_EXT_PROPERTIES"), 0, &vPropertyList);
    VariantClear(&vPropertyList);
    SafeArrayDestroy(psaProperties);

    // Pass the context object as the pCtx parameter of GetObject
    hr = pServices->GetObject(bstrPath, 0, pctxDrive, &pDrive, 0);
    if( FAILED(hr) )
    {
        pServices->Release();
        CoUninitialize();
        printf("failed property GetObject\n");
        return;
    }
    // Display the object
    hr = pDrive->GetObjectText(0, &bstrDriveObj);
    printf("%S\n\n", bstrDriveObj);

    SysFreeString(bstrPath);

    VARIANT vFileSystem;
    // Attempt to get a property that was not requested.
    // The following should return a NULL property if
    // the partial instance retrieval succeded.

    hr = pDrive->Get(_bstr_t(L"FileSystem"), 0,
                       &vFileSystem, NULL, NULL);

    if( FAILED(hr) )
    {
        pServices->Release();
        pDrive->Release();
        CoUninitialize();
        printf("failed get for file system\n");
        return;
    }

    if (V_VT(&vFileSystem) == VT_NULL)
        printf("file system variable is null - expected\n");
    else
        printf("FileSystem = %S\n", V_BSTR(&vFileSystem));

    VariantClear(&vFileSystem);

    pDrive->Release();
    pctxDrive->Release();
    pServices->Release();
    pServices = NULL;    // MUST be set to NULL

When executed, this example outputs the following information. The first object description is from the full instance retrieval. The second object description is from the partial instance retrieval. The last section shows that you will get a NULL value if you request a property that was not requested in the original Getobject call

Successfully connected to namespace

instance of Win32_LogicalDisk
{
        Caption = "C:";
        Compressed = FALSE;
        CreationClassName = "Win32_LogicalDisk";
        Description = "Local Fixed Disk";
        DeviceID = "C:";
        DriveType = 3;
        FileSystem = "NTFS";
        FreeSpace = "3085668352";
        MaximumComponentLength = 255;
        MediaType = 12;
        Name = "C:";
        Size = "4581445632";
        SupportsFileBasedCompression = TRUE;
        SystemCreationClassName = "Win32_ComputerSystem";
        SystemName = "RBURNS";
        VolumeName = "rburns-c";
        VolumeSerialNumber = "7CB4B90E";
};

instance of Win32_LogicalDisk
{
        Caption = "C:";
        CreationClassName = "Win32_LogicalDisk";
        Description = "Local Fixed Disk";
        DeviceID = "C:";
        DriveType = 3;
        MediaType = 12;
        Name = "C:";
        SystemCreationClassName = "Win32_ComputerSystem";
        SystemName = "RBURNS";
};

file system variable is null - expected
Press any key to continue
}

For more information about the named values you can use with partial-instance get operations, see Named Values Used in Partial Instance Operations.


Partial Instance Updates

Partial instance updates allow client applications to modify the value of individual properties of CIM class instances. Client applications can request partial instance updates operations by setting up a context object and adding the named values __PUT_EXTENSIONS and __PUT_EXT_CLIENT_REQUEST, followed by __PUT_EXT_STRICT_NULLS, __PUT_EXT_PROPERTIES and __PUT_EXT_ATOMIC in any combination. Notice that the named values that are used in partial-updates always begin with a double underscore. If specified, the named value __PUT_EXT_PROPERTIES should contain an array of strings that contains the names of the properties you want to retrieve. You can then pass this context object in calls to methods that update CIMM instances.

The following sections show how to update partial instances using the COM API for WMI and the Scripting API for WMI.


Partial Instance Updates Using the WMI Scripting API

Clients that use the WMI Scripting API can request partial instance updates operations by setting up a SWbemNamedValueSet context object and adding the named values that describe the properties you want to retrieve. You can then pass this context object in the objwbemNamedValueSet parameter of the following methods:

• SWbemObject.Put_

• SWbemObject.PutAsync_


Partial Instance Updates Using the COM API for WMI

Client side applications that use the COM API for WMI can request partial-instance get operations by creating an IWbemContext context object and adding the named values __PUT_EXTENSIONS and __PUT_EXT_CLIENT_REQUEST, followed by __PUT_EXT_STRICT_NULLS, __PUT_EXT_PROPERTIES and __PUT_EXT_ATOMIC in any combination. You can then pass this context object in the pCtx parameter of the following methods

  • IWbemServices::PutInstance
  • IWbemServices::PutInstanceAsync


Named Values Used in Partial Instance Operations

The named values that are used in partial-instance operations always begin with a double underscore, like system classes and system properties. These values are different from system classes and system properties in that they can be modified and expected to be written into the context objects by users. The double-leading-underscores designate these values as having standardized semantics known to Windows Management.

Named Values Used in Partial Instance Retrieval Operations

Named Values Used in Partial Instance Update Operations


Named Values Used in Partial Instance Retrieval Operations

The following context values are associated with operations that retrieve properties from CIM object instances.

Named Value | Description
__GET_EXTENSIONS | A VT_BOOL set to VARIANT_TRUE, used to signal that partial-instance gets are being used. This allows a quick single check without having to enumerate the entire context object. If any of the other values are used, this one must be.
__GET_EXT_PROPERTIES | A SAFEARRAY of strings listing the properties to be retrieved. Cannot be simultaneously specified with __GET_EXT_KEYS_ONLY.
__GET_EXT_KEYS_ONLY | A VT_BOOL set to VARIANT_TRUE. Indicates that only key(s) should be provided in the returned object. Cannot be simultaneously specified with __GET_EXT_PROPERTIES.
__GET_EXT_CLIENT_REQUEST | A VT_BOOL set to VARIANT_TRUE. Indicates that the caller was the one who wrote the value into the context object and that it was not propagated from another dependent operation.

Note (1) The named values that are used in partial-instance operations always begin with a double underscore.

(2) The property name "*" is invalid and cannot be used in __GET_EXT_PROPERTIES.

(3) If both __GET_EXT_PROPERTIES and __GET_EXT_KEYS_ONLY are used in a context object, __GET_EXT_KEYS_ONLY will take precedence.

If the provider cannot comply with the per-property operation, it must either proceed as if the context object had not been used, or else return WBEM_E_UNSUPPORTED_PARAMETER. The provider should not comply with part of the request and ignore the other parts.


Named Values Used in Partial Instance Update Operations

The following context values are associated with operations that write properties to CIM object instances:

Named value | Description
__PUT_EXTENSIONS | A VT_BOOL set to VARIANT_TRUE. A value that indicates that one or more of the other context values has been specified. This allows a quick check of the context object inside the provider, to determine if partial-instance puts are being used.
__PUT_EXT_STRICT_NULLS | A VT_BOOL set to VARIANT_TRUE. Indicates the client intentionally has set properties to VT_NULL and expects the write to succeed. If the provider cannot set the values to NULL, an error should be reported.
__PUT_EXT_PROPERTIES | A SAFEARRAY of strings that contains a list of the property names to be updated. May be used alone or in combination with __PUT_EXT_PROPERTIES. The values are of course in the instance itself which is being written.
__PUT_EXT_ATOMIC | A VT_BOOL set to VARIANT_TRUE. Indicates that all updates must succeed simultaneously (atomic semantics) or the provider must revert back. There can be no partial success. May be used alone or in combination with other flags.
__PUT_EXT_CLIENT_REQUEST | A VT_BOOL set to VARIANT_TRUE. Set by the client during the initial request. Used to prevent reentrancy errors.

Client applications perform partial-instance put operations by adding __PUT_EXTENSIONS and __PUT_EXT_CLIENT_REQUEST to the context object followed by __PUT_EXT_STRICT_NULLS, __PUT_EXT_PROPERTIES and __PUT_EXT_ATOMIC in any combination, as they are not mutually exclusive.

The __PUT_EXT_CLIENT_REQUEST is used to prevent reentrancy errors. During the call Windows Management will look for the presence of this value. If found, it will be removed and the context object will be forwarded to the providers. If not found, all put extension values in the above matrix will be deleted. In this way, if any provider propagates the context object into a reentrant call into Windows Management while trying to satisfy a request, the put extensions will not be misinterpreted by other providers, because they will be removed.

If a provider must in turn execute partial-instance put extensions while carrying out a request, it must reuse the context object it receives from Windows Management, set the missing __PUT_EXT_CLIENT_REQUEST and properly clear or modify the above properties for the new request it is making before re-sending the context object back into Windows Management with the reentrant call.

If the provider cannot comply with the per-property operation, it must either proceed as if the context object had not been used, or else return WBEM_E_UNSUPPORTED_PARAMETER. The provider should not comply with part of the request and ignore the other parts. For example, the provider may not implement a put for 2 out of 10 properties, but ignore the __PUT_EXT_ATOMIC if it was specified.

Notes:
(1) Note that there are two leading underscores, not one.
(2) The property name "*" is invalid and cannot be used in __PUT_EXT_PROPERTIES.


Event Notification

Windows Management Instrumentation (WMI) events are occurrences that either correspond to conditions that arise within and outside the managed environment or to changes in the Common Information Model (CIM) repository. Event notifications are objects, typically instances of a subclass of the system class __Event.

After an event, an event provider sends notification of the event's occurrence to WMI. WMI then delivers the notification to one or more registered recipients, known as event consumers. These consumers can be local or remote.

WMI thus serves as the intermediary between event consumers and event providers. When an error occurs and WMI cannot deliver a notification, it sends an error message to the Microsoft® Windows NT®/Microsoft® Windows® 2000 Event Log service. On Windows 95/98 platforms, WMI sends the error message to the Wbemess.log file located in the \Windows\System\Wbem\Logs directory. To help determine the cause of the error, an administrator can check the event logs.

Event consumers register to receive events by sending a subscription using an event filter. The event filter uses an event query that describes the conditions under which the consumer should receive notifications. You create event queries using the WMI Query Language. Consumers send each event subscription to WMI, which holds the registration until the subscription is cancelled. Event consumers do not need information about the source of events and their corresponding notifications.

WMI identifies two types of consumers:

  • Temporary
  • Permanent

A temporary consumer receives event notifications only while it is active; its registration is temporary. Temporary consumers must reregister each time they start. For example, a user interface application might register to receive notifications about objects that it displays. This type of consumer need not receive notifications when it is inactive.

A permanent consumer receives event notifications whether or not it is active until its registration is explicitly cancelled. When WMI receives an event notification for a permanent consumer, WMI determines if the permanent consumer is active. If necessary, WMI starts the consumer before delivering the notification. Remote permanent consumers, however, either must be active or must have permissions set so that WMI can start the consumer on the remote computer. Not all platforms allow consumers to be started remotely. For more information, see Security and Authentication.

Permanent consumers generally perform a specific action, such as displaying a dialog box, when a notification is received. WMI forwards notifications of events to a permanent consumer only if they match an event filter that is part of the consumer. For more information on such filters, see Creating an Event Filter.

Event providers also register with WMI. Their registration specifies the types of events for which they can generate notifications. When a consumer registers to receive the types of events that an event provider can supply, WMI loads that event provider. The event provider then generates notifications either for all of its event types or only the type that matches the consumer's registration query, depending on the provider's implementation. The provider passes the generated notifications to WMI. WMI delivers notifications that match the queries sent by consumers and discards all others.

Note Under usual circumstances, each asynchronous event is delivered to the client one at a time. However, if a client cannot receive asynchronous event notifications as fast as they are arriving (due to network round-trip times, for instance), WinMgmt will start to use automatic batching which batches events into a single call.

Automatic batching helps if round-trip times are the problem (as they often are in high-throughput scenarios), but not if the client itself or the network bandwidth are at fault.

WMI classifies events as:

  • Intrinsic events
  • Extrinsic events
  • Timer events

Intrinsic and extrinsic events occur in response to changes in data, whereas timer events occur in response to consumer requests. For more information about these different event types, see Intrinsic and Extrinsic Events and Timer Events.


Intrinsic and Extrinsic Events

Windows Management Instrumentation (WMI) classifies most events as intrinsic or extrinsic. Intrinsic events occur in response to specific types of changes to data, namely changes in which a namespace, class, or class instance is created, modified, or deleted. WMI acquires information about these changes by inspecting the CIM repository. WMI creates intrinsic events for data stored statically in the CIM repository. Event providers create intrinsic events for dynamic data.

The changes that generate intrinsic events are represented by a set of system classes. When WMI or an event provider generates an intrinsic event, it creates an instance of the system class defined to represent that type of event. The instance is transmitted by WMI to all consumers that are registered for that event. Because intrinsic events map to system classes, they cannot be modified or extended.

The following table briefly describes the objects that WMI uses to report instrinsic events:

Instance Of | Description
__ClassCreationEvent | Notifies a consumer when a class is created.
__ClassDeletionEvent | Notifies a consumer when a class is deleted.
__ClassModificationEvent | Notifies a consumer when a class is modified.
__InstanceCreationEvent | Notifies a consumer when a class instance is created.
__InstanceDeletionEvent | Notifies a consumer when an instance is deleted.
__InstanceModificationEvent | Notifies a consumer when an instance is modified.
__NamespaceCreationEvent | Notifies a consumer when a namespace is created.
__NamespaceDeletionEvent | Notifies a consumer when a namespace is deleted.
__NamespaceModificationEvent | Notifies a consumer when a namespace is modified.

A consumer may need to be notified when a dynamic class instance is created, modified, or deleted, and there is no intrinsic event provider available. In these cases, the consumer registers for polling with WMI by specifying the WITHIN clause in its event query. When polling is requested, WMI monitors the dynamic instance for change and delivers the appropriate intrinsic event.

Whenever possible, providers should implement relevant instrinsic events. For example, an instance provider should implement the __InstanceCreationEvent. This prevents the performance loss which would result from the default polling for this event.

Extrinsic events occur in response to changes in data that is dynamic and external to WMI, such as a change to a key in the registry. Unlike intrinsic events, extrinsic events are neither represented by a fixed set of classes nor limited to the number of event classes that can be created. Because extrinsic events correspond to the wide range of changes that can occur within and outside a managed environment, WMI enables event providers to define the event classes that best describe the changes.

Providers derive extrinsic event classes from the __ExtrinsicEvent system class, a subclass of the system class __Event. WMI class inheritance facilitates good object-oriented design, but only instances of leaf event classes can be provided, that is, classes with no subclasses. Once a provider has registered to provide events for a class, no classes may be derived from that class.

In the following example, consider an event provider that needs to report security violations to one or more buildings. The following class might be defined for the extrinsic event representing a security violation:

class SecurityViolationEvent : __ExtrinsicEvent
{
  string   Building;            // Building where violation occurred
  sint32   EntranceNumber;      // Entrance where violation occurred
  datetime TimeOfDetection;         // Time of day of violation
};

To receive the security violation notifications, a consumer registers for the SecurityViolationEvent event type. Unless otherwise specified, a consumer receives notification of all security violations in all time periods and in all buildings. The event class also contains information that consumers can use to ask for more specific events. In the following example, the query registers the consumer for security violation events in building 24 only:

SELECT * FROM SecurityViolationEvent WHERE Building = 24;

Extrinsic events may also be explicitly generated and delivered by clients using the IWbemServices::QueryObjectSink method.


Timer Events

Timer events are events that either occur once at a particular time and day or repeatedly at regular intervals. Unlike intrinsic and extrinsic events, timer events must be explicitly set up by consumer instructions in order to occur. Notifications of timer events are sent by Windows Management Instrumentation (WMI) and can occur in any namespace.

Consumers represent timer events by system classes that derive from the __TimerInstruction class. The __TimerInstruction class contains a unique developer-assigned string that is used to identify the type of timer event. It also contains a value that specifies whether WMI should send a belated notification if the timer event occurs when WMI is unavailable.

The specific timer event classes derived from __TimerInstruction are:

  • __AbsoluteTimerInstruction, used to send absolute timer events, which occur on a specific date at a specific time.
  • __IntervalTimerInstruction, used to send interval timer events, which occur at regular intervals.

A consumer causes a timer event by sending an instance of __AbsoluteTimerInstruction or __IntervalTimerInstruction to WMI. WMI then generates the event.

To do so, WMI creates an instance of the __TimerEvent class and forwards it to the consumer. This class instance contains the identifier from the consumer's timer instruction. The instance also contains a value that specifies how many times the timer event notification should be sent during any interval when WMI cannot reach the consumer.


Temporary Event Consumers

A temporary event consumer is a component of Windows Management Instrumentation (WMI) that receives notifications of events only when it is active. When a temporary consumer shuts down, it no longer receives event notifications. Typical temporary consumers are user-interface applications requiring notification of events that affect data displayed to users. Temporary consumers register for events whenever registration is appropriate and cancel the registration when they no longer require notification. WMI holds the registrations in memory; they are not stored persistently.

A temporary consumer can receive notifications either asynchronously or synchronously. It is recommended that all temporary consumers register for asynchronous notifications. Asynchronous delivery of notifications improves performance by eliminating the need to poll for notification status, a time-consuming and inefficient technique. To receive asynchronous notifications, a consumer performs the following procedure.

To receive event notifications asynchronously

  1. Call the Component Object Model (COM) function CoInitializeEx to initialize COM, and then call the COM function CoInitializeSecurity immediately afterward to initialize COM security, as shown in the following code sample:
    void main(int argc, char **argv)
{
    CoInitializeEx (0, COINIT_MULTITHREADED);
    CoInitializeSecurity (NULL, -1, NULL, NULL,
      RPC_C_AUTHN_LEVEL_NONE, RPC_C_IMP_LEVEL_IMPERSONATE, NULL,
      EOAC_NONE, NULL);
...
}

    Because WMI handles security through COM, all temporary consumers that receive notifications asynchronously must call CoInitializeSecurity in their process. Calling CoInitializeSecurity grants WMI the permission to call into the consumer's process. For more information, see Security Considerations with Asynchronous Calls. For general information on working asynchronously, see the COM Fundamentals section of the Platform SDK.

  2. Create a sink object, an implementation of the IWbemObjectSink interface. WMI uses IWbemObjectSink to send event notifications as they occur and to report status on an asynchronous operation or event notification. For information about implementing this interface, see Implementing IWbemObjectSink.
  3. Call the IWbemServices::ExecNotificationQueryAsync method to register for events. The pResponseHandler parameter must point to the sink object created in the preceding step.

You should avoid calling IWbemServices::ExecNotificationQueryAsync multiple times to register for different classes of events using the same sink. Use a separate sink for each class of registered event. Having a dedicated sink simplifies processing and aids in maintenance, making it possible to cancel one registration without affecting the others.

To receive synchronous notifications, a consumer performs the following procedure.

To receive event notifications synchronously

  1. Call the IWbemServices::ExecNotificationQuery method to register for a particular class of events and to receive a pointer to an IEnumWbemClassObject interface. The lFlags parameter must be set to the flags WBEM_FLAG_RETURN_IMMEDIATELY and WBEM_FLAG_FORWARD_ONLY. The WBEM_FLAG_RETURN_IMMEDIATELY flag requests semisynchronous processing, and the WBEM_FLAG_FORWARD_ONLY flag requests a forward-only enumerator. For more information, see Making an Asynchronous Call and Enumerating Objects.
  2. Poll for notifications of registered events by making repeated calls to the IEnumWbemClassObject::Next method.

Temporary consumers that perform different tasks after notification of different event types need to make separate calls to ExecNotificationQuery or ExecNotificationQueryAsync for each event type. For example, a consumer might require notification of instance modification events for a specific class of device and of security violation events. In this case, the tasks the consumer performs upon receiving an instance modification event are much different than those the consumer performs upon receiving a security violation event. Thus, the consumer should make one call to IWbemServices::ExecNotificationQuery to register for instance modification events, and another call to IWbemServices::ExecNotificationQueryAsync to register for security violation events.

Temporary consumers should make each query as specific as possible. The goal of registration is to register to receive only the required notifications. Receiving superfluous notifications wastes processing and delivery time. It does not use the filtering ability of WMI to its fullest potential.

To cancel a registration that was created with ExecNotificationQueryAsync, a temporary consumer calls the IWbemServices::CancelAsyncCall method. Regardless of whether the call to CancelAsyncCall succeeds or fails, a temporary consumer must not delete its sink object until the object's reference count reaches zero. For more information, see Canceling an Asynchronous Operation.

To cancel a registration that was created with ExecNotificationQuery, a temporary consumer can release the enumerator that was received in the call. This enumerator is the pointer to IEnumWbemClassObject. Alternately, to cause event delivery to be stopped in all cases, a temporary consumer can release the IWbemServices pointer associated with the registration.


Permanent Event Consumers

Whether or not they are already running, permanent event consumers receive notifications. The event registration of a permanent consumer is stored in the Common Information Model (CIM) repository as an instance of a system class. This registration persists through operating system restarts and must be explicitly removed. When an event occurs, Windows Management Instrumentation (WMI) determines whether or not the permanent consumer is active. If the consumer is inactive, WMI uses information stored in the system registry to locate the consumer and then loads the consumer before attempting to deliver the notification.

You should implement a permanent consumer as a Component Object Model (COM) object. Depending on the platform, you can implement a permanent consumer as an in-process DLL, local server, or remote server. Permanent consumers implemented as in-process DLLs have a higher rate of delivery and lower system overhead than other permanent consumers. This is because with an in-process DLL there is no network traffic and interprocess communication overhead.

Permanent consumers implemented as local and remote servers require the distributed COM (DCOM) protocol. On Microsoft® Windows NT®/Microsoft® Windows® 2000, DCOM runs automatically. On the Windows 95 and Windows 98 platforms, DCOM must be installed.

Permanent consumers can be configured to receive their event notifications either asynchronously or synchronously. With asynchronous event notification, neither WMI nor the event provider is blocked while a notification is delivered. The sending thread is unrelated to the receiving thread. The disadvantage to asynchronous delivery is that a context switch occurs between the time the provider produces the event and the consumer receives it. For general information on working asynchronously, see the COM Fundamentals section of the Platform SDK. For more information on context switches, see Context Switches in the Base Services section of the Platform SDK.

With synchronous notification, the notification is delivered on the same thread that the event provider used to deliver the event to WMI. In this case, when an event provider sends a notification, the event provider is blocked until the notification is delivered. To request synchronous notification, you should set the DeliverSynchronously property in your consumer's instance of the __FilterToConsumerBinding system class to TRUE. For more information on how to do so, see Linking Event Filters with Logical Consumers.

Only if your consumer is extremely fast and can process an event in 100 microseconds or less should you consider supporting synchronous notification. Synchronous consumers that take too long to process events can seriously slow the delivery of events to all other consumers. Furthermore, they can inadvertently block the provider.

Note If a permanent consumer is implemented as an in-process COM server and must connect to WMI separately from the initialization process, then it must use the CLSID_WbemAdministrativeLocator class identifier to access the IWbemLocator interface in the call to the CoCreateInstance COM function that creates the consumer instance, as shown following:

IWbemLocator *pLoc = 0;

DWORD dwRes = CoCreateInstance(CLSID_WbemAdministrativeLocator, 0,
    CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *) &pLoc);

IWbemLocator obtains the initial namespace pointer to the Windows Management on a particular host computer. Failure to use the CLSID_WbemAdministrativeLocator identifier in the CoCreateInstance call results in an access denied error. For more information about making a connection to WMI, see Connecting to WMI.

For more information on permanent consumers, see the following topics:

  • Permanent Consumer Architecture
  • Creating a New Consumer Class
  • Creating a Logical Consumer
  • Creating an Event Filter
  • Linking Event Filters with Logical Consumers
  • Implementing an Event Consumer Provider


Permanent Consumer Architecture

The architecture of a permanent consumer consists of the following components:

  • A new event consumer class.
  • An instance or instances of the new consumer class, also known as a logical consumer.
  • One or more event filters.
  • One or more bindings between a logical event consumer and an event filter.
  • An event consumer provider, a WMI provider that includes:
    • An implementation of the IWbemEventConsumerProvider interface.
    • One or more COM objects known as physical consumers. Physical consumers contain one or more sinks, implementations of the IWbemUnboundObjectSink interface.

Note If a permanent consumer implements IWbemUnboundObjectSink, it need not implement IWbemEventConsumerProvider, and WMI does not call the IWbemEventConsumerProvider::FindConsumer method when it delivers events to instances of the consumer. Instead, WMI calls the IWbemUnboundObjectSink::IndicateToConsumer method of the physical consumer that implements IWbemUnboundObjectSink to deliver the event and the data.

Permanent consumers can create an unlimited number of logical consumers, event filters, and bindings. Because of the separation between these components, it is possible to send:

  • Events matching multiple filters to a single logical consumer.
  • Events from one event filter to multiple logical consumers.
  • Each type of event to the consumer that is dedicated to handling that particular event type.

The following diagram shows how these components interact with WMI and the order in which the interaction occurs. First, WMI receives a notification to deliver. WMI examines the notification to determine if it matches any of the registered event filters. Next, to notify logical consumers, WMI examines the bindings for all filters matching the notification.

For each logical consumer that is bound to a matching filter, WMI must then locate a corresponding event consumer provider. The event consumer provider bridges the gap between a logical consumer referenced in a binding and the physical consumer that is dedicated to receive the notification. To locate and start the event consumer provider for a particular logical consumer, WMI uses the information registered by the provider.

Once the event consumer provider is started, WMI calls the provider's IWbemEventConsumerProvider::FindConsumer method. FindConsumer creates an instance of the physical consumer. The physical consumer is the other COM object in the permanent consumer architecture. A physical consumer does not expose a class identifier (CLSID). It implements only the IWbemUnboundObjectSink interface to provide the processing necessary to handle the notification. To deliver the event, WMI calls the IWbemUnboundObjectSink::IndicateToConsumer method and includes a pointer to the logical consumer as a parameter.

WMI releases its pointer to the event consumer provider after a suitable time-out has elapsed.


Creating a New Consumer Class

Each permanent consumer creates a new consumer class that is derived from the __EventConsumer system class. This class describes the action to be taken upon receipt of the event notification. It provides data to be used by the physical consumer (sink) processing the notification. You can define as many properties for this class as are appropriate. For example, to forward events to all of the employees of a particular building, the following class including the e-mail addresses of the employees can be defined at the same time that the MyConsumer class is derived from __EventConsumer:

class EMailEventConsumer : __EventConsumer
{
  [key] string EmailAddress;
};

class MyConsumer : __EventConsumer
{
  [key] string Name;
};


Creating a Logical Consumer

Each instance of a new consumer class defined by a permanent consumer is known as a logical consumer. The property values of a logical consumer describe the action to be taken upon receipt of a notification. For each of the two consumer classes defined in the Creating a New Consumer Class topic, two logical consumers are defined:

// Logical consumers for the EMailEventConsumer class
// ==============================================

instance of  EMailEventConsumer
{
    EmailAddress = "someone@microsoft.com";
};

instance of  EMailEventConsumer
{
    EmailAddress = "user@host.domain.com";
};

// Logical consumers for the MyConsumer class
// ==============================================

instance of MyConsumer as $CONS1
{
    Name = "Consumer1";
};

instance of MyConsumer as $CONS2
{
    Name = "Consumer2";
};


Creating an Event Filter

An event filter is a component of the permanent consumer architecture that is an instance of the __EventFilter system class. Event filters describe the types of event to be delivered and the conditions under which they are delivered. As with events, event filters belong to a namespace. That is, each event filter works only on events that belong to the namespace to which the filter also belongs.

The Name property of the __EventFilter class is a string that uniquely identifies an event filter. A private scheme for filter naming can be used as long as no conflict arises with other filter naming schemes. A conflict must be avoided because adding an instance with a duplicate key value, such as a duplicate Name property, overwrites the old instance. Therefore, it is recommended that you use a globally unique identifier (GUID) for Name. If Name is left empty, WMI generates a GUID.

Event filters can specify intrinsic or extrinsic events. The following event filter requests an instance of a creation event, an intrinsic event, whenever a new instance of the DiskDrive class is created:

instance of __EventFilter
{
    Name = "{7ca44681-045f-11d1-ae97-00c04fb68820}";
    Query =
           "SELECT * FROM __InstanceCreationEvent "
           "WHERE TargetInstance.__CLASS = \"DiskDrive\"";
    QueryLanguage = "WQL";
};

The preceding query registers for instance creation events only for instances of the DiskDrive class. When instances of classes derived from the DiskDrive class are created, events are not generated. Consumers that must receive events that apply to any instance of the DiskDrive class and its derived classes must use the ISA operator in the WHERE clause of the event query, as shown following:

instance of __EventFilter
{
    Name = "{7ca44681-045f-11d1-ae97-00c04fb68820}";
    Query =
           "SELECT * FROM __InstanceCreationEvent "
           "WHERE TargetInstance ISA \"DiskDrive\"";
    QueryLanguage = "WQL";
};

Event queries for extrinsic events use similar syntax. The following queries register for the same extrinsic event under different conditions:

instance of __EventFilter as $FILT1
{
   Name  = "MyConsumer_Filter_A";
   Query = "SELECT * FROM MyEvent where Value >= 10";
   QueryLanguage = "WQL";
};

instance of __EventFilter as $FILT2
{
   Name  = "MyConsumer_Filter_B";
   Query = "SELECT * FROM MyEvent where Value < 10";
   QueryLanguage = "WQL";
};

Very precise filtering can be achieved with event queries using a variety of operators and extensions to Windows Management Instrumentation Query Language (WQL). Consumers should specify the most restrictive queries possible to avoid needless interprocess communication and network traffic. In other words, it is best to allow WMI to do as much filtering as possible. For more information, see Event Queries.


Linking Event Filters with Logical Consumers

Permanent consumers must associate a particular event filter with a particular logical consumer. To link the two types of components, a permanent consumer creates an instance of the __FilterToConsumerBinding system class. The __FilterToConsumerBinding class is an association class. By including reference properties in instances of __FilterToConsumerBinding, a permanent consumer links an event filter instance with a logical consumer instance. The Filter reference property of the __FilterToConsumerBinding instance indicates the event filter instance, the Consumer reference property the logical consumer instance.

A third property, DeliverSynchronously, determines whether event notifications should be delivered synchronously or asynchronously. Setting this property to TRUE requests synchronous delivery. Whether or not events are actually delivered synchronously depends on whether the associated event consumer provider supports synchronous delivery. Synchronous delivery should only be considered when the permanent consumer can process events within approximately 100 microseconds.

The following __FilterToConsumerBinding instance shows how to associate an instance of the EMailEventConsumer consumer class with a particular event filter. The object path of the logical consumer is its e-mail address, stored in the EmailAddress property of the class. The object path of the event filter is the GUID value stored in its Name property. Events are to be delivered asynchronously.

instance of __FilterToConsumerBinding
{
    Consumer = "EMailEventConsumer=\"mike@anywhere.com\"";
    Filter = "__EventFilter=
       \"{7ca44681-045f-11d1-ae97-00c04fb68820}\"";
    DeliverSynchronously=FALSE;
}

The following binding instances use aliases rather than explicit paths to bind two logical consumers to two event filters:

instance of __FilterToConsumerBinding
{
    Consumer =  $CONS1;
    Filter = $FILT1;
    DeliverSynchronously = FALSE;
};

instance of __FilterToConsumerBinding
{
    Consumer =  $CONS2;
    Filter = $FILT2;
    DeliverSynchronously = FALSE;
};

Each __FilterToConsumerBinding instance represents a registration for event notification. By deleting a binding, the registration is deactivated. Depending on the implementation, you may or may not also have to delete the logical consumer and event filter instances to deactivate registration.


Implementing an Event Consumer Provider

An event consumer provider is a WMI provider that supplies the link between a logical consumer and a physical consumer. A logical consumer is an instance of a static consumer class that provides data for processing an event. A physical consumer is a COM object that implements the IWbemUnboundObjectSink interface and receives the event and its associated data. WMI calls the physical consumer's IWbemUnboundObjectSink::IndicateToConsumer method to deliver the event and the data. Physical consumers are also known as sinks.

Implementing an event consumer provider involves the following tasks:

  • Implementing the IWbemProviderInit interface to support initialization. For more information about how to implement IWbemProviderInit, see Initializing a Provider.
  • Implementing the event consumer provider's primary interface, IWbemEventConsumerProvider, as described in Implementing IWbemEventConsumerProvider.
  • Supplying one or more implementations of the IWbemUnboundObjectSink interface, as described in Implementing IWbemUnboundObjectSink.
  • Registering with WMI. The registration process is standard for all providers. For more information, see Registering an Event Consumer Provider.


Implementing IWbemEventConsumerProvider

The IWbemEventConsumerProvider interface includes one unique method: FindConsumer. The first time an event must be delivered to a particular consumer, WMI calls this method to retrieve a pointer to the sink for that logical consumer. All subsequent occurrences of the event are sent to the sink provided in this initial call, through the sink's IWbemUnboundObjectSink::IndicateToConsumer method.

WMI releases the sink after a configurable period of time with no deliveries. If an event is targeted for a consumer that has been released, WMI calls FindConsumer again to acquire a new sink.

There are three approaches that an event consumer provider can take in implementing the FindConsumer method:

  • Providing a single sink (that is, a single implementation of the IWbemUnboundObjectSink interface) for all logical consumers.
  • Providing a different sink for each logical consumer.
  • Dividing logical consumers into groups and providing a different sink for each group.

Regardless of approach, you should not implement a sink in such a way that it depends on the existence of an event consumer provider. WMI releases an event consumer provider after a designated interval has elapsed between calls. Because the event consumer provider is needed only to supply pointers to sinks for new logical consumers, WMI can release it after all of the logical consumers have been serviced. The sinks, however, must remain to receive all of the events that occur.

Deciding which of the three approaches to take is important because the decision can affect performance and efficiency. The first approach, implementing a single sink, is the most efficient in terms of space because only one COM object is stored in memory. The second approach is the opposite of the first; it optimizes performance. It saves time to have a dedicated sink ready to receive an event as it occurs. The third approach is a hybrid, a compromise between the first two approaches.

To illustrate the trade-offs between implementation strategies, consider an event consumer provider that supplies sinks for logical consumers that log messages to files. With the first strategy, the event consumer provider supplies the same sink for all events that arrive for all logical consumers. The single sink bears the responsibility for examining the data included with each logical consumer and determines how to proceed. Most likely, each event received involves opening a log file, logging the message, and closing the file. While efficient in terms of space, this strategy involves a significant amount of processing time.

The second strategy is faster, but less efficient because of its cost in terms of memory. The event consumer provider supplies a different sink for each logical consumer. Because each sink maintains its own log file, the file can always be open and ready to log messages as events occur. The sink can then close the file when WMI releases the sink after a time-out, providing efficient performance both in high-speed and in low-speed delivery scenarios.

The third, hybrid approach can involve having a few different log files, possibly with each tied to the type of message to be logged. As a compromise between the first two strategies, multiple COM objects handle multiple open files. An event consumer provider taking this approach reads the log file name during the FindConsumer call, opens the file, and returns the sink that logs all messages into this file. The provider closes the file on the last call to the Release method. With this approach, the consumer preserves efficiency as it has information on exactly which file to use without searching or opening a file anew. Also, the consumer can save memory by combining sinks that log different messages to the same file.

Following is an example implementation of an event consumer provider. First, the code declares a class derived from both the IWbemEventConsumerProvider interface and the IWbemProviderInit interface. The object implementing this class contains the provider's initialization methods and provider-specific methods. The code omits private member functions, constructors, destructors, and methods of the IUnknown class for brevity.

class CMyEventConsumer : public IWbemEventConsumerProvider,
    public IWbemProviderInit
{
public:
//
    // IUnknown members
    //
    STDMETHODIMP         QueryInterface(REFIID, LPVOID *);
    STDMETHODIMP_(ULONG) AddRef(void);
    STDMETHODIMP_(ULONG) Release(void);

    virtual HRESULT STDMETHODCALLTYPE CMyEventConsumer::Initialize(
        /* [in] */ LPWSTR pszUser,
        /* [in] */ LONG lFlags,
        /* [in] */ LPWSTR pszNamespace,
        /* [in] */ LPWSTR pszLocale,
        /* [in] */ IWbemServices __RPC_FAR *pNamespace,
        /* [in] */ IWbemContext __RPC_FAR *pCtx,
        /* [in] */ IWbemProviderInitSink __RPC_FAR *pInitSink
        );

};

HRESULT CMyEventConsumer::FindConsumer(
   /* [in] */ IWbemClassObject __RPC_FAR *pLogicalConsumer,
   /* [out] */ IWbemUnboundObjectSink __RPC_FAR *__RPC_FAR *ppConsumer
   )
{
   // Examine the logical consumer to see which one it is.
   // ====================================================

   VARIANT v;
   VariantInit(&v);

   HRESULT hRes = WBEM_E_NOT_FOUND;
   *ppConsumer = 0;

   pLogicalConsumer->Get(_bstr_t(L"Name"), 0, &v, 0, 0);

   // Decide which of the two logical consumers to send back.
   // =======================================================

   if (_wcsicmp(V_BSTR(&v), L"Consumer1") == 0)
   {
      hRes =  m_pConsumer1->
         QueryInterface(IID_IWbemUnboundObjectSink, (LPVOID*)ppConsumer);
   }
   else if (_wcsicmp(V_BSTR(&v), L"Consumer2") == 0)
   {
      hRes =  m_pConsumer2->
          QueryInterface(IID_IWbemUnboundObjectSink, (LPVOID*)ppConsumer);
   }

   VariantClear(&v);
   return hRes;
}

Next, the example codes the IWbemProviderInit interface by simply implementing the Initialize method of the preceding class:

HRESULT CMyEventConsumer::Initialize(
    /* [in] */ LPWSTR pszUser,
    /* [in] */ LONG lFlags,
    /* [in] */ LPWSTR pszNamespace,
    /* [in] */ LPWSTR pszLocale,
    /* [in] */ IWbemServices __RPC_FAR *pNamespace,
    /* [in] */ IWbemContext __RPC_FAR *pCtx,
    /* [in] */ IWbemProviderInitSink __RPC_FAR *pInitSink
    )
{
    pInitSink->SetStatus(WBEM_S_INITIALIZED, 0);

// Optionally, examine the namespace, locale, and so on
// being used.

    return WBEM_S_NO_ERROR;
}

The other primary method to implement is FindConsumer. In the implementation following, assume two sinks exist for receiving events, one for each of the two different event filters that are registered. To determine which sink to send back to WMI, the code examines the incoming logical consumer object, an instance of the IWbemClassObject class. For more information on the sink implementation, see Implementing IWbemUnboundObjectSink.

HRESULT CMyEventConsumer::FindConsumer(
   /* [in] */ IWbemClassObject __RPC_FAR *pLogicalConsumer,
   /* [out] */ IWbemUnboundObjectSink __RPC_FAR *__RPC_FAR *ppConsumer
   )
{
    // Examine the logical consumer to see which one it is.
    // ====================================================

    VARIANT v;
    VariantInit(&v);

    HRESULT hRes = WBEM_E_NOT_FOUND;
    *ppConsumer = 0;

    pLogicalConsumer->Get(_bstr_t(L"Name"), 0, &v, 0, 0);

    // Decide which of the two logical consumers to send back.
    // =======================================================

    if (_wcsicmp(V_BSTR(&v), L"Consumer1") == 0)
    {
        m_pConsumer1->AddRef();
        *ppConsumer = m_pConsumer1;
        hRes = WBEM_S_NO_ERROR;
    }
    else if (_wcsicmp(V_BSTR(&v), L"Consumer2") == 0)
    {
        m_pConsumer1->AddRef();
        *ppConsumer = m_pConsumer2;
        hRes =WBEM_S_NO_ERROR;
    }

    VariantClear(&v);
    return hRes;
}


Implementing IWbemUnboundObjectSink

Implementing a sink involves implementing the IWbemUnboundObjectSink interface. The IWbemUnboundObjectSink interface has one unique method: IndicateToConsumer. IndicateToConsumer contains the code for processing the events that the sink receives. IndicateToConsumer has three parameters: a pointer to the logical consumer, an array of objects, and the number of objects in the array. Because each object in the array corresponds to a separate event, each object must be treated separately.

To support synchronous notification, a sink must be able to complete its event processing in less than 20 milliseconds. Extremely fast event consumer providers that support synchronous notification must not hold onto the pointer to the IWbemClassObject interface or increment the pointer's reference count in the IndicateToConsumer method. If the class object defined by IWbemClassObject is required beyond the lifetime of the IndicateToConsumer call, make a copy of the object. However, if there must be long-term access to the information pointed to by the IWbemClassObject pointer, it is recommended that the event consumer provider not support synchronous notification. Event consumer providers indicate the type of notification that they support when they complete their registration.

Following is an example implementation of a sink, a sink that logs events to a text file as they arrive. The constructor accepts the name of the text file:

class CMySink : public IWbemUnboundObjectSink
{
    ULONG               m_cRef;
    char               *m_pszLogFile;

public:
    CMySink(char *pLogFile) { m_cRef = 0; m_pszLogFile = strcpy(new   char[128], pLogFile); }

  ~CMySink() { delete [] m_pszLogFile; }

    //
    // IUnknown members
    //
    STDMETHODIMP         QueryInterface(REFIID, LPVOID *);
    STDMETHODIMP_(ULONG) AddRef(void);
    STDMETHODIMP_(ULONG) Release(void);

    virtual HRESULT STDMETHODCALLTYPE IndicateToConsumer(
        /* [in] */ IWbemClassObject __RPC_FAR *pLogicalConsumer,
        /* [in] */ long lNumObjects,
        /* [size_is][in] */ IWbemClassObject __RPC_FAR *__RPC_FAR *apObjects
        );
};

The method of interest here is the IndicateToConsumer method, which WMI calls whenever an actual event is delivered. The following implementation examines the event class properties Name and Value and then writes them to a text file:

HRESULT CMySink::IndicateToConsumer(
   /* [in] */ IWbemClassObject __RPC_FAR *pLogicalConsumer,
   /* [in] */ long lNumObjects,
   /* [size_is][in] */ IWbemClassObject __RPC_FAR *__RPC_FAR *apObjects
   )
{
    FILE *f = fopen(m_pszLogFile, "at");

    for (long i = 0; i < lNumObjects; i++)
    {
        IWbemClassObject *pObj = apObjects[i];

        VARIANT v;
        VariantInit(&v);

        // Verify the events are of the class expected.
        // =============================================

        pObj->Get(_bstr_t(L"__CLASS"), 0, &v, 0, 0);

        if (_wcsicmp(V_BSTR(&v), L"MyEvent") != 0)
        {
            VariantClear(&v);
            continue;
        }

        VariantClear(&v);

        // Get the properties and log them to a file.
        // ==========================================

        VARIANT v2;
        VariantInit(&v2);

        pObj->Get(_bstr_t(L"Name"), 0, &v, 0, 0);
        pObj->Get(_bstr_t(L"Value"), 0, &v2, 0, 0);

        fprintf(f, "Event %S value = %d\n", V_BSTR(&v), V_I4(&v2));

        VariantClear(&v);
        VariantClear(&v2);
    }

    fclose(f);

    return WBEM_S_NO_ERROR;
}


Implementing an Event Provider

An event provider is a Windows Management Instrumentation (WMI) provider that sends notifications of events to WMI. WMI forwards the notifications to registered consumers. All event providers implement two interfaces:

  • IWbemProviderInit
  • IWbemEventProvider

Providers should implement IWbemProviderInit in order to support initialization. WMI calls the IWbemProviderInit::Initialize method to request that the event provider complete its initialization tasks. Initialize has several input parameters, including a pointer to the IWbemServices interface, a pointer to the IWbemContext interface, and a pointer to the IWbemProviderInitSink interface.

Event providers can use the IWbemServices pointer to request services such as the retrieval of class definitions. Event providers should increment the reference count on the IWbemServices pointer by calling the IWbemServices::AddRef method, AddRef being the standard COM method for incrementing a reference count, and returning immediately. To send events, the provider must spawn a separate thread. For more information, see Initializing a Provider.

Event providers must not make any class changes while servicing a client call. They also cannot issue any event-related calls, such as a call modifying an event filter.

If an event provider needs to make changes to the namespace in which it is installed, it must use the pointer given to it in the Initialize call or risk deadlock. If an event provider makes an event-registration change in the namespace in which it is installed, the registration will be processed by WMI asynchronously, and is not guaranteed to be active by the time the call returns.

Providers use the IWbemEventProvider interface to generate event notifications. WMI calls a provider's IWbemEventProvider::ProvideEvents method to obtain a pointer to a sink object, which is an implementation of the IWbemObjectSink interface. When the event provider is ready to generate a notification, it calls the IWbemObjectSink::Indicate method.

Note Event providers should never call the IWbemObjectSink::SetStatus method.

Providers place the notifications generated through IWbemEventProvider in event objects, implemented as entries in an array of IWbemClassObject interfaces represented by the Indicate parameter ppObjArray. Event providers that must supply many notifications rapidly for the same class of event should use a single event object rather than creating a unique one for each notification. WMI never holds onto an event object past the completion of the Indicate call.

When an event provider calls Indicate to provide an event, the call may fail with WBEM_E_SERVER_TOO_BUSY. The provider may choose to respond to this message by re-firing the event.

Note Providers must process any requests that CIMOM has issued to them (such as CancelQuery) before re-firing an event. If not, re-firing the event might cause a live-lock, which would keep the event from ever being accepted.

Event providers must increment the reference count for the sink by calling its IWbemObjectSink::AddRef method. WMI introduces no special requirements for AddRef above and beyond the COM standard.

Some event providers also implement the IWbemEventProviderQuerySink interface. Supporting IWbemEventProviderQuerySink helps providers avoid sending useless notifications; this can improve performance. Typically, only those event providers responsible for notifications that require a lot of time to generate implement IWbemEventProviderQuerySink. A provider that supports the IWbemEventProvider and IWbemEventProviderQuerySink interfaces must ensure that its implementation of the IUnknown::QueryInterface method returns pointers to both interfaces.

Whenever WMI receives a new or modified event query from a consumer, WMI calls the IWbemEventProviderQuerySink::NewQuery method to echo the query to the responsible event provider. The event provider can examine the query to see what event notifications are actually being requested. The provider then generates only the notifications requested.

Note IWbemEventProviderQuerySink::NewQuery may be called before IWbemEventProvider::ProvideEvents.

For example, suppose an event provider supports instance modification events for the class EmailClass. EmailClass has three properties: sender, recipient, and subject. The event provider monitors the state of these properties for each class instance. If one of the properties changes, the provider generates an event.

In most scenarios, WMI is responsible for passing on only the notifications that have been requested. For example, if a particular consumer needs information on changes to the sender property, WMI ignores notifications that report changes to recipient and subject.

Event providers that implement IWbemEventProviderQuerySink can save WMI from the time-consuming process of sorting through notifications and discarding unnecessary ones. IWbemEventProviderQuerySink::NewQuery supplies an event provider with the information that it needs to generate only those notifications required for registered consumers. Each query is assigned an identifier that can be used for tracking. The event provider responsible for instance modification events for the class EmailClass can be set up to generate notifications only for sender. When the provider receives a query requesting notification of changes to the subject property, it can start generating those notifications. In this scenario, WMI does not have to discard the notifications that report recipient changes only.

Although WMI calls the methods of IWbemEventProvider only once after an event provider becomes active, WMI calls the methods of IWbemEventProviderQuerySink continuously, as appropriate. The provider can ignore all calls to IWbemEventProviderQuerySink methods as needed. This point is very important; supporting IWbemEventProviderQuerySink indicates that a provider has agreed to supply at least the events requested by queries.

A provider can also generate more events than are requested. WMI filters the events as appropriate. This functionality means providers can implement IWbemEventProviderQuerySink and optimize processing without addressing all parts of the Windows Management Instrumentation Query Language. For instance, if a provider does not specifically handle a particular query, the provider can generate all possible events for the query.

When a consumer cancels registration, WMI calls the event provider's IWbemEventProviderQuerySink::CancelQuery method. CancelQuery includes the identifier of the canceled event query in order to locate the registration to cancel.


Out-of-memory avoidance

Windows Management Instrumentation

Out of Memory Avoidance

The queue of asynchronous events destined to a client has the potential to grow exceptionally large. Because of this, WinMgmt implements a system-wide policy to avoid running out of memory. This policy is designed in such a manner that it has little or no impact on the systems performance. There are two parameters that can be used to tune this performance:

  • Setting the Minimum and Maximum Threshold Properties
  • Setting the Maximum Wait on Events


Setting the Minimum and Maximum Threshold Properties

Threshold properties are used to set limits on minimum and maximum values for out of memory avoidance. The minimum value indicates when to start slowing event notification, using a sleep call, and the maximum value indicates when to start dropping events.

These modifiable values are determined by the following properties in the Win32_WMISetting class:

Properties | Default value
LowThresholdOnEvents | 1000000 (10 MB)
HighThresholdOnEvents | 2000000 (20 MB)


Setting the Maximum Wait on Events

In addition to setting the minimum and maximum threshold properties, you can also modify the maximum amount of time the system should wait before dropping events. This modifiable value is determined by the following property in the Win32_WMISetting class.

Properties | Default value
MaxWaitOnEvents | 2000 (2 seconds)


Creating a WMI Application in MFC

In the following tutorial, you will:

  • Create a simple Windows Management Instrumentation (WMI) client application.
  • Learn to create and connect to a WMI namespace.
  • Find and display all instances of a class.
  • Display the properties of a class instance.

The source code for this tutorial can be found in the WbemClient project in the Program Files\WMI\Samples\vc\SimpleClient folder of the WMI SDK.

Note The sample code in this tutorial was built with Microsoft® Visual C++® version 6.0 running under Microsoft® Visual Studio® 97. Other integrated development environments (IDEs) that support MFC could be used to build this code.


Creating the Project

  1. Open Microsoft® Visual Studio® and select File, New.
  2. Select the Projects tab from the New dialog box and then select the MFC AppWizard for building executable files.
  3. Choose a Location for your program and give it the Project name of WbemClient.

  4. Create a dialog-based application without Microsoft® ActiveX® controls support. Accept all other defaults. Your final MFC AppWizard screen should look like this.

  5. Build the project and verify that it runs.


Initializing WMI

Add the following OLE initialization code to the start of the InitInstance function of the CWbemClientApp class.

    // Initialize OLE libraries
    if (!AfxOleInit())
    {
        AfxMessageBox(_T("Failed to Initialize OLE"));
        return FALSE;
    }

This call to AfxOleInit loads the OLE support (Ole32.dll) and invokes the CoInitialize function. This process initializes the Component Object Model (COM) library so that you can make calls to any COM objects, including Windows Management Instrumentation (WMI) objects.


Adjusting the Security Level

A good rule of thumb for Windows Management Instrumentation (WMI) programming is to follow a call to Colnitialize with a call to ColnitializeSecurity. If you don't, your next call to a Distributed Component Object Model (DCOM) service will use the default security levels, which may be incorrect for WMI programming. You might wait 2 minutes or more, only to find out that your call has failed. To view your default security levels, run the Dcomcnfg.exe program in your \Systems directory.

The Authentication Level is normally set to Connect, and the Impersonation Level is set to Identify. A WMI program must programmatically change these levels.

To modify security levels

  1. Add the InitSecurity function to the CWbemClientApp class by adding the following highlighted text to WbemClient.h.
    class CWbemClientApp : public CWinApp{
public:
    CWbemClientApp();

    bool InitSecurity();
  2. Add this function to the end of the implementation file, WbemClient.cpp.
    // CWbemClientApp security

// Initialize COM security for DCOM services.
// Returns true if successful.
bool CWbemClientApp::InitSecurity(void)
{
    // Adjust the security to allow client impersonation.
    HRESULT hres = CoInitializeSecurity
        (NULL, -1, NULL, NULL,
        RPC_C_AUTHN_LEVEL_NONE,
        RPC_C_IMP_LEVEL_IMPERSONATE,
        NULL, 0, 0);

    return (SUCCEEDED(hres));
}

    This step calls CoInitializeSecurity with an authentication level of NONE and an impersonation level of IMPERSONATE.

    Note For the least demanding security, set the authentication level to RPC_C_AUTHN_LEVEL_NONE and the impersonation level to RPC_C_IMP_LEVEL_IMPERSONATE.

  3. To enable the DCOM preprocessor support, add the definition, _WIN32_DCOM, to the project C++/Preprocessor settings found in All Configurations.

  4. The DCOM macro support is defined in the file Objidl.h, which is included by the header file Objbase.h, which is in turn included in the file Afxdisp.h. Add this boldfaced line to the beginning of the file Stdafx.h:
    #include <afxwin.h>         // MFC core and standard components
#include <afxext.h>         // MFC extensions
#include <afxdisp.h>        // MFC OLE automation classes
  5. Add the highlighted lines to the InitInstance function, right after the call to AfxOleInit:
        // Initialize OLE libraries
    if (!AfxOleInit())
    {
        AfxMessageBox(_T("Failed to Initialize OLE"));
        return FALSE;
    }
    if (!InitSecurity())
    {
        AfxMessageBox(_T("Failed to adjust security"));
        return FALSE;
    }
  6. Recompile and run the project.


Adding a Trace Window

To add a Trace window

  1. From the Resource Editor, open the IDD_WBEMCLIENT_DIALOG dialog box in the design window.
  2. Change the identifier of the OK button to IDC_CONNECT and its caption to "&Connect".
  3. Change the caption of the Cancel button to E&xit.
  4. Remove the ToDo label, add a Namespace label, and follow it with an edit box with the identifier, IDC_NAMESPACE.
  5. Add a list box with the ID of IDC_OUTPUTLIST, turning the Sort option off.

    Your completed dialog box should look something like this.

  6. Use the class wizard Member Variables tab to connect the IDC_OUTPUTLIST control to a CWbemClientDlg class list box member variable named m_outputList.
  7. Connect IDC_NAMESPACE to a Cstring member variable named m_namespace.

    You will use the edit box to select the Windows Management Instrumentation (WMI) namespace and the list box to trace the progress of the WMI connection.

  8. For now, initialize m_namespace in the CWbemClientDlg constructor by using the following code.
    CWbemClientDlg::CWbemClientDlg(CWnd* pParent /*=NULL*/)
    : CDialog(CWbemClientDlg::IDD, pParent)
{
    //{{AFX_DATA_INIT(CWbemClientDlg)
    m_namespace = _T("\\\\.\\root\\cimv2");
    //}}AFX_DATA_INIT
  9. Use the class wizard to attach the CWbemClientDlg::OnConnect function to the Connect button.
  10. Add the following code to the function.
    // CWbemClientDlg connection

void CWbemClientDlg::OnConnect()
{
    // Indicate success.
    m_outputList.ResetContent();
    m_outputList.AddString(_T("Connected to namespace"));
}
  11. Build the project and test your code.

    Clicking Connect should write the message, "Connected To Namespace" in the list box.


Connecting to WMI

You will need to use the IWbemLocator interface to obtain the initial namespace pointer to the Common Information Model (CIM) repository interface on your machine. After you obtain a pointer to this interface, you can use the ConnectServer method to obtain the IWbemServices pointer, which you can use to access Windows Management Instrumentation (WMI) itself.

To create an instance of the IWbemLocator interface, you need only to call CoCreateInstance.

    CoCreateInstance(CLSID_WbemLocator, ...

The IWbemLocator object you obtain is always an in-process Component Object Model (COM) server.

Note If you are accessing WMI as an in-process provider of any type or as an in-process consumer, you must use CLSID_WbemAdministrativeLocator instead. This is an alternate CLSID reserved for in-process subcomponents of WMI that require no authentication.

Both CLSID_WbemLocator and CLSID_WbemAdministrativeLocator are defined in the Wbemcli.h file located in the \Include directory of the WMI SDK.

To connect to WMI

  1. Add a path to this directory to the project C++/Preprocessor settings located in All Configurations.

  2. Add a path to the WMI SDK lib directory to the project Link/Input settings. Include Wbemuuid.lib and exclude Libc.lib.

    The Wbemuuid.lib library contains the constants that define the various interface IDs (IIDs) for WMI.

    Note If Wbemuuid.lib does not exist in the \Wbem\lib directory, and if Wbemcli.h does not appear in the Wbem\Include directory, you will have to build them yourself. From the DOS prompt, navigate to the \Wbem\Include directory, and type nmake <Enter>.

  3. Include the Wbemcli.h file in the WbemClientDlg.h header file as follows.
    #if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000

#include "..\\..\\..\\Include\\wbemcli.h"
  4. Add a member variable to the CWbemClientDlg class.
    protected:
    virtual void DoDataExchange(CDataExchange* pDX);
    //}}AFX_VIRTUAL
private:
    IWbemServices *m_pIWbemServices;

// Implementation
protected:
    CWbemClientDlgAutoProxy* m_pAutoProxy;
  5. Initialize m_pIWbemServices in the CWbemClientDlg constructor.
            //{{AFX_DATA_INIT(CWbemClientDlg)
        m_namespace = _T("\\\\.\\root\\cimv2");
        //}}AFX_DATA_INIT
        // Note that LoadIcon does not require a subsequent DestroyIcon in Win32
        m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
        m_pIWbemServices = NULL;
}
  6. Replace the code to the CWbemClientDlg::OnConnect function with the following code.
    //////////////////////////////////////////////////////////////////////
// CWbemClientDlg connection

void CWbemClientDlg::OnConnect()
{
    // Create an instance of the WbemLocator interface.
    IWbemLocator *pIWbemLocator = NULL;

    if(CoCreateInstance(CLSID_WbemLocator,
        NULL,
        CLSCTX_INPROC_SERVER,
        IID_IWbemLocator,
        (LPVOID *) &pIWbemLocator) == S_OK)
    {
        // If already connected, release m_pIWbemServices.
        if (m_pIWbemServices)  m_pIWbemServices->Release();

        // Using the locator, connect to WMI in the given namespace.
        BSTR pNamespace = m_namespace.AllocSysString();

        if(pIWbemLocator->ConnectServer(pNamespace,
                                NULL,    //using current account
                                NULL,    //using current password
                                0L,      // locale
                                0L,      // securityFlags
                                NULL,    // authority (NTLM domain)
                                NULL,    // context
                                &m_pIWbemServices) == S_OK)
        {
            // Indicate success.
            m_outputList.ResetContent();
            m_outputList.AddString(_T("Connected To Namespace"));
        }
        else AfxMessageBox(_T("Bad namespace"));

        // Done with pNamespace.
        SysFreeString(pNamespace);

        // Done with pIWbemLocator.
        pIWbemLocator->Release();

            // Switch security level to IMPERSONATE.
            CoSetProxyBlanket(m_pIWbemServices,    // proxy
                RPC_C_AUTHN_WINNT,        // authentication service
                RPC_C_AUTHZ_NONE,         // authorization service
                NULL,                         // server principle name
                RPC_C_AUTHN_LEVEL_CALL,   // authentication level
                RPC_C_IMP_LEVEL_IMPERSONATE,    // impersonation level
                NULL,                         // identity of the client
                EOAC_NONE);               // capability flags
        }
    else AfxMessageBox(_T("Failed to create IWbemLocator object"));
}

    CoCreateInstance creates an IWbemLocator interface. IWbemLocator contains a single method, ConnectServer, which you can use to connect to the WMI namespace held in the member variable, m_namespace. If successful, save the interface in m_pIWbemServices. Set the security information that will be used for future calls to IWbemServices and its proxies.

  7. Release the IWbemLocator interface.


Displaying Class Instances

To display class instances

  1. Use the Dialog Editor to add a button to your dialog with the ID IDC_ENUMDISKS and the caption "&Enum Disks". Then, disable the button.

  2. Use the Class Wizard to add the button handler, CWBEMCLIENTDLG::ONENUMDISKS to the dialog class.
  3. Use the Member Variables tab to connect the IDC_ENUMDISKS button to a CWbemClientDlg class CButton member variable named m_enumDisks.
  4. To enable this button when a connection has been established, add the following lines of code to the CWbemClientDlg::OnConnect method.
                // Indicate success.
            m_outputList.ResetContent();
            m_outputList.AddString(_T("Connected To Namespace"));

            // It's safe the hit the other buttons now.
            m_enumDisks.EnableWindow(TRUE);
  5. Add the helper function to the beginning of the WbemClientDlg.cpp file:
    // Return error message.
CString ErrorMsg(LPCTSTR str, HRESULT hRes) {
       CString s;
    s.Format("%s(0x%08lx)", str, hRes);
    return s;
}
  6. Look at the code you will need for the CWbemClientDlg::OnEnumdisks method. Call CreateInstanceEnum to get an enumerator for all the instances of the class Win32_LogicalDisk. Save this enumerator in pEnumStorageDevs.
        BSTR className = SysAllocString(L"Win32_LogicalDisk");
    IEnumWbemClassObject *pEnumStorageDevs = NULL;

    HRESULT hRes = m_pIWbemServices->CreateInstanceEnum(
        className,             // name of class
        0,
        NULL,
        &pEnumStorageDevs);    // pointer to enumerator

    Repeat the call to the IEnumWbemClassObject::Next method as often as needed to get a pointer to each instance.

  7. Provide storage for all the instances you request. The easiest way to do this is to request just one instance. The uReturned parameter will return one if an instance is returned and will return zero if there are no more instances.
            ULONG uReturned = 1;
        while(uReturned == 1)
        {
            IWbemClassObject *pStorageDev = NULL;
            //---------------------------
            // enumerate through the resultset.
            hRes = pEnumStorageDevs->Next(
                2000,           // timeout in two seconds
                1,              // return just one storage device
                &pStorageDev,   // pointer to storage device
                &uReturned);    // number obtained: one or zero
  8. Now that you have a pointer to an instance of Win32_LogicalDisk, use the IWbemClassObject::Get method to get the __RELPATH property and send it to the trace window.
                    // Get the "__RELPATH" system property.
                BSTR propName = SysAllocString(L"__RELPATH");

                hRes = pStorageDev->Get(
                    propName,    // property name
                    0L,
                    &pVal,       // output to this variant
                    NULL,
                    NULL);

                if (SUCCEEDED(hRes))
                    m_outputList.AddString(CString(V_BSTR(&pVal)));
  9. Navigate to the CWbemClientDlg::OnEnumdisks method and fill it with the following code.
    void CWbemClientDlg::OnEnumdisks()
{
    // Get the Win32_LogicalDisk class
    BSTR className = SysAllocString(L"Win32_LogicalDisk");
    IEnumWbemClassObject *pEnumStorageDevs = NULL;

    BeginWaitCursor();
    m_outputList.ResetContent();

    // Get the list of logical storage device instances.
    HRESULT hRes = m_pIWbemServices->CreateInstanceEnum(
        className,             // name of class
        0,
        NULL,
        &pEnumStorageDevs);    // pointer to enumerator

    EndWaitCursor();
    SysFreeString(className);

    // For each logical storage device...
    if (SUCCEEDED(hRes))
    {
        ULONG uReturned = 1;
        while(uReturned == 1)
        {
            IWbemClassObject *pStorageDev = NULL;
            //---------------------------
            // enumerate through the resultset.
            hRes = pEnumStorageDevs->Next(
                2000,           // timeout in two seconds
                1,              // return just one storage device
                &pStorageDev,   // pointer to storage device
                &uReturned);    // number obtained: one or zero

            if (SUCCEEDED(hRes) && (uReturned == 1))
            {
                VARIANT pVal;
                VariantClear(&pVal);

                // Get the "__RELPATH" system property.
                BSTR propName = SysAllocString(L"__RELPATH");

                hRes = pStorageDev->Get(
                    propName,    // property name
                    0L,
                    &pVal,       // output to this variant
                    NULL,
                    NULL);

                // Done with this object.
                if (pStorageDev)  pStorageDev->Release();

                // Add the path property to the output list box.
                if (SUCCEEDED(hRes))
                    m_outputList.AddString(CString(V_BSTR(&pVal)));
            }
        } // end while

        // Done with this enumerator.
        if (pEnumStorageDevs)  pEnumStorageDevs->Release();
    }
    else m_outputList.AddString(
        ErrorMsg(_T("CreateInstanceEnum() failed:"), hRes));
}
  10. Build the project and run the program.
  11. Click Connect. When you see Connected in the trace window, Enum Disks should be enabled. Click it; you should see a list of logical devices in the trace window:

    Note Every Windows Management Instrumentation (WMI) object has a relative path, whose syntax is represented by the following code.

    Class.KeyName="KeyValue"
So
Win32_LogicalDisk.DeviceID="A:"

    In this case, the code means that your namespace contains an instance of class Win32_LogicalDisk, whose key property, DeviceID, is "A:".


Displaying Instance Properties

Now that you can select an instance of Win32_LogicalDisk, you can add code to display the properties of the selected disk.

To display properties of a specific disk

  1. Use the Dialog Editor to add a button to your dialog with the identifier, IDC_DISKINFO, and the caption "&Disk Info". Disable Disk Info.

  2. Use the Class Wizard to add the button handler, CWBEMCLIENTDLG::ONDISKINFO to the dialog class.
  3. Use the Member Variables tab to connect the IDC_DISKINFO button to a CWbemClientDlg class CButton member variable named m_diskInfo.
  4. To enable the button after the Win32_LogicalDisk instances are displayed and to set the selection to the first logical disk, add the following lines of code to the CWbemClientDlg::OnEnumdisks method.
            // Done with this enumerator.
        if (pEnumStorageDevs)  pEnumStorageDevs->Release();

        // Enable disk info button if disk info is available.
        if (m_outputList.GetCount() > 0)
        {
            m_outputList.SetCurSel(0);
            m_diskInfo.EnableWindow(TRUE);
        }
  5. Get the current selection from the list box:
        // Get selected disk from list box as a BSTR
    CString sDevice;
    int index = m_outputList.GetCurSel();
    m_outputList.GetText(index, sDevice);

    BSTR sDisk = sDevice.AllocSysString();

    You are getting the path to the selected logical disk as a BSTR. Assuming the first disk is "A:", you would get this relative instance path:

    Win32_LogicalDisk.DeviceID="A:"

  6. Pass this path to m_pIWbemServices->GetObject to get a pointer to the IWbemClassObject interface for the selected disk (in other words, to get a "pointer to the disk").
        // Get the selected Win32_LogicalDisk instance.
    IWbemClassObject *pDisk = NULL;

    HRESULT hRes = m_pIWbemServices->GetObject(
        sDisk,         // object path
        0L,    NULL,
        &pDisk,        // pointer to object
        NULL);

    With this interface pointer, you can read the property names of the disk into a SAFEARRAY (a resizable array with upper and lower bounds and index checking).

  7. Use the flag WBEM_FLAG_NONSYSTEM_ONLY to limit the array to properties that are peculiar to the disk.
        // Get the property names from this instance.
    SAFEARRAY *psaNames = NULL;

    hRes = pDisk->GetNames(
        NULL,
        WBEM_FLAG_ALWAYS | WBEM_FLAG_NONSYSTEM_ONLY,
        NULL,
        &psaNames);
  8. Query the array to find out how many property names you have:
            // Get the number of properties.
        long lLower, lUpper;

        SafeArrayGetLBound(psaNames, 1, &lLower);
        SafeArrayGetUBound(psaNames, 1, &lUpper);
  9. Clear the list box. Read each property name into the BSTR PropName and add it to the new list.
            m_outputList.ResetContent();

        for (long i = lLower; i <= lUpper; i++)
        {
            // Get this property.
            hRes = SafeArrayGetElement(
                psaNames,
                &i,
                &PropName);

                CString sProp = CString(PropName);

                m_outputList.AddString(sProp);
  10. Navigate to the CWbemClientDlg::OnDiskinfo method and fill it with the following code:
    // Display the properties of the selected disk.
void CWbemClientDlg::OnDiskinfo()
{
    CWaitCursor wait;

    // Get selected disk from list box as a BSTR
    CString sDevice;
    int index = m_outputList.GetCurSel();
    m_outputList.GetText(index, sDevice);

    BSTR sDisk = sDevice.AllocSysString();

    // Get the selected Win32_LogicalDisk instance.
    IWbemClassObject *pDisk = NULL;

    HRESULT hRes = m_pIWbemServices->GetObject(
        sDisk,         // object path
        0L,    NULL,
        &pDisk,        // pointer to object
        NULL);

    SysFreeString(sDisk);

    // Get the property names from this instance.
    SAFEARRAY *psaNames = NULL;

    hRes = pDisk->GetNames(
        NULL,
        WBEM_FLAG_ALWAYS | WBEM_FLAG_NONSYSTEM_ONLY,
        NULL,
        &psaNames);

    if (SUCCEEDED(hRes))
    {
        // Get the number of properties.
        long lLower, lUpper;

        SafeArrayGetLBound(psaNames, 1, &lLower);
        SafeArrayGetUBound(psaNames, 1, &lUpper);

        // For each property...
        BSTR PropName = NULL;

        m_outputList.ResetContent();

        for (long i = lLower; i <= lUpper; i++)
        {
            // Get this property.
            hRes = SafeArrayGetElement(
                psaNames,
                &i,
                &PropName);
            if (SUCCEEDED(hRes))
            {
                // Format: name (type) ==> value
                CString sProp = CString(PropName);
                m_outputList.AddString(sProp);
            }
            SysFreeString(PropName);
        }
        SafeArrayDestroy(psaNames);
    }
    pDisk->Release();
}

    11. Build the project and run it. Connect to Windows Management Instrumentation (WMI), click Enum Disks, select a disk, and click on the Disk Info button.

Now that you can display property names, you can add code to display the property types. Each property has a set of qualifiers and an MOF data type. One of the standard qualifiers for any property is the Cimtype qualifier, which contains a textual representation of the MOF data type. For example, the logical disk property Description has a Cimtype qualifier, "string".

To read the Cimtype qualifiers

  1. Read the set of all qualifiers with IWbemClassObject::GetPropertyQualifierSet.
    // Get qualifier set for this property.
IWbemQualifierSet *pQualSet = NULL;

hRes = pDisk->GetPropertyQualifierSet(
  PropName,        // name of property
  &pQualSet);      // qualifier set pointer

    Note that system properties, such as __RELPATH, have no qualifier set. Remember, however, that you have already filtered out system properties with the WBEM_FLAG_NONSYSTEM_ONLY flag.

  2. Use the IWbemQualifierSet::Get method to get the value of the Cimtype qualifier.
            BSTR cimType  = SysAllocString(L"CIMTYPE");

                    pQualSet->Get(
                        cimType,      // property name
                        0L,
                        &pVal,        // output to this variant
                        NULL);
  3. Add the highlighted lines of code to the CWbemClientDlg::OnDiskinfo method.
            // For each property...
        BSTR cimType  = SysAllocString(L"CIMTYPE");
        BSTR PropName = NULL;

        m_outputList.ResetContent();

        for (long i = lLower; i <= lUpper; i++)
        {
            // Get this property.
            hRes = SafeArrayGetElement(
                psaNames,
                &i,
                &PropName);
            if (SUCCEEDED(hRes))
            {
                CString sProp = CString(PropName) + _T(" (");
                VARIANT pVal;
                VariantClear(&pVal);

                // Get qualifier set for this property.
                // Note that system properties have no qualifier set.
                IWbemQualifierSet *pQualSet = NULL;

                hRes = pDisk->GetPropertyQualifierSet(
                    PropName,        // name of property
                    &pQualSet);        // qualifier set pointer

                if (SUCCEEDED(hRes))
                {
                    pQualSet->Get(
                        cimType,    // property name
                        0L,
                        &pVal,        // output to this variant
                        NULL);

                    if (SUCCEEDED(hRes))
                    {
                       sProp += V_BSTR(&pVal);
                    }
                }
                sProp += _T(")");
                m_outputList.AddString(sProp);
  4. Rebuild and run the project as before.

    You should now see a list of disk properties and their MOF data types.


Creating a Class Instance

In this section, you will learn how to create a new namespace called "SAMPLE_Office". This new namespace will become a child namespace of the current namespace, Root\Cimv2. In Windows Management Instrumentation (WMI), a namespace is simply an instance of the __Namespace class. Its key property, Name, is used to differentiate between schemas by name.

Note Since a namespace is just a class instance, you can use this technique to create any other class instance.

To create a class instance

  1. Add another button to your dialog box. Give it the identifier, IDC_MAKEOFFICE, and the caption "&Make Office".
  2. Disable the button.

  3. Use the class wizard to add the button handler, CWBEMCLIENTDLG::ONMAKEOFFICE, to the dialog class. Use the Member Variables tab to connect the IDC_MAKEOFFICE button to a CWbemClientDlg class CButton member variable, m_makeOffice.
  4. To enable this button when a connection has been established, add the following line to the CWbemClientDlg::OnConnect method.
    // It's safe to hit the other buttons now.
m_enumDisks.EnableWindow(TRUE);
m_makeOffice.EnableWindow(TRUE);

    The task of creating a namespace has several steps:

    • Ensure you have not already created the namespace.
    • Retrieve the class definition for __Namespace.
    • Spawn an instance of this class.
    • Write the NAME property into the instance.
    • Write the instance to WMI.
    • Open the new namespace, if desired.
  5. Add a member variable to the CWbemClientDlg class to hold the new IWbemServices interface pointer:
    protected:
    virtual void DoDataExchange(CDataExchange* pDX);
    //}}AFX_VIRTUAL
private:
    IWbemServices *m_pIWbemServices;
    IWbemServices *m_pOfficeService;
  6. Initialize m_pOfficeService in the CWbemClientDlg constructor:
            m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
        m_pIWbemServices = NULL;
        m_pOfficeService = NULL;
}
  7. Try to open the "SAMPLE_Office" namespace as if it already exists. If you succeed, you are done.
        // if "Office" namespace doesn't exist...
    BSTR Namespace = SysAllocString(L"SAMPLE_Office");

    HRESULT hRes = m_pIWbemServices->OpenNamespace(
        Namespace,
        0, NULL,
        &m_pOfficeService,
        NULL);

    if (FAILED(hRes))
  8. If you have failed, you need to create the namespace. Retrieve the definition of the class __Namespace from your current namespace, Root\Cimv2.
            BSTR NamespaceClass = SysAllocString(L"__Namespace");
        IWbemClassObject *pNSClass = NULL;

        hRes = m_pIWbemServices->GetObject(
            NamespaceClass,    // object path
            0L,    NULL,
            &pNSClass,         // pointer to object
            NULL);

    IWbemServices::GetObject retrieves either a class definition or an instance, based on its path. You have given it the path "__Namespace", which is a relative class path, so it retrieves a class definition. A relative instance path would end with the key property which selects the instance, for example: __Namespace.Name="MyInstance".

  9. Now that you have the class definition, you spawn a new instance.
                IWbemClassObject *pNSInst = NULL;

            hRes = pNSClass->SpawnInstance(0, &pNSInst);

    IWbemClassObject::SpawnInstance makes a new instance of the class. You must set the key property and call to IWbemServices::PutInstance to actually write the instance to WMI. If you intend to discard the object before calling IWbemServices::PutInstance, simply make a call to IWbemClassObject::Release. Notice that pNSInst is itself a pointer to an IWbemClassObject. You can spawn an instance from another instance, if you wish.

  10. To set the key property, use this code.
                    VARIANT v;
                VariantInit(&v);
                V_VT(&v) = VT_BSTR;
                V_BSTR(&v) = Namespace;

                BSTR Prop = SysAllocString(L"Name");

                hRes = pNSInst->Put(
                    Prop,
                    0,
                    &v,
                    0);

    This call to IWbemClassObject::Put sets the key property, Name, to the Namespace string.

  11. Write the new instance to WMI with IWbemServices::PutInstance.
                    hRes = m_pIWbemServices->PutInstance(
                    pNSInst,
                    WBEM_FLAG_CREATE_OR_UPDATE,
                    NULL, NULL);
  12. Navigate to the CWbemClientDlg::OnMakeoffice method, and fill it with the following code.
    // Save a pointer to the root\cimv2\office namespace
// in m_pOfficeService.
// Create the namespace if it doesn't already exist
void CWbemClientDlg::OnMakeoffice()
{
    CWaitCursor wait;

    // If already connected to the namespace, we are done.
    if (m_pOfficeService)  return;

    // if "Office" namespace doesn't exist...
    BSTR Namespace = SysAllocString(L"SAMPLE_Office");

    HRESULT hRes = m_pIWbemServices->OpenNamespace(
        Namespace,
        0, NULL,
        &m_pOfficeService,
        NULL);

    // Don't SysFreeString(Namespace) here; we'll need it later.
    m_outputList.ResetContent();

    if (FAILED(hRes))
    {
        // Create __namespace class.
        BSTR NamespaceClass = SysAllocString(L"__Namespace");
        IWbemClassObject *pNSClass = NULL;

        hRes = m_pIWbemServices->GetObject(
            NamespaceClass,    // object path
            0L,    NULL,
            &pNSClass,        // pointer to object
            NULL);

        SysFreeString(NamespaceClass);

        if (SUCCEEDED(hRes))
        {
            // Spawn a new instance of this class.
            IWbemClassObject *pNSInst = NULL;

            hRes = pNSClass->SpawnInstance(0, &pNSInst);
            if(SUCCEEDED(hRes))
            {
                // Set the new namespace's name.
                VARIANT v;
                VariantInit(&v);
                V_VT(&v) = VT_BSTR;
                V_BSTR(&v) = Namespace;

                BSTR Prop = SysAllocString(L"Name");

                hRes = pNSInst->Put(
                    Prop,
                    0,
                    &v,
                    0);

                SysFreeString(Prop);
                VariantClear(&v);

                // Create the instance.
                hRes = m_pIWbemServices->PutInstance(
                    pNSInst,
                    WBEM_FLAG_CREATE_OR_UPDATE,
                    NULL, NULL);

                pNSInst->Release();
                pNSInst = NULL;

                if (SUCCEEDED(hRes)) {
                    m_outputList.AddString(
                        _T("Created office namespace"));

                    // open the new namespace.
                    hRes = m_pIWbemServices->OpenNamespace(
                        Namespace, 0, NULL, &m_pOfficeService, NULL);

                            m_diskInfo.EnableWindow(FALSE);
                }
            }
            pNSClass->Release();  // Don't need the class any more
            pNSClass = NULL;
        }
    }

    SysFreeString(Namespace);

    if (m_pOfficeService)
         m_outputList.AddString(_T("Connected to office"));
    else m_outputList.AddString(
        ErrorMsg(_T("Failed to connect to office"), hRes));
}
  13. Build the project, and run the program.
  14. Click Connect.

    When you see "Connected" in the trace window, Make Office should be enabled.

  15. Click Make Office.

    You should see that a new office namespace has been created. You can verify this from WMI Object Browser.

  16. Log on to the Root\Cimv2 namespace, browse for instances of the class __Namespace, and click the "SAMPLE_Office" instance; it becomes the new tree root.

  17. Close your WbemClient application and run it again.

    When you click Make Office this time, you should connect to the existing office namespace without creating it again.

    From the WMI CIM Studio application, you can get another view of the SAMPLE_Office instance.

  18. Log on to the Root\Cimv2 namespace. Click Search for Classes and type in "__namespace". Click Instances for a listing of instances.

In addition to viewing class instances, you can add and delete them, too. To delete the "SAMPLE Office" namespace, select it and click Delete. To delete a class or instance programmatically, use IWbemServices::DeleteClass or IWbemServices::DeleteInstance, respectively.


WMI Provider Programming

The Windows Management Instrumentation (WMI) SDK is designed for those who create software that uses WMI (application developers and provider developers) and those who use WMI to extract management information from a computer organization (network administrators and system managers).

The WMI SDK provides the tools you need to design providers that supply WMI with just-in-time information. Provider developers will find the following WMI SDK sections especially useful.

Section | Description
Programming Basics for WMI Providers | Implementation and tasks for WMI providers.
WMI Providers | Built-in providers for WMI.
Provider Framework | Classes that can be used to create a WMI instance and/or method provider.


Programming Basics for WMI Providers

Windows Management Instrumentation (WMI) providers are standard Component Object Model (COM) or distributed COM (DCOM) servers that can be implemented using the full range of supported server types, which includes:

  • In-process dynamic-link libraries (DLL)
  • Local or remote Microsoft® Windows NT®/Microsoft® Windows® 2000 services
  • Local or remote standard executable files (.exe)

WMI providers are categorized according to the types of requests that they service. The most common providers are instance providers. Instance providers supply instances of a given class and support one or more of the following asynchronous operations:

  • Instance retrieval
  • Enumeration
  • Modification
  • Deletion
  • Query processing

Class providers can support the same asynchronous operations as instance operations. However, class providers supply class definitions rather than instances of a class. Because the operations supported by class providers can negatively impact system performance, they should only be implemented when absolutely required.

Class providers can be implemented as pull or push providers; instance providers can only be implemented as pull providers. Pull providers maintain their own data, generating it dynamically when necessary. Push providers rely on WMI to maintain their data in the Common Information Model (CIM) repository. For more information about these types of class and instance providers, see Pull and Push Providers.

Property providers can support the retrieval and modification of individual property values.

Method providers implement the methods of one or more classes. Having a single provider support both methods and instances can be convenient.

Event providers deliver event notifications to WMI from a data source, such as the system registry or a Simple Network Management Protocol (SNMP) device. Then, WMI forwards the events to the appropriate consumers.

Event consumer providers are used by permanent event consumers to supply the appropriate physical destination for particular events.

Providers typically perform the following tasks:

  • Register with WMI. All types of providers are required to complete the registration process.
  • Implement the IWbemProviderInit interface to perform initialization. All types of providers are required to support initialization.
  • Implement a primary interface. Most providers are required to implement a primary interface to support the features that are specific to the type of provider. Only push providers are exempt from having to implement a primary interface.
  • Support a request from WMI to unload. All "pure" providers (providers that operate only as providers) are required to unload when asked to do so by WMI. Non-pure providers (providers that can also operate as clients) do not have to respond to an unload request. However, such providers place an additional load on WMI by performing private operations not related to their role as providers. This should only be done if strictly necessary. Providers specify whether or not they are pure or non-pure in the registration process. For more information about pure providers, see the description of the Pure property of the __Win32Provider class.


Provider Primary Interfaces

Providers implement a primary interface that supports the type of functionality specific to their role. The following table lists primary interfaces by provider type.

Provider | Primary interface
Class provider | IWbemServices (asynchronous methods only)
Instance provider | IWbemServices (asynchronous methods only)
Property provider | IWbemPropertyProvider
Method provider | IWbemServices (ExecMethodAsync only)
Event provider | IWbemEventProvider
Event consumer provider | IWbemEventConsumerProvider

As an option, event providers can also implement IWbemEventProviderQuerySink. This interface is most useful for providers that supply events of multiple types and that need to perform as many internal optimizations as possible.

Because IWbemServices is also used by applications and providers to request services of WMI, it contains many methods that are irrelevant to certain types of providers. Class, instance, and method providers are typically concerned with fewer than six IWbemServices methods. These providers can supply a stub implementation that returns WBEM_E_PROVIDER_NOT_CAPABLE for all of the other methods that do not support their feature set. This is illustrated in the following code sample.

HRESULT STDMETHODCALLTYPE PutClassAsync(
            IWbemClassObject __RPC_FAR *pObject,
            long lFlags,
            IWbemContext __RPC_FAR *pCtx,
            IWbemObjectSink __RPC_FAR *pResponseHandler)
                 {return WBEM_E_PROVIDER_NOT_CAPABLE;};

Class and instance providers can support zero or more of the following features by supplying a complete implementation of the corresponding IWbemServices method.:

Feature | Class provider method | Instance provider method
Data retrieval | GetObjectAsync | GetObjectAsync
Data modification | PutClassAsync | PutInstanceAsync
Data deletion | DeleteClassAsync | DeleteInstanceAsync
Data enumeration | CreateClassEnumAsync | CreateInstanceEnumAsync
Query processing | ExecQueryAsync | ExecQueryAsync

Note that both provider types implement only the asynchronous variety of methods. There is no support in this release for providers that implement the synchronous methods of IWbemServices.

The target data for a class provider is a class definition; the data for an instance provider is an instance of a class. Class and instance providers inform WMI of their feature set as part of the registration process.

Method providers fully implement a set of methods for a Common Information Management (CIM) object in their primary interface, ExecMethodAsync. All of the other methods return WBEM_E_NOT_IMPLEMENTED. For information about implementing ExecMethodAsync, see Implementing IWbemServices::ExecMethodAsync.

A single provider can act simultaneously as a class, instance, and method provider by proper registration and implementation of all relevant methods.

Property, event, and event consumer providers implement all of the methods in their primary interface.

Note Class providers that are designed as simple push providers only implement IWbemProviderInit; they do not implement a primary interface. This is because push providers use WMI to support their operations. See Pull and Push Providers for more information.


Registering a Provider

Providers register with Windows Management Instrumentation (WMI) to publish information about the data and operations that they support and their physical implementation. WMI uses this information to load and initialize the provider and to determine the right provider for a particular client request. All types of providers follow the same procedure for registration. Neither WMI nor the provider needs to be running during the registration process. To register with WMI, a provider must execute the following steps.

  1. Register with the Component Object Model (COM) by creating registry entries if necessary. This process applies to all COM servers and is unrelated to WMI.
  2. Create a Managed Object Format (MOF) file that contains the following two instances:
    • An instance of the __Win32Provider class to describe the physical implementation of the provider.
    • An instance of a class derived either directly or indirectly from __ProviderRegistration to describe the logical implementation of the provider. For more information, see one of the following topics:

      Registering Class and Instance Providers

      Registering a Property Provider

      Registering a Method Provider

      Registering an Event Provider

      Registering an Event Consumer Provider

  3. Place the .mof file into a permanent directory, typically the provider's installation directory.
  4. Locate the following registry key: HKLM\SOFTWARE\Microsoft\WBEM. This key contains a REG_SZ value named "MOF Self-Install Directory."
  5. Copy the .mof file into the directory named by the registry key value. Placing the .mof file into this directory ensures that it is compiled either right away (if WMI is currently running) or the next time that WMI is started.
  6. Locate the following registry key: HKLM\SOFTWARE\Microsoft\WBEM\CIMOM. This key contains a REG_MULTI_SZ value named "Autorecover MOFs" that contains a list of paths to various .mof files.
  7. Add the full path to the permanent location of the .mof file to the end of this list. This ensures that the .mof file will be recompiled if a problem occurs.

For testing purposes, a registration .mof file can be immediately compiled using the MOF Compiler instead of the preceding steps.

During installation, some providers place their .mof files in a temporary location such as C:\Wbem\Mof before copying them to their permanent location. Do not include the path to this temporary location in the list of paths described in step 6. Because WMI deletes all temporary copies of .mof files after they have been compiled, always use the path to the permanent copy.


Updating a Provider

Sometimes it may be necessary to install a newer version of a WMI provider onto a running system. WMI allows one to do so without having to restart the service (let alone having to reboot the machine), or impacting any applications that are using WMI at that time.

The following steps must be followed by all provider setups when upgrading to a new version of their provider.

In what follows, we assume that the provider in question is implemented as an in-proc server (a DLL). Similar steps should be take when upgrading a local-server-implemented provider.


Assumptions About Updating a Provider

Before updating a provider, verify these assumptions:

  • The old provider DLL name is myprov.dll
  • The old WMI provider name (the value of the Name property of its __Win32Provider object) is "MyProv"
  • The old CLSID is CLSID_MyProv


Building the New Provider

To build the new provider, follow these steps:

  1. Compile the new provider with a different DLL name and a different CLSID, e.g. myprov1.dll with CLSID_MyProv1
  2. Modify provider registration MOF to use the new CLSID (CLSID_MyProv1), but the same provider name ("MyProv")


Installing the New Provider

To install the new provider, follow these steps:

  1. Copy the new provider DLL with the new name alongside the old one.
  2. Self-register the new provider (regsvr32 myprov1.dll)
  3. Compile the new provider registration MOF (thus overwriting the old provider registration). From this point on, the new provider is fully operational (until this point, the old provider was fully functional).


Cleaning Up After the Update

If you wish to remove the old version of the provider, follow these steps:

  1. Unregister the old DLL (regsvr32 /u myprov.dll)
  2. Mark the old DLL to be deleted on reboot by calling MoveFileEx.


Initializing a Provider

IWbemProviderInit and IWbemProviderInitSink are two interfaces involved in the initialization of all providers. IWbemProviderInit is implemented by providers and called by Windows Management Instrumentation (WMI) to begin initialization. When WMI determines that a provider's services are needed, it loads the provider and calls its IWbemProviderInit::Initialize method.

IWbemProviderInitSink is implemented by WMI and called by providers to report initialization status. Because Initialize should return after only a few seconds and initialization can sometimes take longer, providers can report interim status.

WMI passes the following as input parameters to IWbemProviderInit::Initialize:

  • If the provider has requested per-user initialization by setting the PerUserInitialization property in the __Win32Provider class to TRUE, the name of the logical user.
  • A set of flags that currently must be zero.
  • The name of the namespace.
  • The name of the locale.

WMI also passes pointers to three interfaces:

  • IWbemServices
  • IWbemContext
  • IWbemProviderInitSink

The IWbemServices and IWbemContext interfaces can be used to make requests to WMI either during the initialization process or later. If the provider needs to use any of these pointers after returning from the Initialize call, it must call AddRef to increment the reference count for that pointer.

The initialization process of some providers can involve other providers. Providers that are dependent upon information from another provider are known as dependent providers. WMI defines some special rules for dependent providers:

  • Dependent requests must reuse the IWbemContext pointer that was passed to Initialize.

    Non-dependent requests must not reuse this pointer. This means that any calls into WMI made during initialization must reuse the IWbemContext pointer that was passed in from WMI. Failure to do so can result in deadlock.

  • Dependent providers must make requests to WMI by using one of the following two strategies:
    • The dependent request can be made with the thread that was received from WMI.
    • The dependent request can be made with a new thread created by the provider. Before making the request, the provider records it in an internal data structure and returns the call.
  • Dependent providers must always return the thread that was received from WMI, either through the dependent request or by returning from Initialize.

Under no circumstances will a provider be allowed to block a thread received from WMI. The danger in not carefully handling the threads that are delivered by WMI is that it is possible for a provider to acquire all of the threads in the WMI thread pool and block them, resulting in a deadlocked system.

Note In-process providers that must connect to WMI separately from the initialization process must use the CLSID_WbemAdministrativeLocator class identifier to access IWbemLocator in the CoCreateInstance call.

  IWbemLocator *pLoc = 0;

  DWORD dwRes = CoCreateInstance(CLSID_WbemAdministrativeLocator, 0,
      CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *) &pLoc);

Failure to use this identifier will result in an Access Denied error. For more information about making a connection to WMI, see Connecting to WMI.


Reporting Initialization Status

All implementations of IWbemProviderInit::Initialize must call IWbemProviderInitSink::SetStatus to report initialization status to WMI. The SetStatus call allows WMI to determine if a provider is ready to receive requests and the type of requests that the provider is ready to receive. Providers set the lStatus parameter of SetStatus to one of the following values:

  • WBEM_S_INITIALIZED
  • WBEM_S_INDIRECTLY_UPDATED
  • WBEM_E_FAILED

To report a fully successful initialization, providers set lStatus to WBEM_S_INITIALIZED. Providers return this status code when they are ready to handle requests from applications, WMI, and other providers. After receiving the WBEM_S_INITIALIZED status, WMI makes a call to the provider's IWbemProviderInit::QueryInterface method to retrieve a pointer to its primary interface. For a list of each provider type's primary interface, see Provider Primary Interfaces.

To report an error during initialization, providers set lStatus to WBEM_E_FAILED. WMI views providers that specify WBEM_E_FAILED as not functional.

WMI releases its IWbemProviderInit pointer either after it has obtained a pointer to the provider's primary interface or after initialization has failed.

The following code sample is an example of an implementation of IWbemProviderInit::Initialize for an instance provider.

STDMETHODIMP CInstPro::Initialize (LPWSTR pszUser, LONG lFlags,
                                   LPWSTR pszNamespace,
                                   LPWSTR pszLocale,
                                   IWbemServices *pNamespace,
                                   IWbemContext *pCtx,
                                   IWbemProviderInitSink *pInitSink)
{
    if (pNamespace)
        pNamespace->AddRef();      // increment reference count
    m_pNamespace = pNamespace;     // save pointer locally

    // Report status to WMI

    pInitSink->SetStatus (WBEM_S_INITIALIZED, 0);
    return WBEM_S_NO_ERROR;
}


Making Calls to WMI

Providers can call methods implemented by Windows Management Instrumentation (WMI) from within their method implementations. When a provider calls the WMI implementation of an IWbemServices method from within its own implementation of the same method, there are special considerations. These considerations are important regardless of whether the provider calls the synchronous or asynchronous version of the method.

Each IWbemServices method that a provider can implement has a pCtx parameter, a pointer to an IWbemContext interface implementation. When WMI calls the provider, it passes a valid pointer in this parameter. Providers must always pass this same pointer in any calls to WMI that they make while servicing requests. Neglecting to set pCtx appropriately can cause WMI to start an infinite loop.

For example, the following code shows the correct way to call the WMI implementation of GetObject from within its implementation of GetObjectAsync.

STDMETHODIMP CClassProv::GetObjectAsync (BSTR ObjectPath, long lFlags,
    IWbemContext *pCtx, IWbemObjectSink *pHandler)
{
  IWbemClassObject *pclObj = NULL;

  hr = m_pNamespace->GetObject( _bstr_t(L"AClass"), 0, pCtx, &pclObj,
      NULL );
  RELEASE( pclObj );
  return pHandler->SetStatus(0, hr, NULL, NULL);
}

Instance, class, and property providers must not issue any calls to WMI requesting the modification of data while servicing a read request. The only providers that are exceptions to this rule are push providers. These types of providers are class providers that store their data in the CIM repository and rely on WMI to handle requests from clients. While servicing a read request, a push provider can update the CIM repository, but it must set the lFlags parameter to WBEM_FLAG_OWNER_UPDATE in the appropriate IWbemServices call.

Event providers must not make any class changes while servicing a call. They also cannot issue any event-related calls, such as modifying an event filter.


Client Impersonation by Providers

The following section applies only to Microsoft® Windows NT®/Microsoft® Windows® 2000 platforms running Windows Management Instrumentation (WMI) SDK version 1.1 or later. It does not apply to the original WBEM SDK 1.0 release, nor does it apply to the Windows 95 or Windows 98 platforms.

In the Windows NT/Windows 2000 environment, WMI typically runs as an administrative service at a high security level (the LocalServer security context). This approach gives it the means to access privileged information. When WMI calls a provider for information, it passes its security ID (SID) to the provider, enabling the provider to access information at the same high security level.

When a WMI application is launched, it is given the security context of the user who launched it. This is typically a lower security level than LocalServer, so the user may not have permission to access all of the information available to WMI. When the user application asks for dynamic information, WMI passes the user's SID to the corresponding providers. If the provider is written appropriately, it will attempt to access information with the user's SID, rather than its own. In this way, the provider can return only the information that the user is permitted to obtain. This process is called impersonation, because the provider is impersonating the client.

For impersonation to succeed, several conditions must be met.

  • The user application must call WMI with a DCOM connection security level of RPC_C_IMP_LEVEL_IMPERSONATE or RPC_C_IMP_LEVEL_DELEGATE.
  • The appropriate dynamic provider must be registered with WMI as an impersonation provider.
  • The impersonation provider must switch to the security level of the user application before accessing privileged information.
  • The provider must correctly handle error conditions if access to this information is denied.


Client Coding Considerations for Impersonation

When using DCOM, the client application has the ability to decide the security level under which the connection will occur. During the call to CoInitializeSecurity, the client may specify one of the following:

  • RPC_C_IMP_LEVEL_NONE
  • RPC_C_IMP_LEVEL_IDENTIFY
  • RPC_C_IMP_LEVEL_IMPERSONATE
  • RPC_C_IMP_LEVEL_DELEGATE (Windows 2000 only)
CoInitializeSecurity(
NULL,
-1,
NULL,
NULL,
RPC_C_AUTHN_LEVEL_CALL,
RPC_C_IMP_LEVEL_IMPERSONATE,
NULL,
EOAC_NONE,
0
);

In order to grant the ultimate provider or providers permission to impersonate the client, the client application should specify either RPC_C_IMP_LEVEL_IMPERSONATE or RPC_C_IMP_LEVEL_DELEGATE (Windows 2000 only). Alternately, the client can allow the user to choose the security level during the connection to WMI. Furthermore, during use of the IWbemServices interface, the proxy security level must be changed to the same settings using CoSetProxyBlanket.

CoSetProxyBlanket(
    pIWbemServices, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL,
     RPC_C_AUTHN_LEVEL_CALL,     RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EAOC_NONE
    );

Note For WMI, it is recommended that client applications default to the RPC_C_IMP_LEVEL_IMPERSONATE security level.

Future releases of the WMI SDK may offer classes that collect instance information from several servers. This means local providers may access providers on other machines. If the client and its ultimate provider or providers are located on a different machines, the client must grant permission for its SID to be passed across the local machine boundary. In other words, the client application must specify the RPC_C_IMP_LEVEL_DELEGATE security level.

Unfortunately, given RPC_C_IMP_LEVEL_DELEGATE security permission, a provider can impersonate a client so perfectly that it becomes indistinguishable from the client. For example, a hostile provider could launch an e-mail application and send e-mail identified as originating from the unsuspecting client. For this reason, the RPC_C_IMP_LEVEL_DELEGATE level should only be used when the client is connecting to a well-known and trusted server.

For information on other security issues, see Security Considerations with Asynchronous Calls.


Registration of Impersonation Providers

WMI will only pass the SID of the client application to providers who have registered as impersonation providers. The __Win32Provider class definition is shown below for reference purposes.

class __Win32Provider : __Provider
{
    [not_null: DisableOverride ToInstance ToSubClass] string CLSID;
    string ClientLoadableCLSID;
    string DefaultMachineName;
    [SUBTYPE("interval"); ToInstance ToSubClass]datetime UnloadTimeout;
    boolean InitializeAsAdminFirst;
    [Values{"None"}: ToSubClass] sint32 ImpersonationLevel = 0;
    [Values{"CLSID", "Namespace", "COM Object"}: ToSubClass] sint32 InitializationReentrancy = 0;
    boolean PerUserInitialization = FALSE;
    boolean PerLocaleInitialization = FALSE;
    boolean Pure = TRUE;
};

You can register this provider by setting the ImpersonationLevel property in __Win32Provider to 1 (the default is 0) and PerUserInitialization to TRUE as shown below.

instance of __Win32Provider
{
    CLSID = "{FD4F53E0-65DC-11d1-AB64-00C04FD9159E}";
    ImpersonationLevel = 1;
    Name = "MS_NT_EVENTLOG_PROVIDER";
    PerUserInitialization = TRUE;
};

The ImpersonationLevel property is documentary; it is used to publish whether the provider supports impersonation or not. If the value is zero, then the provider declares it is not impersonating the client and will perform all operations requested of it in the same user context as WMI. If the property has a value of 1, then the provider indicates that it will use impersonation calls to check operations performed on the client's behalf.

If the provider is registered with InitializeAsAdminFirst, then the thread security token will be administration level during the initialization phase only. While CoImpersonateClient will not fail, the security context will be that of WMI and not the client.


Provider Coding Considerations for Impersonation

If the provider is registered with ImpersonationLevel set to 1, then the provider will be called so that the provider may invoke the security context of the remote client of WMI that made the request. For example:

  • JoeUser is running WMI CIM Studio, and a call to IWbemServices::GetObject is made.
  • WMI receives the call over DCOM and records the fact that JoeUser made the request.
  • WMI processes the request internally as LocalSystem.

If a call to a provider is needed, WMI allocates a thread and uses COM APIs to set the call to the security context of JoeUser and then calls the provider's implementation of IWbemServices::GetObjectAsync.

If the provider needs to insist on the IMPERSONATE level before executing, then the provider needs to check this near the IWbemServices method entry points. This can be quickly achieved by using OpenThreadToken and GetTokenInformation.

Important These APIs will fail unless the provider first calls CoImpersonateClient.

It is important to note that although IServerSecurity and CoQueryClientBlanket have the ability to detect the impersonation level, they actually fail to do so. This is documented in Microsoft® Win32® and DCOM documentation.


How the Provider Impersonates the Client

The provider must call CoImpersonateClient to impersonate the client. If it fails to do this, it is executing at the administrator level. If the provider needs to temporarily act as an administrator or perform the access check manually, then CoRevertToSelf can be called.

On entry into the IWbemServices method exported by the provider, the provider must call CoImpersonateClient to actually set the thread token to match that of the client.

Important By default, the thread identity is that of WMI and not the client's.

If an applicable security violation occurs, the provider should return an appropriate completion code to WMI through IWbemObjectSink::SetStatus. For more information, see Reporting Access Denials.


An Example of Client Impersonation

A simple impersonation provider can be implemented as follows.

IWbemServices::GetObjectAsync(...)
{
    CoImpersonateClient();
    \\...execute Win32 code, checking for ACCESS_DENIED return codes

    CoRevertToSelf(); // Become Admin again (WMI)
    \\...execute as an admin for a while
    CoImpersonateClient();
    ...
    CoRevertToSelf(); // Become Admin again (WMI)
}

In general, the provider is initially an administrator and bounces back and forth between CoImpersonateClient and CoRevertToSelf to impersonate the client or reverts to the administration level, as required. It is the provider's responsibility to correctly place these calls so as not to expose a security hole to the end-user. Within the impersonated code sequence, the provider simply calls native Win32 APIs, for example.

In cases where the client connected with IDENTIFY level impersonation, CoImpersonateClient does not return an error code. Instead, the client is impersonated in a weak way (for identification only), and most Win32 APIs will return ACCESS_DENIED. This is harmless in practice, as the user will not be permitted to do anything he should not do. However, it may be useful during provider development to know whether the client was truly impersonated or not; the following code fragment will make the determination.

DWORD dwImp = 0;
HANDLE hThreadTok;
DWORD dwBytesReturned;
BOOL bRes;

// You must call this before trying to open a thread token!
CoImpersonateClient();

bRes = OpenThreadToken(
    GetCurrentThread(),
    TOKEN_QUERY,
    TRUE,
    &hThreadTok
);

if (bRes == FALSE)
{
    printf("Unable to read thread token (%d)\n", GetLastError());
    return 0;
}

bRes = GetTokenInformation(
    hThreadTok,
    TokenImpersonationLevel,
    &dwImp,
    sizeof(DWORD),
    &dwBytesReturned
);

if (!bRes)
{
    printf("Unable to read impersonation level\n");
    CloseHandle(hThreadTok);
    return 0;
}

switch (dwImp)
{
case SecurityAnonymous:
    printf("SecurityAnonymous\n");
    break;

case SecurityIdentification:
    printf("SecurityIdentification\n");
    break;

case SecurityImpersonation:
    printf("SecurityImpersonation\n");
    break;

case SecurityDelegation:
    printf("SecurityDelegation\n");
    break;

default:
    printf("Error. Unable to determine impersonation level\n");
    break;
}

CloseHandle(hThreadTok);


Reentrancy Considerations for Impersonation

In client impersonation operations, several reentrancy issues can arise. Whenever the provider calls into WMI, WMI may again call back into the provider in a reentrant fashion. When a provider has made any call that could alter the security level (including calls into WMI), then the provider must ensure that it sets the appropriate level again before proceeding. The following code block provides an example.

IWbemServices::GetObjectAsync(...)
{
CoImpersonateClient();
// Call into WMI for class def
pIWbemServices->GetClass(...);
CoImpersonateClient(); // WMI may have altered the thread to be admin (and probably did)
...
}

Note If you call a system API or another interface method, the call context is not guaranteed to be maintained.

This applies to all DCOM development in general and is not a WMI restriction.

It is important to note that if a reentrant call to WMI is made during impersonation, then any providers invoked during this nested call will also be able to impersonate the client. However, if CoRevertToSelf is called before the call back into WMI, then the call is made in the security context of WMI and not the original client. Any providers invoked during this nested call will not impersonate the client but will instead execute in the security context of WMI. Typically, it is correct to make reentrant calls into WMI while impersonating (after the call to CoImpersonateClient but before CoRevertToSelf) so that other providers may also impersonate the client and not expose a security hole.


Reporting Access Denials

There are several problems associated with reporting access denials. When not all the properties of an instance can be retrieved or when not all instances can be constructed due to access restrictions, there are several ways a provider can respond. The provider can return partial information and a success code, no information and an error code, or no information and no error code.

If the provider returns an ACCESS DENIED error code to WMI and WMI passes this on to the client, that client can infer that the information exists but that access to it is denied. In some situations, this can be a breach of security.

If a dynamic class provider returns WBEM_E_ACCESS_DENIED error codes to WMI, it will not be propagated to the client. Instead, the set of classes that the provider would have supplied will simply not be exposed.

If a dynamic instance provider is called, the underlying data source will undoubtedly have its own rules as to how to deal with this situation. It is the responsibility of the provider to replicate that philosophy into the WMI space.


Reporting Partial Instances

It is the provider's responsibility to deal with the policy when an instance cannot be completely filled with properties due to access violations. If a particular user can see some properties and not others, there is no way to set a fixed policy on whether the entire operation should be failed or if a partial instance should be returned with the denied properties set to NULL.

In WMI version 1.x releases, the provider has two choices.

  • The entire instance should not be reported and WBEM_E_ACCESS_DENIED returned.

    The provider can optionally include an error object describing the reason for the denial.

  • The properties that are denied should be set to NULL.

Therefore, if during a call to GetObject the provider cannot completely report the instance, it may return WBEM_E_ACCESS_DENIED or report a partial instance with the denied properties set to NULL and report WBEM_S_NO_ERROR.


Reporting Partial Enumerations

It is the provider's responsibility to deal with the policy when all instances cannot be completely returned during an enumeration or a query due to access violations. If a particular user can see some instances and not others, there is no way to set a fixed policy on whether the entire operation should be failed, whether some instances should be returned with a No Error message, or some instances should be returned with a special status or error code.

Possible provider responses include:

  • Return all instances that can be accessed with WBEM_S_NO_ERROR.

    The user is thus not aware that some instances were not available.

  • Fail the entire operation with WBEM_E_ACCESS_DENIED and return no instances.

    The provider may optionally have included an error object describing the situation to the user. This presents a problem, since providers may access their data sources serially and may not be aware of denials until partway through the enumeration.

  • Return all the instances that can be accessed but return the non-error status code, WBEM_S_ACCESS_DENIED.

    The provider should note the denial during enumeration and may continue providing instances, finishing up with the non-error status code. The provider may also elect to abort the enumeration at the first denial.

To justify the first case, there are a number of systems such as Structured Query Language (SQL) with row-level security, which return successful partial results using the caller's security level to define the result set with no error.

The justification for the last case is that different providers have different retrieval paradigms. A provider may have already delivered instances before discovering an access violation. Some providers may elect to continue providing other instances and others may wish to abort.

Returning an error code is a problem in DCOM, because excepting an error object, no information may be marshaled back during an error. Since some information may have already been returned, returning an error brings the user into a logically inconsistent state. Instead, the result code should be a non-error status code.


Unloading a Provider

Windows Management Instrumentation (WMI) unloads a provider when it determines that it is no longer needed. When a provider is idle for more than a specific amount of time, WMI will begin the process of unloading the provider. The minimum amount of time a provider will remain active is determined by a property named ClearAfter in instances of classes that are derived from the WMI system class __CacheControl in the \Root namespace. Each of these derived classes control provider unloading for a specific type of provider. Listed below are the classes that control provider unloading:

  • __EventConsumerProviderCacheControl
  • __EventProviderCacheControl
  • __EventSinkCacheControl
  • __ObjectProviderCacheControl
  • __PropertyProviderCacheControl

You can change the minimum amount of time that WMI will allow a provider to remain inactive by editing the ClearAfter property in cache control instance for a specific type of provider. For example, if you want to want to limit the amount of time a property provider can remain idle you could use WMI CIM Studio to edit an instance of the class __PropertyProviderCacheControl in the Root namespace. You can use the interval editor to set the value of the ClearAfter property to a new value.

In future versions, WMI will use the UnloadTimeout property of the provider's __Win32Provider instance. Therefore, providers should set this property to 5 minutes or less.

To unload a provider, WMI calls the Release method of the provider's primary interface. For example, WMI calls IWbemServices::Release for a class provider and IWbemPropertyProvider::Release for a property provider. When Release is called, a pure provider (a provider that has set the Pure property of its Win32Provider instance to TRUE) is required to release all of the interface pointers that it currently holds against WMI. Typically, providers hold pointers to the IWbemServices and IWbemContext interfaces supplied to them in IWbemProviderInit::Initialize. A pure provider exists only to service requests and cannot take on the role of a client application.

Non-pure providers can transition to the role of client application after WMI has asked it to unload. Non-pure providers set the Pure property to FALSE. Such providers also independently act as clients, but because they cannot be unloaded, they increase system overhead. For more information about pure and non-pure providers, see the documentation of the __Win32Provider system class.


Abrupt Termination of Providers

When Windows Management Instrumentation (WMI) is stopped by the user (either explicitly, or during system shutdown), any providers (instance, class, event, and so on) that are still loaded at the time will not be released. Also, an in-process provider's DllCanUnloadNow entry point will not be called. Moreover, if an in-process provider is in the middle of a method call at the time of the shutdown, the executing thread can be terminated in the middle of the call.

If WMI shuts down while a provider is loaded, some of the routines that normally handle cleanup (the object's destructor and DllCanUnloadNow) are not called. Except in most unusual circumstances, the only routine guaranteed to be called is the DLL entry point (DllMain). This situation makes provider cleanup more difficult.

Because it is possible that WMI will shut down in the middle of a call, providers must make sure that they do not leave their data sources in an inconsistent state. For read-only providers, this is generally not a problem. Providers with write capabilities, however, may want to implement some sort of transactioning to allow a safe rollback after an abrupt termination.

When WMI exits, the operating system will automatically release all memory allocated to an in-process provider and will close most resources held by the provider (file handles, window handles, mutexes, and so on). The provider does not need to take any specific action to make this happen.

Certain types of resources are not automatically released by the operating system; an example would be a socket or a database connection. Such resources may need to be manually cleaned up by the provider. One place to perform this sort of cleanup is DllMain—the DLL entry point function that is called (once) when the DLL is being unloaded.

Cleanup code can be added directly into DllMain, executing it in response to DLL_PROCESS_DETACH. This can be somewhat difficult to arrange, especially in programming environments such as MFC or ATL. See the Microsoft Knowledge Base article Q148791, "How to Provide Your Own DllMain in an MFC Regular DLL."

An alternate approach is to put the cleanup code in the destructor of a global class. Global objects are not allocated on the heap and are automatically destroyed during DLL unload. The following code sample provides an example.

class CMyCleanup
{
    ~CMyCleanup()
    {
        CloseHandle(m_hOpenFile);
        CloseDatabaseConnection(g_hDatabase);
    }
} g_Cleanup;

There are many restrictions as to what can be done in the cleanup code with either approach. Neither threads nor any DLLs that are not implicitly linked, may be accessed in any way; COM calls cannot be made under any circumstances. For more information, see "Win32 Q & A" in Microsoft Systems Journal (March 1996 and September 1996).

Note that out-of-process providers do not experience any of these problems, as they are not killed when WMI shuts down, but they will be released after a COM timeout. Providers for whom cleanup and termination robustness issues are more important than performance may want to consider making themselves out-of-process.


Multithreading Considerations for Providers

Event providers must use the multithreading model "Both". All other providers are strongly encouraged to use the multithreading model "Both".


Class and Instance Providers

Class providers supply applications with class definitions, and instance providers supply applications with instances of a given class. Instance providers are the most commonly written providers; class providers are rare. This is because using a class provider can negatively impact system performance for all. Before constructing a class provider, verify that the classes to be supported truly need to be dynamically generated. In most cases, the list of classes is slow-changing and finite. The recommended mechanism is to place the class definitions in the Common Information Model (CIM) repository using the Windows Management Instrumentation (WMI) application programming interface (API) or a Managed Object Format (MOF) file.

Class providers can be modeled as pull providers or push providers. Instance providers can be modeled only as pull providers. The three provider models differ in how they manage their data. Pull providers supply their data dynamically in response to an application request whereas push providers store their data once in the CIM repository. For more information, see Pull and Push Providers.

Class and instance providers register with WMI by creating the standard __Win32Provider instance and an instance derived from the __ObjectProviderRegistration class. For information about registration, see Registering Class and Instance Providers.

Class and instance providers implement IWbemServices as their primary interface and can support the same set of features: data retrieval, data update, data removal, enumeration, and query processing. To support data retrieval and query processing, class and instance providers implement the same methods, GetObjectAsync and ExecQueryAsync. To support the other features, class providers implement PutClassAsync, DeleteClassAsync, and CreateClassEnumAsync. Instance providers have their own versions that they implement: PutInstanceAsync, DeleteInstanceAsync, and CreateInstanceEnumAsync.

For information about implementing any of these methods, see one of the following topics:

Implementing IWbemServices::GetObjectAsync

Supporting Query Processing

Implementing IWbemServices::PutClassAsync

Implementing IWbemServices::PutInstanceAsync

Implementing IWbemServices::DeleteClassAsync

Implementing IWbemServices::DeleteInstanceAsync

Implementing IWbemServices::CreateClassEnumAsync

Implementing IWbemServices::CreateInstanceEnumAsync


Pull and Push Providers

Class providers can be modeled as:

  • Pull providers
  • Push providers

Instance providers can be modeled only as pull providers

These models specify how a provider expects to interact with WMI and the CIM repository. Push providers have significant interaction with WMI and the CIM repository. Because they manage data that does not change frequently, these providers use the CIM repository for storage, thereby avoiding the run-time overhead of generating the class definitions repeatedly. Also, because WMI operates efficiently with its own CIM repository and generates event notifications when a change is detected, push providers can avoid having to support data retrieval or event notification. Push providers update the CIM repository with their data only at initialization time.

Pull providers have minimal interaction with WMI and the CIM repository. The data managed by a pull provider typically changes frequently, requiring the provider to either generate it dynamically or retrieve it from a local cache whenever an application issues a request. Pull providers must implement their own data retrieval, cache, and event notification mechanisms. Using the WMI implementation and the CIM repository is not practical. Most providers are modeled as pull providers.

Push and pull providers differ in complexity. Push providers are the simplest, and pull providers are the most complex. The degree of complexity relates to the number of interface methods that a provider implements and the type of implementation.

Whereas most providers implement IWbemProviderInit for initialization and at least one other interface as their primary interface, push providers implement only IWbemProviderInit. In their implementation of IWbemProviderInit::Initialize, a push provider ensures that the CIM repository contains only current data. The push provider retrieves its class data and places it in the CIM repository and deletes any data that is obsolete. After initialization is complete, all application requests for classes belonging to the push provider are handled by WMI without any further provider interaction. The push provider effectively acts like a client of WMI rather than a provider. The WDM class provider included with the WMI SDK is modeled as a push provider.

When push providers are calling WMI to create, update, or remove data, they must set the lFlags parameter to include the WBEM_FLAG_OWNER_UPDATE flag in their calls to IWbemServices methods.

The following diagram illustrates the difference between pull and push providers as they handle application requests. Pull providers receive a request from WMI and satisfy the request either by generating the data dynamically or retrieving it from a local cache. WMI uses data in the CIM repository to handle all application requests for push providers.

Class providers that manage a limited amount of slowly changed or completely static data should be implemented as push providers. This is especially true for class providers. This approach has several advantages:

  • The provider does not need to implement a local cache to store its data.
  • The provider does not need to support data retrieval; it can rely on WMI to provide that support.

    When an application makes a request for data supplied by the provider, WMI fulfills that request.

  • The provider does not need to support event notification; it can rely on WMI to provide that support.

    Because the provider's data is stored in the CIM repository, WMI can generate intrinsic event notifications when changes are detected.


Registering Class and Instance Providers

Class and instance providers register with WMI by creating an instance of the __Win32Provider class and an instance of either the __ClassProviderRegistration or __InstanceProviderRegistration class. The __Win32Provider instance describes the provider's physical implementation, while the __ClassProviderRegistration and __InstanceProviderRegistration instances describe the provider's feature set.

Many of the properties of the __ClassProviderRegistration and __InstanceProviderRegistration classes are inherited from the superclass, __ObjectProviderRegistration. The __ObjectProviderRegistration class contains the InteractionType property to indicate whether the provider is a pull or push provider; several Boolean values for indicating support for particular features; and an array of strings to indicate query support. For example, an instance provider might use the following registration instances.

instance of __Win32Provider as $P
{
    Name="TestProv";
    CLSID="{A41602A4-C038-11d1-AEB6-00C04FB68820}";
};

instance of __InstanceProviderRegistration
{
    Provider = $P;
    SupportsGet = TRUE;
    SupportsEnumeration = TRUE;
    QuerySupportLevels = { "WQL:UnarySelect" };
};

The class itself must be tagged with two standard qualifiers, Dynamic and Provider. The Dynamic qualifier signals to WMI that it should use a provider rather than WMI to retrieve the instances. The Provider qualifier specifies the name of the provider that WMI should use.

[ dynamic,
  provider("TestProv")
]

class TestClass
{
    [key] string KeyVal;

    string StrVal1;

    sint32 IntVal1;
    sint32 IntVal2;

    sint32 IntArray2[];
};

WMI requires all class providers to support at least Get and Enumerate methods. In classes that lack this support, provider registration will fail. WMI provides support for any operation that a provider is missing if at all possible. Push providers, for example, do not support any operations and rely on WMI exclusively. Other providers support one or more operations. For more information about registering for particular features, see the documentation for the __ObjectProviderRegistration system class.

The properties directly defined in the __ClassProviderRegistration class include the object path to the provider and more detailed information about the classes that are supported. There are three query properties:

  • ResultSetQueries
  • ReferencedSetQueries
  • UnsupportedQueries

When used together, these three properties describe the entire range of classes supplied by the class provider. The class provider uses special WMI Query Language (WQL) SELECT statements called schema queries to specify the types of classes that it supports. Schema queries specify a special class name called meta_class.

The ResultSetQueries property contains information about the result set that the provider supplies. This information is used by WMI to determine whether to invoke the provider to satisfy an application's query. ResultSetQueries describes either the set of all classes that can be supplied or a superset of those classes but never a subset.

The UnsupportedQueries property contains information about the result set that a class provider does not supply. The UnsupportedQueries property is used to subtract from the set of classes implied by ResultSetQueries. For example, a class provider can specify in ResultSetQueries that it supplies all classes derived from MyClass and specify in UnsupportedQueries that it does not supply one particular derived class. Providers are required to specify at least one query in the ResultSetQueries property.

The more information that a provider can register about its query processing capabilities, the faster it will run. Entering one or more queries in the UnsupportedQueries property is one way to be specific and is particularly important when a provider relies on a class that it does not supply. When a request is made for a class that is listed in a query in the UnsupportedQueries property, WMI can know to supply the class itself or invoke an alternate provider to supply it.

For each class supplied, there must be a separate query. WMI does not support the use of the OR clause. For example, if a class provider supplies MyClass1, MyClass2, and MyClass3, the following queries must be specified in ResultSetQueries:

SELECT * FROM meta_class WHERE __Class = "MyClass1"
SELECT * FROM meta_class WHERE __Class = "MyClass2"
SELECT * FROM meta_class WHERE __Class = "MyClass3"

To indicate that only subclasses of a given class (but not the superclass) are supplied, specify this query in ResultSetQueries:

SELECT * FROM meta_class WHERE __Dynasty = "MyClass"

To indicate that a class and all of its subclasses are supplied, use the special __this property and set ResultSetQueries to:

SELECT * FROM meta_class WHERE __this ISA "MyClass"

The ReferencedSetQueries property specifies the set of referenced classes that the provider can supply. For example, if a provider supplies an association class that references the Win32_LogicalDisk class, ReferencedSetQueries must be set to:

SELECT * FROM meta_class WHERE __Class = "Win32_LogicalDisk"

A provider supplying classes that reference other unknown classes can specify the following general query.

SELECT * FROM meta_class

The ReferencedSetQueries property is used by WMI to determine whether to bypass the provider in schema queries where associations and references are being requested. Providers that can supply association classes must include at least one query in their ReferencedSetQueries property.


Supporting Query Processing

The current version of WMI does not support query processing for class providers. Class providers must return WBEM_E_PROVIDER_NOT_CAPABLE from their implementation of IWbemServices::ExecQueryAsync, set their QuerySupportLevels registration property to NULL, or both.

Instance providers have the option of supporting query processing or relying on WMI for that service. To support queries, an instance provider must be capable of parsing simple Structured Query Language (SQL) statements, executing the requested query, and delivering the result set objects to the requester's sink.

If a provider supports query processing, WMI sends a query directly to the provider, which parses it. It is important to note that WMI does not modify the query sent to the provider, regardless of whether this is a WMI Query Language (WQL) query.

In the current WMI release, WMI only delivers simple unary "select" queries to an instance provider. The provider can elect to refuse the query as being too complex. When this happens, WMI may:

  • Retry the provider with a simpler query, possibly a superset.
  • Elect instead to enumerate the instances.

WMI must retrieve a superset of the required instances so that it can perform the filtering operations of the query itself. The following sample shows a typical instance provider implementation of ExecQueryAsync.

HRESULT CStdProvider::ExecQueryAsync(
            /* [in] */ BSTR strQueryLanguage,
            /* [in] */ BSTR strQuery,
            /* [in] */ long lFlags,
            /* [in] */ IWbemContext __RPC_FAR *pCtx,
            /* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler
            )
{
   IWbemClassObject *pClass = 0;

// Parse the query

    if (!ParseQuery(strQuery))  return WBEM_E_PROVIDER_NOT_CAPABLE;

// Assume we have an IWbemServices pointer available so
// that we can retrieve the class definition.

    HRESULT hRes = m_pSvc->GetObject(strClass, 0, NULL, &pClass, 0);
    if (FAILED(hRes))
        return hRes;

// Now loop through our private source and create each
// instance which is part of the result set of the query.

    While (1)
    {
// Prepare an empty object to receive the class def.
         IWbemClassObject *pNextInst = 0;
         pClass->SpawnInstance(0, &pNextInst);

// Create the instance
         FillInst(pNextInst);

// Deliver the class to WMI.
         pResponseHandler->Indicate(1, &pNextInst);
         pNextClass->Release( );
    }

// Tell WMI we are finished.

    pResponseHandler->SetStatus(0, WBEM_S_NO_ERROR, 0, 0);

    return WBEM_S_NO_ERROR;
}

It is important to note that the instance provider has acquired a thread from WMI to perform these operations. It may be desirable to call the sink's AddRef method and create another thread for delivering the objects in the result set. This strategy allows the current thread to return to WMI without depleting the thread pool. Whether the provider chooses the single thread design over the dual thread design depends on how long the provider plans on using the WMI thread. There are no fixed rules. Experimentation can help the implementer determine whether WMI performance is adversely affected with either design.

The instance provider should return one of the following codes from ExecQueryAsync, either by its return code or by the sink object pointed to by the pResponseHandler parameter. If the sink is used, the return code sent to it takes precedence. Note that because WMI will have already parsed the query, the provider should not return the WBEM_E_INVALID_QUERY error code.

Return code | Description
WBEM_S_NO_ERROR | ExecQueryAsync was successful.
WBEM_E_NOT_FOUND | The provider could not recognize the class name.
WBEM_E_PROVIDER_NOT_CAPABLE | The provider cannot execute the query due to its complexity, even though it recognizes the syntax. Return this code in all cases when a more specific code is not required.
WBEM_E_FAILED | The provider failed internally, even though the operation was valid.
WBEM_E_UNSUPPORTED_FLAGS | lFlags contains fields that were not recognized.


Implementing IWbemServices::GetObjectAsync

Both class providers and instance providers implement the IWbemServices::GetObjectAsync method. Class providers implement this method if they must dynamically generate their classes; instance providers implement it to retrieve instances in response to client requests. The implementations are similar. Both provider types use an object path to locate the requested class or instance.

For specific information about implementing GetObjectAsync, see one or both of the following topics:

GetObjectAsync for Class Providers

GetObjectAsync for Instance Providers


GetObjectAsync for Class Providers

Instance providers implement IWbemServices::GetObjectAsync to retrieve individual classes. Class providers that implement GetObjectAsync use object paths to identify requested classes. Class object paths consist of the class name surrounded by either single or double quotes.

GetObjectAsync must determine which class is being requested by parsing the class name object path stored in the strObjectPath parameter. GetObjectAsync then either builds the class dynamically or takes it from a private cache and sends it to WMI using the IWbemObjectSink pointer pointed to by the pResponseHandler parameter.

The following code sample shows how a typical class provider would implement GetObjectAsync.

HRESULT CStdProvider::GetObjectAsync(
            /* [in] */ BSTR strObjectPath,
            /* [in] */ long lFlags,
            /* [in] */ IWbemContext __RPC_FAR *pCtx,
            /* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler
            )
{

    IWbemClassObject *pClass = 0;

// Assume we have an IWbemServices pointer available.
// We retrieve an 'empty' object which will be built up
// into the class definition.

    HRESULT hRes = m_pSvc->GetObject(NULL, 0, NULL, &pClass, 0);
    if (hRes)
        return hRes;

// Parse the object path and determine which class is
// required. The path string will be the required class name.
// Fill in the properties required for the class definition
// using pClass->Put(…), etc.

    // …

    // Send the class definition back to WMI.
    pResponseHandler->Indicate(1, &pClass);

// Indicate that we are now finished.

    pResponseHandler->SetStatus(0, WBEM_S_NO_ERROR, 0, 0);
    pClass->Release( );  // we no longer need this
    return WBEM_S_NO_ERROR;
}

The class provider should return one of the following codes from GetObjectAsync.

Return code | Description
WBEM_S_NO_ERROR | GetObjectAsync was successful.
WBEM_E_NOT_FOUND | The provider could not recognize the requested class.
WBEM_E_PROVIDER_NOT_CAPABLE | The provider could not retrieve the requested instance, even though the class name was recognized as being supplied by the provider.
WBEM_E_FAILED | The provider failed internally, even though the operation was valid.
WBEM_E_UNSUPPORTED_FLAGS | lFlags contained fields that were not recognized.


GetObjectAsync for Instance Providers

Instance providers implement IWbemServices::GetObjectAsync to retrieve individual instances. When an application or WMI calls GetObjectAsync, the path to the target instance is placed in the ObjectPath parameter. The strObjectPath parameter can be in any of the following formats:

  • Namespace:Class.Key = "Value"
  • Namespace:Class = "Value"
  • Namespace:Class.Key = "Value", Key2 = "Value2"

Specifying the namespace before the class is optional. Object paths without namespaces refer to instances in the current namespace. It is recommended that the object path parser sample code in the WMI SDK be used to parse object paths for recognizing which object is being requested.

The single-quote character (') can be substituted for the double-quote character (") to delimit the start and end of string property types.

Providers that support derived classes need only supply the values for the local properties of the class and not worry about the inherited properties. WMI requests that the provider of the base class handle those properties.

The following code is an example of an implementation of GetObjectAsync for an instance provider.

SCODE CInstPro::GetObjectAsync (BSTR ObjectPath,
                                long lFlags, IWbemContext *pCtx,
                                IWbemObjectSink FAR* pHandler)
{
    ULONG cRef;         // Reference count
    SCODE sc;
    BOOL bOK = FALSE;

    IWbemServices *  m_pNamespace;
    IWbemClassObject FAR* pObj;

    // Check arguments

    if(ObjectPath == NULL || pHandler == NULL || m_pNamespace == NULL)
        return WBEM_E_INVALID_PARAMETER;

    // Get the instance and send it back

    sc = GetByPath (ObjectPath, &pObj, pCtx);
    if(sc == S_OK)
    {
        pHandler->Indicate (1, &pObj);
        pObj->Release();
        bOK = TRUE;
    }

    sc = (bOK) ? S_OK : WBEM_E_NOT_FOUND;

    // Set Status

    pHandler->SetStatus(0,sc, NULL, NULL);
    return sc;
}

The instance provider should return one of the following codes from GetObjectAsync.

Return code | Description
WBEM_S_NO_ERROR | GetObjectAsync was successful.
WBEM_E_NOT_FOUND | The provider could not recognize the requested instance.
WBEM_E_PROVIDER_NOT_CAPABLE | The provider could not retrieve the requested instance, even though the object path was recognized as being supplied by this provider.
WBEM_E_FAILED | The provider failed internally, even though the operation was valid.
WBEM_E_UNSUPPORTED_FLAGS | lFlags contained fields that were not recognized.


Implementing IWbemServices::PutClassAsync

IWbemServices::PutClassAsync is implemented by class providers that support the modification or creation of new classes. The lFlags parameter indicates whether the caller wants the provider to reject the request if the class to be updated does not yet exist. There are six valid values for lFlags:

  • WBEM_FLAG_UPDATE_ONLY
  • WBEM_FLAG_CREATE_ONLY
  • WBEM_FLAG_CREATE_OR_UPDATE
  • WBEM_FLAG_UPDATE_COMPATIBLE
  • WBEM_FLAG_UPDATE_SAFE_MODE
  • WBEM_FLAG_UPDATE_FORCE_MODE

Class providers can report success or failure either with the return code from PutClassAsync or through a call to SetStatus made through pResponseHandler. If the latter mechanism is used, the return code sent to the sink through pResponseHandler takes precedence. Class providers should return one of the following codes.

Return code | Description
WBEM_S_NO_ERROR | PutClassAsync was successful.
WBEM_E_NOT_FOUND | The provider could not recognize the class name.
WBEM_E_INVALID_CLASS | The class is considered invalid for the provider.
WBEM_E_PROVIDER_NOT_CAPABLE | The provider cannot create or update classes. Return this error code in all cases if a more specific one is not required.
WBEM_E_FAILED | The provider failed internally, even though the operation was valid.
WBEM_E_UNSUPPORTED_FLAGS | lFlags contained fields that were not recognized.

Because returning WBEM_E_FAILED causes other providers not to have a chance to create the class, it should only be returned when the class provider has failed in a way that might later succeed.

If there multiple class providers are installed, than interesting problem associated with class creation can arise, because WMI does not know which class provider will be capable of creating a particular new class.

The provider simply receives the new class definition and reports success or failure of the creation.

HRESULT CStdProvider::PutClassAsync(
            /* [in] */ IWbemClassObject __RPC_FAR *pObject,
            /* [in] */ long lFlags,
            /* [in] */ IWbemContext __RPC_FAR *pCtx,
            /* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler
            )
{

   If (ClassIsValid(lFlags, pObject)) return WBEM_S_NO_ERROR;

   Return WBEM_E_PROVIDER_NOT_CAPABLE;
}


Implementing IWbemServices::DeleteClassAsync

Class providers implement IWbemServices::DeleteClassAsync to support class deletion. To implement this method, a class provider examines the class name specified in the strClass parameter and attempts to locate it and then delete it. The following code sample shows how to implement DeleteClassAsync.

HRESULT CStdProvider::DeleteClassAsync(
            /* [in] */ BSTR strClass,
            /* [in] */ long lFlags,
            /* [in] */ IWbemContext __RPC_FAR *pCtx,
            /* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler
            )
{
    if (DeleteClass(lFlags, strClass))
        return WBEM_S_NO_ERROR;

    return WBEM_E_NOT_FOUND;
}

Class providers can report success or failure either with the return code from DeleteClassAsync or through a call to SetStatus made through pResponseHandler. If the latter mechanism is used, the return code sent to the sink through pResponseHandler takes precedence. Class providers should return one of the following codes.

Return code | Description
WBEM_S_NO_ERROR | DeleteClassAsync was successful.
WBEM_E_NOT_FOUND | The provider could not recognize the class name.
WBEM_E_PROVIDER_NOT_CAPABLE | The provider cannot delete classes regardless of whether it recognizes the name. Return this error code in all cases if a more specific one is not required.
WBEM_E_FAILED | The provider failed internally, even though the operation was valid.
WBEM_E_UNSUPPORTED_FLAGS | lFlags contained fields that were not recognized.


Implementing IWbemServices::CreateClassEnumAsync

IWbemServices::CreateClassEnumAsync is called to ask a class provider to enumerate all of the classes that it supports. The class provider should create each class definition from scratch and deliver it to the sink pointed to by pResponseHandler. Providers should only return subclasses of the requested class and not the class itself.

The following code sample shows how to implement CreateClassEnumAsync.

HRESULT CStdProvider::CreateClassEnumAsync(
            /* [in] */ BSTR strSuperclass,
            /* [in] */ long lFlags,
            /* [in] */ IWbemContext __RPC_FAR *pCtx,
            /* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler
            )
{
   IWbemClassObject *pClass = 0;

// Assume we have an IWbemServices pointer available.
// We retrieve an 'empty' object which will be built up
// into the class definition.

    HRESULT hRes = m_pSvc->GetObject(NULL, 0, NULL, &pClass, 0);
    if (hRes)
        return hRes;

 // Now loop through our private source of class definitions
// and create each class.

    While (1)
    {
// Prepare an empty object to receive the class def.
         IWbemClassObject *pNextClass = 0;
         pClass->Clone(&pNextClass);

// Create the class definition elsewhere.
         FillClassDef(pNextClass);

// Deliver the class to WMI.
         pResponseHandler->Indicate(1, &pNextClass);
         pNextClass->Release( );
    }

pClass->Release();

// Tell WMI we are finished.

    pResponseHandler->SetStatus(0, WBEM_S_NO_ERROR, 0, 0);

    return WBEM_S_NO_ERROR;
}

It is important to note that the instance provider has acquired a thread from WMI to perform these operations. It may be desirable to call the sink's AddRef method and create another thread for delivering the objects in the result set. This strategy allows the current thread to return to WMI without depleting the thread pool. Whether the provider chooses the single thread design over the dual thread design depends on how long the provider plans on using the WMI thread. There are no fixed rules. Experimentation can help the implementer determine whether WMI performance is adversely affected with either design.

Class providers can report success or failure either with the return code from CreateClassEnumAsync or through a call to SetStatus made through pResponseHandler. If the latter mechanism is used, the return code sent to the sink through pResponseHandler takes precedence. Class providers should return one of the following codes.

Return code | Description
WBEM_S_NO_ERROR | CreateClassEnumAsync was successful.
WBEM_E_NOT_FOUND | The provider could not recognize the class name.
WBEM_E_PROVIDER_NOT_CAPABLE | The provider cannot enumerate classes regardless of whether it recognizes the name. Return this error code in all cases if a more specific one is not required.
WBEM_E_FAILED | The provider failed internally, even though the operation was valid.
WBEM_E_UNSUPPORTED_FLAGS | lFlags contained fields that were not recognized.


Implementing IWbemServices::PutInstanceAsync

Instance providers implement IWbemServices::PutInstanceAsync to update or create instances of a given class.

If the instance has a key property that the application has set to NULL, PutInstanceAsync should choose a value that is guaranteed to be unique within the class. When WMI services a request to update an instance with a NULL key property, it internally generates a GUID and assigns it to the key property.

The lFlags parameter specifies whether or not the caller wants the instance to be created if it does not currently exist. The lFlags parameter can have the following values:

  • WBEM_FLAG_UPDATE_ONLY
  • WBEM_FLAG_CREATE_ONLY
  • WBEM_FLAG_CREATE_OR_UPDATE

Instance providers can choose to support updating existing instances only, support either operation, or refuse an update request completely by returning WBEM_E_PROVIDER_NOT_CAPABLE. Providers that support some form of update can further choose whether they allow partial instances to be modified or only full instances. A partial instance update modifies a subset of the properties of the instance whereas a full instance update modifies all of the properties. To determine whether the caller is requesting a full or partial update, an instance provider must check the pCtx parameter.

If pCtx is NULL, the entire instance should be updated. Each property is modified as follows.

  • If the property's type is VT_NULL, the provider can either ignore the property without making a change or fail the operation.
  • If the property's type is not VT_NULL and the property cannot be updated, the provider should return an error, because it is obligated to update the property with the new value.

If pCtx is not NULL and points to valid context information, the caller application is requesting a partial instance update. Instance provider that do not support partial instance updating should fail the operation by returning WBEM_E_PROVIDER_NOT_CAPABLE.

Instance providers supporting a partial update must check for the existence of a particular system context value, __PUT_EXTENSIONS. System context values are defined by WMI to have specific meanings that are set by client applications and supported by instance providers. System context values resemble system classes and system properties because they also begin with a double-leading underscore. The IWbemContext interface provides access to system context values and other provider-specific context values.

The following system context values are used to support partial instance update operations.

System context value | Description
__PUT_EXTENSIONS (VT_BOOL) | Indicates that one or more of the other system context values has been set, providing additional information about the update operation.
__PUT_EXT_STRICT_NULLS (VT_BOOL) | Indicates that the instance provider must force the setting of properties to VT_NULL when appropriate and raise an error on failure.
__PUT_EXT_PROPERTIES (VT_ARRAY | VT_BSTR) | Contains a list of the properties to update; the instance provider should ignore all others.
__PUT_EXT_ATOMIC (VT_BOOL) | Indicates that all updates must succeed or the instance provider must revert back. There can be no partial success.

The following code sample shows how PutInstanceAsync can be structured.

HRESULT CStdProvider::PutInstanceAsync(
            /* [in] */ IWbemClassObject __RPC_FAR *pInst,
            /* [in] */ long lFlags,
            /* [in] */ IWbemContext __RPC_FAR *pCtx,
            /* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler
            )
{

   If (InstanceIsValid(lFlags, pInst))
       return WBEM_S_NO_ERROR;

   return WBEM_E_PROVIDER_NOT_CAPABLE;
}

Instance providers can report success or failure either with the return code from PutInstanceAsync or through a call to SetStatus made through pResponseHandler. If the latter mechanism is used, the return code sent to the sink through pResponseHandler takes precedence. Instance providers should return one of the following codes:

Return code | Description
WBEM_S_NO_ERROR | PutInstanceAsync was successful.
WBEM_E_NOT_FOUND | The provider could not recognize the instance, or the instance is not valid for this provider.
WBEM_E_PROVIDER_NOT_CAPABLE | The provider cannot create or update the instance. Return this error code in all cases if a more specific one is not required.
WBEM_E_FAILED | The provider failed internally, even though the operation was valid. Return this code only when the provider has failed in a way that might have later succeeded.
WBEM_E_UNSUPPORTED_FLAGS | lFlags contained fields that were not recognized.

When the instance being updated belongs to a child class, the success of the operation is dependent on the success of a PutInstanceAsync call to each of the providers responsible for the classes higher in the hierarchy. Do not return WBEM_S_NO_ERROR until it is clear that all of the other providers have succeeded. For more information, see the Remarks section for the documentation of IWbemServices::PutInstance.


Implementing IWbemServices::DeleteInstanceAsync

Instance providers implement IWbemServices::DeleteInstanceAsync to support instance deletion. To implement this method, an instance provider parses the object path string specified in the strObjectPath parameter and attempts to locate the corresponding instance and delete it. The following code sample shows how to implement DeleteInstanceAsync.

HRESULT CStdProvider::DeleteInstanceAsync(
            /* [in] */ BSTR strObjectPath,
            /* [in] */ long lFlags,
            /* [in] */ IWbemContext __RPC_FAR *pCtx,
            /* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler
            )
{
    if (DeleteClass(lFlags, strClass))
        return WBEM_S_NO_ERROR;

    return WBEM_E_NOT_FOUND;
}

Instance providers can report success or failure either with the return code from DeleteInstanceAsync or through a call to SetStatus made through pResponseHandler. If the latter mechanism is used, the return code sent to the sink through pResponseHandler takes precedence. Instance providers should return one of the following codes:

Return code | Description
WBEM_S_NO_ERROR | DeleteInstanceAsync was successful.
WBEM_E_NOT_FOUND | The provider could not recognize the instance.
WBEM_E_PROVIDER_NOT_CAPABLE | The provider cannot delete instances regardless of whether it recognizes the name. Return this error code in all cases if a more specific one is not required.
WBEM_E_FAILED | The provider failed internally, even though the operation was valid.
WBEM_E_UNSUPPORTED_FLAGS | lFlags contained fields that were not recognized.

When the instance being deleted belongs to a class that is a member of a class hierarchy, the success of the operation is dependent on the success of a DeleteInstanceAsync call on the topmost non-abstract class. For example, consider a DeleteInstanceAsync call where the strObjectPath parameter points to an instance of ClassC. This class derives from a non-abstract class called ClassB, which derives from an abstract class called ClassA. The ClassC instance can be deleted successfully only if the DeleteInstanceAsync call to the provider responsible for ClassB succeeds. For more information, see the Remarks section for the documentation of IWbemServices::DeleteInstance.


Implementing IWbemServices::CreateInstanceEnumAsync

IWbemServices::CreateInstanceEnumAsync is called to ask an instance provider to enumerate all of the instances of a supported class. The instances should be delivered to the sink pointed to by the pResponseHandler parameter. The following code sample shows how to implement CreateInstanceEnumAsync.

HRESULT CStdProvider::CreateInstanceEnumAsync(
            /* [in] */ BSTR strClass,
            /* [in] */ long lFlags,
            /* [in] */ IWbemContext __RPC_FAR *pCtx,
            /* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler
            )
{
   IWbemClassObject *pClass = 0;

// Assume we have an IWbemServices pointer available so
// that we can retrieve the class definition.

    HRESULT hRes = m_pSvc->GetObject(strClass, 0, NULL, &pClass, 0);
    if (hRes)
        return hRes;

// Now loop through our private source and create each instance.

    While (1)
    {
// Prepare an empty object to receive the class definition.
         IWbemClassObject *pNextInst = 0;
         pClass->SpawnInstance(0, &pNextInst);

// Create the instance
         FillInst(pNextInst);

// Deliver the class to WMI.
         pResponseHandler->Indicate(1, &pNextInst);
         pNextClass->Release( );
    }

// Tell WMI we are finished.

    pResponseHandler->SetStatus(0, WBEM_S_NO_ERROR, 0, 0);

    return WBEM_S_NO_ERROR;
}

It is important to note that the instance provider has acquired a thread from WMI to perform these operations. It may be desirable to call the sink AddRef method and create another thread for delivering the objects in the result set. This strategy allows the current thread to return to WMI without depleting the thread pool. Whether the provider chooses the single thread design over the dual thread design depends on how long the provider plans on using the WMI thread. There are no fixed rules. Experimentation can help the implementer determine whether WMI performance is adversely affected with either design.

Instance providers can report success or failure either with the return code from CreateInstanceEnumAsync or through a call to SetStatus made through pResponseHandler. If the latter mechanism is used, the return code sent to the sink through pResponseHandler takes precedence. Instance providers should return one of the following codes.

Return code | Description
WBEM_S_NO_ERROR | CreateInstanceEnumAsync was successful.
WBEM_E_NOT_FOUND | The provider could not recognize the class name.
WBEM_E_PROVIDER_NOT_CAPABLE | The provider cannot enumerate instances regardless of whether it recognizes the name. Return this error code in all cases if a more specific one is not required.
WBEM_E_FAILED | The provider failed internally, even though the operation was valid.
WBEM_E_UNSUPPORTED_FLAGS | lFlags contained fields that were not recognized.


Method Providers

Method providers allow management applications to invoke methods that are defined for a particular class. They register with Windows Management Instrumentation (WMI) by creating an instance of the __Win32Provider class and an instance of the __MethodProviderRegistration class.

Method providers implement IWbemProviderInit to support initialization and the IWbemServices::ExecMethodAsync method to support client requests. However, many method providers also serve as instance providers. Pure method providers return WBEM_E_PROVIDER_NOT_CAPABLE from all IWbemServices methods except ExecMethodAsync. Combination method and instance providers must support more of the IWbemServices methods. See Class and Instance Providers for more information.


Registering a Method Provider

Method providers create an instance of the __MethodProviderRegistration system class. The only property of the ____MethodProviderRegistration class is the object path to the provider's __Win32Provider instance.

The following MOF statements supply examples of instances that can be used to register a method provider.

  instance of __Win32Provider as $P
  {
    Name    = "MethProvider" ;
    ClsId   = "{E30EC6A0-23CF-11d1-8FDE-0000F804AA5C}" ;
  };

  instance of __MethodProviderRegistration
  {
    Provider = $P;
  };


Implementing IWbemServices::ExecMethodAsync

Method providers must implement IWbemServices::ExecMethodAsync to allow applications to invoke a method of a class or instance. There are six parameters to the method:

  • The object path for the class or instance that contains the method
  • The name of the method
  • The flag for requesting intermediate status reports
  • An IWbemClassObject pointer for accessing the input parameters
  • An IWbemObjectSink pointer for delivering the output parameters
  • An optional IWbemContext pointer that is typically set to NULL.

    However, if it is not set to NULL, the method provider must pass it in any call that it makes to WMI.

For each input parameter to the method to be called, there is one non-system property. Because not all methods have input parameters, method providers must be able to accept NULL for the pInParams parameter to ExecMethodAsync.

Method providers ignore the Id qualifiers attached to each parameter in the method. Id qualifiers are typically used only by browsers and similar applications.

A single method provider can supply methods for many classes and instances. Static methods can be invoked using either a class name or an object path to an instance. The method provider can parse the object path parameter to determine the class and instance that contain the method definition.

The input and output parameters are represented by instances of the __PARAMETERS system class. One instance of this class is created for the input parameters; another instance is created for the output parameters and return value. Therefore, if the method has both input and output parameters, two __PARAMETERS class instances are created. The output parameter's __PARAMETERS class instance is passed to the caller through the IWbemObjectSink::Indicate method. Method providers call Indicate to return output parameter information before they call IWbemObjectSink::SetStatus to report the final status.

Method providers have to deal with a maximum of three return values.

Return value | Description
From ExecMethodAsync (required) | Indicates whether or not the input parameters for the method that are pointed to by the pInParams parameter are valid. Can be set to WBEM_S_NO_ERROR or WBEM_E_INVALID_PARAMETER.
From the method to be invoked (optional) | Specific value and meaning is dependent on the method. The return value is placed in the ReturnValue property of the __PARAMETERS instance representing the output parameters.
From the method to be invoked (optional output parameters) | Specific value and type is dependent on the method. Output parameters are placed in non-system properties of a __PARAMETERS instance.

After a method provider determines that the input parameters are correct, the method pointed to by strMethodName might still pass or fail. Some method providers spawn a second thread to implement the method so that the method's actual success or failure ends up being reported to the caller through the IWbemObjectSink pointer. The following procedure describes how to create a system class instance to hold output parameter information.

To create an instance of the __PARAMETERS system class

  1. Determine the class path for the class containing the method definition.
  2. Using the class path and the IWbemServices pointer passed in from IWbemProviderInit::Initialize, call IWbemClassObject::GetMethod to retrieve the input and output parameter classes.

    GetMethod returns an IWbemClassObject pointer for accessing each of these classes.

  3. Using the IWbemClassObject pointer for the output class, call IWbemClassObject::SpawnInstance to create an instance of the class.
  4. Populate the instance by setting the properties that correspond to the output values and (if there is a return value for the method) the ReturnValue system property.
  5. Pass the __PARAMETERS instance back to the caller through the IWbemObjectSink::Indicate method.

In the following example, the method provider supports a single method on a single class. For brevity, error checking is eliminated, and there are no input or output parameters.

STDMETHODIMP CMethodPro::ExecMethodAsync(BSTR ObjectPath,
    BSTR MethodName, long lFlags, IWbemContext* pCtx,
    IWbemClassObject* pInParams, IWbemObjectSink* pResultSink)
{
    // Lets just beep
    MessageBeep(0);
    hr = pResultSink->SetStatus(0,S_OK,NULL,NULL);
    return WBEM_S_NO_ERROR;
}

For a more realistic example, assume the following class definition.

[dynamic: ToInstance, provider("MethProvider")]
class TestMeth
{
    [implemented, static]
    uint32 Echo([IN]string sInArg, [out] string sOutArg);
};

The TestMeth class supports a method that has one input parameter and one output parameter and that returns an unsigned 32-bit integer. The following sample code shows how to implement IWbemServices::ExecMethodAsync for the TestMeth method. The implementation assumes that there is only one method called TestMeth and one class that contains it. For the sake of brevity, there is no error checking or object path parsing.

STDMETHODIMP CMethodPro::ExecMethodAsync(BSTR ObjectPath,
    BSTR MethodName, long lFlags, IWbemContext* pCtx,
    IWbemClassObject* pInParams, IWbemObjectSink* pResultSink)
{
    HRESULT hr;
    IWbemClassObject * pClass = NULL;
    IWbemClassObject * pOutClass = NULL;
    IWbemClassObject* pOutParams;

    // Allocate some BSTRs

    BSTR ClassName = SysAllocString(L"TestMeth");
    BSTR InputArgName = SysAllocString(L"sInArg");
    BSTR OutputArgName = SysAllocString(L"sOutArg");
    BSTR retValName = SysAllocString(L"ReturnValue");

    // Get the class object, this is hard coded and matches the class
    // in the MOF.  A more sophisticated example would parse the
    // ObjectPath to determine the class and possibly the instance.

    hr = m_pWbemSvcs->GetObject(ClassName, 0, pCtx, &pClass, NULL);

    // This method returns values, and so create an instance of the
    // output argument class.

    hr = pClass->GetMethod(MethodName, 0, NULL, &pOutClass);
    pOutClass->SpawnInstance(0, &pOutParams);

    // Copy the input argument into the output object

    VARIANT var;
    VariantInit(&var);

    // Get the input argument
    pInParams->Get(InputArgName, 0, &var, NULL, NULL);

    // put it into the output object
    pOutParams->Put(OutputArgName , 0, &var, 0);

    long lLen = wcslen(var.bstrVal);
    VariantClear(&var);
    var.vt = VT_I4;
    var.lVal = lLen;
    // special name for return value.
    pOutParams->Put(retValName , 0, &var, 0);

    // Send the output object back to the client via the sink. Then
    // release the pointers and free the strings.

    hr = pResultSink->Indicate(1, &pOutParams);
    pOutParams->Release();
    pOutClass->Release();
    pClass->Release();
    SysFreeString(ClassName);
    SysFreeString(InputArgName);
    SysFreeString(OutputArgName);
    SysFreeString(retValName);

    // all done now, set the status

    hr = pResultSink->SetStatus(0,WBEM_S_NO_ERROR,NULL,NULL);
    return WBEM_S_NO_ERROR;
}


Property Providers

Property providers retrieve and modify individual property values for instances of a given class that is stored in the Common Information Management (CIM) repository. As a Windows Management Instrumentation (WMI) provider, property providers implement IWbemProviderInit to support initialization and another primary interface to support basic functionality. The primary interface of a property provider is IWbemPropertyProvider. Property providers that return property values implement IWbemPropertyProvider::GetProperty; property provider that update property values implement IWbemPropertyProvider::PutProperty.

Property providers can support property retrieval, property modification, or both operations. Providers that do not support retrieval return WBEM_E_PROVIDER_NOT_CAPABLE from their implementation of IWbemPropertyProvider::GetProperty, and providers that do not support modification return WBEM_E_PROVIDER_NOT_CAPABLE from IWbemPropertyProvider::PutProperty.

Management applications that create classes and instances with properties to be supported by a property provider must include several standard qualifiers on their class and instance definitions. The Dynamic and Provider qualifiers appear together on a class, an instance, or a property. These qualifiers mark an item as being supported by a dynamic provider and identify the provider by name.

Note Dynamic property providers must be in-process providers. WMI will initialize property providers written as services or executable files but will never call their GetProperty and PutProperty methods.

The DynProps qualifier marks an instance as containing at least one property that is managed by a property provider. Each of the properties in an instance marked with the DynProps qualifier has the Dynamic, Provider and PropertyContext qualifiers. The PropertyContext qualifier specifies context-specific information that pertains to the property. For example, in a class that is used to store data supplied by the Registry Provider, PropertyContext is the path to the registry key that contains the property's value.

Two other context qualifiers can appear on an instance or class definition. The InstanceContext qualifier is attached to an instance and contains information that applies to every property in the instance. The ClassContext qualifier is attached to a class and contains information that applies to every instance in the class. Property providers must be prepared to handle all three types of context qualifiers.


Registering a Property Provider

Property providers register with WMI by creating an instance of the __Win32Provider system class and an instance of the __PropertyProviderRegistration system class. The properties that are defined by __PropertyProviderRegistration include the object path to the provider and more information about the provider's implementation.

The following MOF statements supply examples of instances that can be used to register a property provider.

  instance of __Win32Provider as $P
  {
    Name    = "PropProvider" ;
    ClsId   = "{E30EC6A0-23CF-11d1-8FDE-0000F804AA5C}" ;
  };

  instance of __PropertyProviderRegistration
  {
    Provider = $P;
    SupportsGet = TRUE;
    SupportsPut = FALSE;
  };

Note that the __Win32Provider instance accepts the default values for the other properties, such as the TRUE value for the Pure property. For a complete discussion of the __Win32Provider class, see its documentation in the System Class Reference.


Implementing IWbemPropertyProvider::GetProperty

The following code shows one way to implement GetProperty. The InstMapping parameter holds the context of the InstanceContext qualifier while the PropMapping parameter holds the context of the PropertyContext qualifier. This particular implementation checks the value of PropMapping and returns either a hard-coded integer or a string. The only error that it returns is WBEM_E_OUT_OF_MEMORY.

STDMETHODIMP CPropPro::GetProperty(
            long lFlags,
            BSTR Locale,
            BSTR ClassMapping,
            BSTR InstMapping,
            BSTR PropMapping,
            VARIANT *pvValue)
{
    SCODE sc = WBEM_S_NO_ERROR;

    if(!_wcsicmp(PropMapping, L"GiveMeANumber!"))
    {
        pvValue->vt = VT_I4;
        pvValue->lVal = 27;
    }
    else
    {
        pvValue->vt = VT_BSTR;
        pvValue->bstrVal = SysAllocString(L"Hello World");
        if(pvValue->bstrVal == NULL)
            sc = WBEM_E_OUT_OF_MEMORY;
    }
    return sc;
}


Event and Event Consumer Providers

Event providers supply Windows Management Instrumentation (WMI) with notifications of particular types of events. Event providers can support intrinsic events (events that report changes to data in the CIM repository) and extrinsic events (events that report changes to provider-specific managed objects). Event providers implement IWbemProviderInit to support standard initialization and IWbemEventProvider to generate events. As an option, event providers can also implement IWbemEventProviderQuerySink. For a complete discussion of how to implement these interfaces, see Implementing an Event Provider.

Event consumer providers supply a link between a logical consumer and a physical consumer (sink). Logical and physical consumers are part of the permanent consumer architecture. After registration, permanent consumers receive notifications regardless of whether they are active at the time the notifications were sent. For information about permanent consumers and event consumer providers, see the following topics:

Permanent Consumer Architecture

Implementing an Event Consumer Provider


Registering an Event Provider

Event providers register with WMI by creating an instance of the __Win32Provider system class and an instance of the __EventProviderRegistration system class. The properties that are local to the __EventProviderRegistration class are the object path to the provider and a list of queries describing the events that the provider supports.

For example, consider the following __EventProviderRegistration instance.

instance of __Win32Provider as $P
{
    ClientLoadableCLSID = NULL;
    CLSID = "{AA7828C5-95F9-11d2-BB0D-00C042424242}";
    DefaultMachineName = NULL;
    ImpersonationLevel = 0;
    InitializationReentrancy = 0;
    InitializeAsAdminFirst = FALSE;
    Name = "FaxEventProvider";
    PerLocaleInitialization = FALSE;
    PerUserInitialization = FALSE;
    Pure = TRUE;
    UnloadTimeout = NULL;
};

instance of __EventProviderRegistration
{
Provider = $P;
EventQueryList = {
         "SELECT * FROM FaxEvent",
         "SELECT * FROM __InstanceCreationEvent where TargetInstance ISA \"Win32_LogicalDisk\""};
};

The first query indicates that the provider generates all event notifications for the extrinsic event class FaxEvent. Because it uses the ISA operator, the second query implies that the provider generates notifications for all instance creation events for the Win32_LogicalDisk class and all of its subclasses.

When a provider registers to provide an intrinsic event, the event must apply to all instances of a class. In other words, a query cannot be written to provide instance creation events for only some of the disk drives that belong to the Win32_LogicalDisk class.


Registering an Event Consumer Provider

Event consumer providers register with WMI by creating an instance of the __Win32Provider system class and an instance of the __EventConsumerProviderRegistration system class. The properties that are defined by __EventConsumerProviderRegistration include the object path to the provider and the names of the logical consumer classes that the event consumer provider supports.

The following declarations show how to register an event consumer provider.

// Provider registration.
// ======================

instance of __Win32Provider as $P
{
    Name  = "MyEventConsumer";
    CLSID = "{4916157B-FBE7-11d1-AEC4-00C04FB68820}";

    DefaultMachineName = NULL;
    ClientLoadableCLSID = NULL;
    ImpersonationLevel = 0;

    PerUserInitialization = FALSE;
    Pure = TRUE;
    UnloadTimeout = NULL;
};

instance of __EventConsumerProviderRegistration
{
    Provider = $P;
    ConsumerClassNames = { "MyConsumer" };
};


Contexts for WMI Providers

[This is preliminary documentation and subject to change.]

To be written.


CIM Object Manager Provider Logs

[To be written.]


High-Performance Provider

[This is preliminary documentation and subject to change.]

The Windows Management Instrumentation (WMI) High-Performance (HiPerf) providers greatly increase the speed at which select WMI clients can obtain information from WMI. HiPerf providers require special registration and must support several of the High-Performance interfaces.


Registering High Performance Providers

[This is preliminary documentation and subject to change.]

A High-Performance provider is actually an instance provider. You register these providers with WMI by creating an instance of the __Win32Provider class and an instance of the __InstanceProviderRegistration class. The __Win32Provider instance defines the provider's physical implementation, and the __InstanceProviderRegistration instance defines the provider's feature set.

Note Refreshers cannot be registered on Microsoft® Windows® 95 or Windows 98 operating systems, or on any Windows operating system earlier than Microsoft® Windows NT® version 4.0.

Many of the properties of the _InstanceProviderRegistration class are inherited from the __ObjectProviderRegistration class. The __ObjectProviderRegistration class uses the InteractionType property to indicate:

  • Whether the provider is a pull or push provider.
  • Several Boolean values used to indicate support for particular features.
  • An array of strings that indicate query support.

HiPerf providers are, by definition, pull providers and in-process servers. WMI loads in-process servers into the client address space when requested by the client. This request can be made either through a call to the IWbemServices interface or by a remote refresh.

For a HiPerf provider to support refresh operations, it must provide a ClientLoadableCLSID in its instance of __Win32Provider. If both the provider and client reside on the same machine, the provider will be loaded in process to the client and instantiated from the ClientLoadableCLSID. When the provider and client reside on different machines, the provider is loaded in process to WinMgmt and instantiated from the CLSID value.

instance of __Win32Provider as $P
{
    Name="TestProv";
    CLSID="{A41602A4-C038-11d1-AEB6-00C04FB68820}";
};

instance of __InstanceProviderRegistration
{
    Provider = $P;
    SupportsGet = TRUE;
    SupportsEnumeration = TRUE;
};

The class itself must be tagged with two standard qualifiers, Dynamic and Provider. The Dynamic qualifier signals to WMI that it should use a dynamic provider to retrieve the instances. The Provider qualifier specifies the name of the provider.

[ dynamic,
  provider("TestProv")
]

class TestClass
{
    [key] string KeyVal;

    string StrVal1;

    sint32 IntVal1;
    sint32 IntVal2;

    sint32 IntArray2[];
};

HiPerf providers only need to specify whether they support get operations, enumeration operations, or both. WMI assumes that a provider supports refresh operations if it sees the ClientLoadableCLSID. For Query operations, WMI will perform the appropriate filtering.


Implementing a High-Performance Provider

[This is preliminary documentation and subject to change.]

High-Performance providers must be in-process servers; they are loaded in-process to either WMI itself or to a client application. When loaded in process to WMI, these providers are instantiated from a CLSID. When loaded in process to another process, the providers are instantiated from a ClientLoadable CLSID. If different values are given for these two identifiers, a provider can easily tell if it is in process to WMI or to the client application. If it is in process to WMI, the provider should do any necessary client impersonation by using CoImpersonateClient. If the provider is in process to a client, by default, the provider inherits the access token of the thread it is being called on.

In either case, WMI initializes the provider by using the IWbemProviderInit interface. All HiPerf providers must implement this interface. For more information, see IWbemProviderInit, and Initializing A Provider.


Implementing IWbemHiPerfProvider::QueryInstances

[This is preliminary documentation and subject to change.]

The IWbemHiPerfProvider::QueryInstances method enumerates all of the instances of a supported class. These instances should be delivered to the sink pointed to by the pSink parameter. WMI calls this method in response to an IWbemServices::CreateInstanceEnum or IWbemServices::CreateInstanceEnumAsync request.

The following code sample shows how to implement QueryInstances.

HRESULT CHiPerfProvider::QueryInstances(
    /* [in] */ IWbemServices* pNamespace,
    /* [in] */ BSTR strClass,
    /* [in] */ long lFlags,
    /* [in] */ IWbemContext __RPC_FAR *pCtx,
    /* [in] */ IWbemObjectSink __RPC_FAR *pSink
)
{
   IWbemClassObject *pClass = 0;

    // Use the namespace pointer to retrieve a class
    // definition.

    HRESULT hRes = pNamespace ->GetObject(strClass, 0, NULL, &pClass, 0);
    if (hRes)
        return hRes;

    // Now loop through our private source and create each instance.

    while (1)
    {
    // Prepare an empty object to receive the class definition.
         IWbemClassObject *pNextInst = 0;
         pClass->SpawnInstance(0, &pNextInst);

         // Create the instance
         FillInst(pNextInst);

         // Deliver the class to WMI.
         pResponseHandler->Indicate(1, &pNextInst);
         pNextClass->Release( );
    }

    // Tell WMI we are finished.

    pResponseHandler->SetStatus(0, WBEM_S_NO_ERROR, 0, 0);

    return WBEM_S_NO_ERROR;
}

HiPerf providers can report success or failure either through the return code from QueryInstances or through a call to the SetStatus method of pResponseHandler. If the SetStatus method is called, the return code sent to the sink through pResponseHandler takes precedence over the QueryInstances return code. HiPerf providers should return one of the following codes.

Return code | Description
WBEM_S_NO_ERROR | QueryInstances was successful.
WBEM_E_NOT_FOUND | The provider could not recognize the class name.
WBEM_E_PROVIDER_NOT_CAPABLE | The provider cannot enumerate instances regardless of whether it recognizes the name. Return this error code in all cases if a more specific one is not required.
WBEM_E_FAILED | The provider failed internally, even though the operation was valid.
WBEM_E_UNSUPPORTED_FLAGS | lFlags contained fields that were not recognized.


Implementing IWbemHiPerfProvider::GetObjects

[This is preliminary documentation and subject to change.]

The IWbemHiPerfProvider::GetObjects method retrieves selected object instances. These instances are passed to the provider with their key properties filled in. It is the job of the provider to fill in the remaining properties; WMI calls this method in response to a IWbemServices::GetObject call. If a provider does not implement this method, WMI, will attempt to service the IWbemServices::GetObject request by using the IWbemHiPerfProvider::CreateRefreshableObject method.

The following code sample shows how to implement GetObjects.

HRESULT CHiPerfProvider::GetObjects(
  /* [in] */IWbemServices *pNamespace,
  /* [in] */  long lNumObjects,
  /* [in,out] */IWbemObjectAccess **apObj,
  /* [in] */long lFlags,
  /* [in] */IWbemContext *pCtx
);
{

  for ( long i = 0; i < lNumObjects; i++ )
  {
    // Validate the instance (i.e. make sure
    // the path is good), if it fails return
    // the error

    if ( !ValidateInstance( apObj[i] ) )
      return WBEM_E_NOT_FOUND;

    // Fill out the instance
    FillInstance( apObj[i] );
  }

  return WBEM_S_NO_ERROR;
}

HiPerf providers should return one of the following codes.

Return code | Description
WBEM_S_NO_ERROR | GetObjects was successful.
WBEM_E_NOT_FOUND | The provider could not get a requested instance.
WBEM_E_PROVIDER_NOT_CAPABLE | The provider cannot retrieve specific instances, regardless of whether it recognizes the paths. Unless a more specific error code is required, return this error code in all cases.
WBEM_E_FAILED | The provider failed internally, but the operation was valid.
WBEM_E_UNSUPPORTED_FLAGS | lFlags contained fields that were not recognized.


Implementing IWbemHiPerfProvider::CreateRefresher

[This is preliminary documentation and subject to change.]

The IWbemHiPerfProvider::CreateRefresher method requests a new instance of the IWbemRefresher interface. WMI calls this method if it is going to try to use IWbemHiPerfProvider::CreateRefreshableObject to service an IWbemServices::GetObject request. The WMI Refresher calls this method when it needs a new provider-side refresher. If a provider implements CreateRefreshableObject, CreateRefreshableEnum and/or StopRefreshing, it must also implement CreateRefresher.

The following code sample shows how to implement CreateRefresher.

HRESULT CHiPerfProvider::CreateRefresher(
  /* [in] */IWbemServices *pNamespace,
  /* [in] */ long lFlags,
  /* [out] / IWbemRefresher** ppRefresher
);
{

   // Allocate a new refresher

   CMyRefresher* pMyRefresher = new CMyRefresher;

   return pMyRefresher->QueryInterface(
     IID_IWbemRefresher, (void**) ppRefresher );

}

When a refresher is released, it should clean up any refreshable objects and/or enumerators that were added to it.

Return code | Description
WBEM_S_NO_ERROR | CreateRefresher was successful.
WBEM_E_PROVIDER_NOT_CAPABLE | The provider cannot retrieve specific instances regardless of whether it recognizes the paths. Return this error code in all cases if a more specific one is not required.
WBEM_E_FAILED | The provider failed internally, even though the operation was valid.
WBEM_E_UNSUPPORTED_FLAGS | lFlags contained fields that were not recognized.
WBEM_E_REFRESHER_BUSY | The refresher is busy.


Implementing IWbemHiPerfProvider::CreateRefreshableObject

[This is preliminary documentation and subject to change.]

The IWbemHiPerfProvider::CreateRefreshableObject returns a refreshable object. WMI uses this method to service IWbemServices::GetObject if IWbemHiPerfProvider::GetObjects is not implemented. The WMI Refresher calls this method in response to a client request to IWbemConfigureRefresher::AddObjectByPath or IWbemConfigureRefresjer::AddObjectByTemplate. The provider should associate the returned object with the supplied refresher, which was obtained from an earlier call to IWbemHiPerfProvider::CreateRefresher. One possible way to do this would be to keep an array of refreshable objects in the refresher.

The provider must not access the returned object, unless the object owning the refresher restores the object. The key properties of the supplied instance template will be filled out. The provider should validate the instance path.

The following code sample shows how to implement CreateRefreshableObject.

HRESULT CHiPerfProvider::CreateRefreshableObject(
  /* [in] */IWbemServices *pNamespace,
  /* [in] */IWbemObjectAccess *pTemplate,
  /* [in] */IWbemRefresher *pRefresher,
  /* [in] */long lFlags,
  /* [in] */IWbemContext *pCtx,
  /* [out] */IWbemObjectAccess **ppRefreshable,
  /* [out] */ long *plId
);
{
  // We'll use a private interface we defined
  // to talk with the refresher.
  IMyRefresher* pMyRefr = NULL;

  HRESULT hres = pRefresher->QueryInterface(
    IID_IMyRefresher,
    (void**) &pMyRefr );

  if ( SUCCEEDED( hres ) )
  {
    // Check for a valid instance
    if ( ValidateInst( pTemplate ) )
    {
      IWbemClassObject* pTemplateObj = NULL;
      IWbemClassObject* pCloneObj = NULL;
      IWbemObjectAccess* pCloneAcc = NULL;

      // Clone the object, then get an
      // IWbemObjectAccess pointer
      pTemplate->QueryInterface(
        IID_IWbemClassObject,
        (void**) &pTemplateObj );

      pTemplateObj->Clone( &pCloneObj );

      pCloneObj->QueryInterface(
        IID_IWbemObjectAccess,
        (void**) &pCloneAcc );

      // Generates a unique id
      *plId = InterlockedIncrement( &m_lLastId );

      // Adds the object to an array of
      // objects to refresh
      pMyRefr->AddInstance( *plId, pCloneAcc );

      // Maintains AddRef from QI
      *ppRefreshable = pCloneAcc;

      pTemplateObj->Release();
      pCloneObj->Release();
    }
    else
    {
      hres = WBEM_E_NOT_FOUND;
    }

    pMyRefr->Release();
  }

  return hres;
}

HiPerf providers should return one of the following codes.

Return code | Description
WBEM_S_NO_ERROR | CreateRefreshableObject was successful.
WBEM_E_NOT_FOUND | The provider could not get a requested instance.
WBEM_E_PROVIDER_NOT_CAPABLE | The provider does not support refreshing instance objects. Unless a more specific error code is required, return this error code in all cases.
WBEM_E_FAILED | The provider failed internally, but the operation was valid.
WBEM_E_UNSUPPORTED_FLAGS | lFlags contained fields that were not recognized.


Implementing IWbemHiPerfProvider::CreateRefreshableEnum

[This is preliminary documentation and subject to change.]

The IWbemHiPerfProvider::CreateRefreshableEnum creates a refreshable enumerator. The WMI Refresher calls this method in response to a client request to IWbemConfigureRefresher::AddEnum. The provider should associate the supplied enumerator with the supplied refresher, returned by IWbemHiPerfProvider::CreateRefresher. One possible way to do this would be to keep an array of refreshable enumerators in the refresher.

The provider must not access the enumerator unless the owner's IWbemRefresher::Refresh method is called. As with refreshable objects, the provider must not update the enumerator, unless the object owning the enumerator refreshes the enumerator.

The following code sample shows how to implement CreateRefreshableEnum.

HRESULT CHiPerfProvider::CreateRefreshableEnum(
  /* [in] */IWbemServices *pNamespace,
  /* [in] */LPCWSTR wszClass,
  /* [in] */IWbemRefresher *pRefresher,
  /* [in] */long lFlags,
  /* [in] */IWbemContext *pCtx,
  /* [in] */IWbemHiPerfEnum *pEnum,
  /* [out] */ long *plId
);
{
  // We'll use a private interface we defined
  // to talk with the refresher.
  IMyRefresher* pMyRefr = NULL;

  HRESULT hres = pRefresher->QueryInterface(
    IID_IMyRefresher,
    (void**) &pMyRefr );

  if ( SUCCEEDED( hres ) )
  {
    // Generates a unique id
    *plId = InterlockedIncrement( &m_lLastId );

    // Use an internal method to add the
    // enumerator to an array
    pMyRefr->AddEnum( wszClass, *plId, pEnum );

    pMyRefr->Release();
  }

  return hres;
}

HiPerf providers should return one of the following codes:

Return code | Description
WBEM_S_NO_ERROR | CreateRefreshableEnum was successful.
WBEM_E_NOT_FOUND | The provider cannot enumerate the requested class.
WBEM_E_PROVIDER_NOT_CAPABLE | The provider does not support refreshing instance objects. Unless a more specific error code is required, return this error code in all cases if a more specific one is not required.
WBEM_E_FAILED | The provider failed internally, but the operation was valid.
WBEM_E_UNSUPPORTED_FLAGS | lFlags contained fields that were not recognized.


Implementing IWbemHiPerfProvider::StopRefreshing

[This is preliminary documentation and subject to change.]

The IWbemHiPerfProvider::StopRefreshing method asks a provider to stop refreshing an object or enumerator. The WMI Refresher calls this method in response to a client request to IWbemConfigureRefresher::Remove. The provider should check the objects and enumerators associated with the refresher for a matching ID. When one is found, the object or enumerator should be removed and released.

The following code sample shows how to implement StopRefreshing.

HRESULT CHiPerfProvider::StopRefreshing(
  /* [in] */LPCWSTR wszClass,
  /* [in] */long lId,
  /* [in] */long lFlags,
);
{
  // We'll use a private interface we defined
  // to talk with the refresher.
  IMyRefresher* pMyRefr = NULL;

  HRESULT hres = pRefresher->QueryInterface(
    IID_IMyRefresher,
    (void**) &pMyRefr );

  if ( SUCCEEDED( hres ) )
  {
    // This function will iterate the arrays of
    // instances and enumerators, checking for
    // the id.  If a match is found, the object
    // or enumerator will be removed.
    hres = pMyRefr->Remove( lId );

    pMyRefr->Release();
  }

  return hres;
}

HiPerf providers should return one of the following codes:

Return code | Description
WBEM_S_NO_ERROR | StopRefreshing was successful.
WBEM_E_NOT_FOUND | The provider could not find an object or enumerator corresponding to the supplied ID.
WBEM_E_PROVIDER_NOT_CAPABLE | The provider does not support refreshing instance objects. Return this error code in all cases if a more specific one is not required.
WBEM_E_FAILED | The provider failed internally, even though the operation was valid.
WBEM_E_UNSUPPORTED_FLAGS | lFlags contained fields that were not recognized.


Implementing IWbemRefresher::Refresh

[This is preliminary documentation and subject to change.]

The IWbemRefresher::Refresh method is called to refresh objects and/or enumerators that have been added to the refresher. The WMI Refresher calls this function in response to a client request to Refresh. The provider should only access the objects and enumerators in a refresher in response to a call to this method. It would, however, be perfectly valid to have a background thread polling for data with which to fill these objects, to prepare for when Refresh is called.

The following code sample shows how to implement Refresh.

HRESULT CHiPerfProviderRefresher::Refresh(
/* [in] */long lFlags,
);
{
  // Run through the objects and update their
  // data
  for ( int i = 0; i < m_nNumObjects; i++ )
  {
    FillInstance( m_apObjAccess[i] );
  }

  // Now run through the enumerators
  for ( i = 0; i < m_nNumEnumerators; i++ )
  {
    // Empty the enumerator and refill it
    m_apEnum[i]->RemoveAll();
    FillEnumerator( m_apEnum[i] );
  }

  return WBEM_S_NO_ERROR;
}

When refreshing enumerators and objects, providers should take as little time as possible. Using IWbemObjectAccess methods and caching property handles for reuse can dramatically improve performance. When updating enumerators, a provider can either remove and re-instantiate all objects, or simply remove and add the changed instances. It is up to the provider implementer to choose the best approach. In either case, caching instances can improve performance.

HiPerf providers should return one of the following codes.

Return code | Description
WBEM_S_NO_ERROR | Refresh was successful.
WBEM_S_PARTIAL_RESULTS | Not all objects or enumerators were successfully refreshed.
WBEM_E_FAILED | The provider failed internally, even though the operation was valid.
WBEM_E_UNSUPPORTED_FLAGS | lFlags contained fields that were not recognized.

Sample code for a simple HiPerf provider can be found in the WMI SDK in the \Sdksampl\BasicHiPerf folder.


Capturing and Reporting Performance Data Using a High-Performance Provider

[This is preliminary documentation and subject to change.]

You can create a High-Performance provider to capture and report performance data that is displayed by the Windows 2000 System Monitor (SysMon). This alternative to writing a performance library provides greater access to performance data in terms of speed and granularity of the data that is retrieved.

High-Performance (HiPerf) providers greatly increase the speed at which clients that access HiPerf classes can obtain information from WMI. This is because they are implemented as dynamic link libraries, that can be loaded in-process to the client or the server. For more details, see Implementing a High-Performance Provider.

Also, by implementing your own High Performance provider, WMI does not have to call the Performance Counters Provider, which in turn calls the performance library to collect the data. Removing this layer greatly improves your performance.

The other advantage of the HiPerf provider is that it gives you greater control over the amount of data that is returned to the client. With the HiPerf provider, you are returned only the instance level data that you require as compared to performance libraries that must return all instances when you call the Collect function.

The Windows 2000 System Monitor (SysMon) displays performance data that is derived from the Win32_PerfRawData class. In addition to writing a HiPerf provider to provide your class instance data, you must:

  1. Create your class in the Cimv2 namespace. The class must be derived from Win32_PerfRawData.
  2. Specify the following class level qualifiers: DisplayName, Locale, and PerfDetail.
  3. Include a key property called Name in your class (this property is not required for singleton classes). The Name property must be the only key property in the class.
  4. Specify the following property level qualifiers for all properties in your class: DisplayName, Locale, DefaultScale, PerfDetail, CounterType, and PerfDefault (only set for the default counter type).

The DisplayName and Locale qualifiers are used for localization. You must add amended qualifiers to the MS_409 (English) namespace, so SysMon knows how to display your class data. You must also add amended qualifiers to any other locale's namespace that your class supports. If a user requests data from a locale for which you do not provide amended qualifiers, WMI defaults to the definitions specified in the MS_409 namespace. For more information on localization issues, see WMI Localization.

The following table defines the DefaultScale, PerfDetail, PerfDefault, and CounterType qualifiers. You can find further descriptions of these qualifiers in Chapter 12, volume 4 of the 3.51 Resource Kit. In addition, the Winperf.h header file contains values that you can use specify for PerfDetail and CounterType.

Qualifier | Description
CounterType | Specifies this counter's type. For more information on counter types, see Chapter 12, volume 4 of the 3.51 Resource Kit.
DefaultScale | Specifies the default number by which SysMon multiplies the actual value of the counter to calculate the value displayed in the charts.
PerfDefault | Specifies the object's default counter.
PerfDetail | Specifies the level of detail associated with the counter, such as novice or advanced.

In order for SysMon to display your HiPerf class data, you must specify the following command line.

mmc perfmon.msc /wmi_sysmon


WMI Providers

Windows Management Instrumentation (WMI) defines two types of providers:

  • Application-specific providers, also known as custom providers
  • Built-in providers

Third-party vendors develop application-specific providers to communicate information from objects in their domain to WMI.

Built-in providers are providers that are included with WMI.These providers supply WMI with information from various logical and physical sources such as the operating system registry, the Microsoft® Win32® subsystem, and Simple Network Management Protocol (SNMP) devices. There are two varieties of built-in providers: those that provide data and those that provide events.

The built-in providers are briefly described in the following table.

Provider | Description
Directory Services Provider | Makes the classes and objects in the Active Directory available to WMI management applications.
Event Log Provider | Provides access to data and notifications of events from the Microsoft® Windows NT®/Microsoft® Windows® 2000 Event Log.
Microsoft Windows Installer Provider | Provides access to information about applications that are installed using Windows Installer.
Performance Counters Provider | Provides access to raw performance counter data.
Performance Monitor Provider | Provides access to data from the Windows NT/Windows 2000 Performance Monitor.
Power Management Event Provider | Represents power management events resulting from power state changes.
Registry Event Provider | Sends an event whenever a change occurs to a key, a value, or an entire tree in the registry.
Registry Provider | Provides access to data from the registry.
Security Provider | Provides access to security settings that control ownership, auditing, and access rights to the NTFS file system.
SNMP Provider | Provides access to data and events from SNMP devices.
View Provider | Creates new classes made of properties from different source classes, different namespaces, or from different computers.
WDM Provider | Provides access to data and events from device drivers that conform to the WMI interface.
Win32 Provider | Provides access to data from the Win32 subsystem.


Event Log Provider

The Microsoft® Windows NT®/Microsoft® Windows® 2000 Event Log Provider provides access to data from the Windows NT/Windows 2000 Event Log service and thus to notifications of Windows NT/Windows 2000 events. The Event Log service writes Windows NT/Windows 2000 events to one of several log files that reside on each user's computer in the order in which they are received. For more information on the Event Log service, see the Windows NT/Windows 2000 documentation.

The Event Log Provider consists of a Component Object Model (COM) server implemented as a DLL and one Managed Object Format (MOF) file, Ntevt.mof. WMI loads the DLL when a client makes a request of the provider. The MOF file contains definitions of Event Log Provider classes that are used to represent the Event Log data and of Windows NT/Windows 2000 events. Related association classes and classes used for registration are also included in this file. All Event Log Provider classes are available only in the Root\Cimv2 namespace.

The Event Log Provider acts as an instance provider, a method provider, and an event provider. As an instance and method provider, the Event Log Provider supports the Win32_EventlogFile class. Win32_EventlogFile is used to map data from the Windows NT/Windows 2000 event logs and to clear or back up a log. As an event provider, the Event Log Provider supports the Win32_NTLogEvent class to represent Windows NT/Windows 2000 events.

The Event Log Provider implements the standard IWbemProviderInit interface for initialization and the following methods of the IWbemServices interface:

  • CreateInstanceEnumAsync
  • ExecMethodAsync
  • ExecQueryAsync
  • GetObjectAsync
  • PutInstanceAsync

Because clients are serviced though WMI and never interact with the providers directly, any IWbemServices method can be called, whether synchronous or asynchronous. WMI either translates the call into an asynchronous request or service the request itself.

Note The Event Log Provider requires Windows NT version 4.0 or Windows 2000. This provider does not run on Windows 95 or Windows 98.


Registering the Event Log Provider

The Event Log Provider is registered automatically when WMI is installed, even if WMI is installed by default as part of the operating system; registration by a client is typically unnecessary. However, if an application does need to register the Event Log Provider, it does so by compiling the Ntevt.mof file using the MOF compiler. To compile the Ntevt.mof file at the command prompt, use the following syntax where WBEMinstalldir represents the location of the WMI SDK installation:

C:\> WBEMinstalldir\mofcomp WBEMinstalldir\ntevt.mof

The following definitions can be used to register the Event Log Provider as an instance and method provider:

instance of __Win32Provider as $NTEventDataProv
{
  Name = "MS_NT_EVENTLOG_PROVIDER";
  ClsId = "{FD4F53E0-65DC-11d1-AB64-00C04FD9159E}";
};

instance of __MethodProviderRegistration
{
  Provider = $NTEventDataProv;
};

instance of __InstanceProviderRegistration
{
  Provider = $NTEventDataProv;
  SupportsPut = TRUE;
  SupportsGet = TRUE;
  SupportsDelete = FALSE;
  SupportsEnumeration = TRUE;

  QuerySupportLevels = {"WQL:UnarySelect", "WQL:References"};
};

The following instances can be used to register the Event Log Provider as an event provider:

instance of __Win32Provider as $NTEventProv
{
  Name = "MS_NT_EVENTLOG_EVENT_PROVIDER";
  ClsId = "{F55C5B4C-517D-11d1-AB57-00C04FD9159E}";
};

instance of __EventProviderRegistration
{
  Provider = $NTEventProv;
  EventQueryList = {"select * from __InstanceCreationEvent
    where TargetInstance isa \"Win32_NTLogEvent\""};
};

The Event Log Provider employs the standard registration process for WMI providers. For a complete description of this process, see Registering a Provider.


Using the Event Log Provider as an Instance and Method Provider

The Win32_NTEventlogFile class includes two methods: BackupEventlog and ClearEventlog. These methods implement the Win32 functions of the same names and take one input parameter, the name of the backup file to be created. For BackupEventlog, this parameter must not be NULL or the name of a file that already exists. ClearEventlog accepts a NULL parameter if the calling application does not require the log file to be backed up before it is cleared. If the parameter is non-NULL, the file must not already exist. Both methods return zero if they are successful. If unsuccessful, they return an error code obtained from the Win32 GetLastError function.

Windows NT/Windows 2000 events are written to one of several log files that reside on each user's computer in the order in which they are received. Every computer has at least the following three log files:

  • Application
  • System
  • Security

Windows 2000 systems have an additional log file to store directory events.

Data is stored in these log files in a format defined by the Win32 EVENTLOGRECORD data structure. The Event Log Provider maps each member of this structure to a property in the Win32_NTEventlogFile class.

The following table describes the local computer's non-system Win32_NTEventlogFile class properties.

Property | Description
LogfileName | Name of the log file. The standard log file names are Application, System, and Security.
MaxFileSize | Maximum size for the log file. This is a read/write value retrieved from the Windows NT/Windows 2000 Event Log service's MaxSize value in the registry.
NumberOfRecords | Number of records in the log file. This value is determined by calling the Win32 function GetNumberOfEventLogRecords.
OverwriteOutDated | Number of days after which an event can be overwritten.
OverWritePolicy | Current overwrite policy the Windows NT/Windows 2000 Event Log service employs for this log file. Data can be overwritten either never, when necessary, or when outdated. When data is outdated depends on the OverwriteOutDated value. OverWritePolicy is read-only.

Clients of the Event Log Provider can change the value for the MaxFileSize property. If MaxFileSize is decreased, the change does not take effect until the log file is manually cleared.

The properties OverWritePolicy and OverwriteOutDated are based on the Windows NT/Windows 2000 Event Log service's Retention registry value. OverwriteOutDated is set to the same value as Retention. Possible values for this property are:

  • 0, indicating that any entry can be overwritten when necessary.
  • 1 through 365, indicating that events that have been in the log file for one year (365 days) or less can be overwritten.
  • 4294967295, indicating that nothing can be overwritten.

However, values between 365 and 4294967295 cannot be used with the Event Log Provider. When the IWbemServices::PutInstance or IWbemServices::PutInstanceAsync method is called to store an instance of Win32_NTEventlogFile, the registry is updated. PutInstance or PutInstanceAsync fails if there is an attempt to set OverwriteOutDated to a value between 365 and 4294967295.

To change the overwrite policy used for the log file, change the OverwriteOutDated property.

The OverWritePolicy value is based on the value of the OverwriteOutDated property. It is set as follows:

OverwriteOutDated value | OverWritePolicy value
0 | WhenNeeded
1 through 365 | OutDated
4294967295 | Never

For more information about overwrite policy values, see Log File Registry Entries.

Win32_NTEventlogFile inherits properties from two of its the superclasses in the hierarchy: CIM_ManagedSystemElement and CIM_LogicalFile. For information about these properties, see Properties Inherited from CIM_ManagedSystemElement and Properties Inherited from CIM_LogicalFile.


Properties Inherited from CIM_ManagedSystemElement

The Win32_NTEventlogFile class inherits several properties from its abstract base class: CIM_ManagedSystemElement. The following table lists these properties and describes the inherited values.

Property | Description
Caption | Last 64 characters of the Name property. If Name has less than 64 characters, Caption has the same value as Name.
Description | Same value as the Name property.
InstallDate | Same value as the CreationDate property. For more information on CreationDate, see Properties Inherited from CIM_LogicalFile.
Name | Full path of the log file retrieved from the Windows NT/Windows 2000 Event Log service's File registry value.
Status | Value indicating whether the log file can be opened. Valid values are: OK if the file can be opened, Unknown if the file cannot be opened due to a sharing violation, and Error if the file cannot be opened for any other reason.

The Extension and Path properties are determined by parsing the value of the Name property from the end of the string to the beginning. For the Extension property, which indicates the log file extension, the parsing process looks for a period ("."). If a backward slash ("\") is encountered first or a period is not found, Extension is NULL. If a period is found, Extension contains a string consisting of the characters parsed, including the period. For example, if Name is "C:\File.evt", Extension is set to ".evt".

For the Path property, which indicates the path to the log file, the parsing process looks for a backslash. If a backslash is not found, Path is NULL. If a backslash is found, Path contains the backslash appended to a string consisting of the characters that have yet to be parsed. For example, if Name is "C:\file.evt", Path is "C:\".

Note If there are multiple backslashes in the path, the path is taken up to the last backslash.


Properties Inherited from CIM_LogicalFile

The Win32_NTEventlogFile class inherits several properties from its parent class, CIM_LogicalFile. The following table lists some of these properties and describes the inherited values.

Property | Description
CreationClassName | Always Win32_NTEventlogFile.
CSCreationClassName | Always Win32_ComputerSystem.
CSName | Local computer name. This value is determined by calling the Win32 function GetComputerName. If the call fails, CSName is NULL.
Encrypted | Value indicating the log file is encrypted. This value is always FALSE.
FileType | File type. This value is determined by looking up the extension without the preceding period (".") in the list of known file types in the registry. If the extension is not found, FileType contains the characters "File" appended to the extension. If there is no extension, FileType is NULL.
FSCreationClassName | Always Win32_FileSystem.
FSName | Current volume name. This value is determined by calling the Win32 function GetVolumeInformation. If the call fails, FSName is NULL.
LastArchivedDate | Last date the log file was backed up. This value is always NULL.
Open | Determined by calling the Win32 function CreateFile with exclusive access. If the call succeeds, Open is FALSE. If the call fails with a sharing violation, Open is TRUE. If the call fails for another reason, Open is NULL.
Readable | Value indicating the log file is human-readable. This value is always TRUE.

To determine the current value for the following properties inherited from CIM_LogicalFile, call the C run-time function _wfindfirsti64. If the call succeeds, query the _wfinddatei64_t structure that is returned. If the call fails, the property is set to NULL.

Property | Description
Archive | File or directory's archive flag (a bit) set by applications to mark files or directories for backup or removal. This bit is automatically set whenever the Win32 CreateFile function creates a new file.
Compressed | Value indicating the log file is compressed.
CreationDate | Date the log file was created.
LastAccessDate | Date the log file was last accessed.
LastModifiedDate | Date the log file was last modified.
Size | Size of the log file.
Writeable | Value indicating the log file is read/write.


Log File Registry Entries

The Windows NT/Windows 2000 Event Log service currently maintains three log files: Application, Security, and System. Each of these log files has a section in the Windows NT/Windows 2000 registry under the following hierarchy of keys:

HKEY_LOCAL_MACHINE
  SYSTEM
    CurrentControlSet
      Services
        Eventlog

Within each section, there are four values: File, MaxSize, Retention, and Sources. The following table describes these values.

Value | Type | Description
File | REG_SZ_EXPAND | Path to the log file. This value can include environment variables.
MaxSize | REG_DWORD | The log file's maximum size in bytes. This value must be between 64K and 419,240K and can only be incremented in 64K chunks.
Retention | REG_DWORD | Overwrite policy of the log file.
Sources | REG_MULTI_SZ | List of sources from which logged events can come.

The Retention value can be set to:

  • 0, indicating that any entry can be overwritten when necessary.
  • 1 through 365, indicating that events that have been in the log file for one year or less can be overwritten.
  • 4294967295, indicating that nothing can be overwritten.

If the log file becomes full and no events are old enough to be overwritten, the log file must be cleared manually. Otherwise, the file discards new events until an event becomes old enough to be overwritten. The log file must be cleared before any change to its size can take effect.

The Event Log Provider properties OverWritePolicy and OverwriteOutDated are based on Retention. For more information on OverWritePolicy and OverwriteOutDated, see Using the Event Log Provider as an Instance and Method Provider.


Using the Event Log Provider as an Event Provider

As an event provider, the Event Log Provider registers with the Windows NT/Windows 2000 Event Log service to receive notifications of new Windows NT/Windows 2000 events. For information on how to do so, see Registering the Event Log Provider. Each Windows NT/Windows 2000 event is represented as an instance of the Win32_NTLogEvent class. For more information, see Using the Event Log Provider as an Instance and Method Provider.

When the Event Log Provider receives notification of a new Windows NT/Windows 2000 event, it generates an instance creation event. Instance creation events are intrinsic events represented by the __InstanceCreationEvent system class. The Event Log Provider sets the TargetInstance property of the new event to an instance of the Win32_NTLogEvent class.

The Win32_NTLogEvent class is defined as follows:

class Win32_NTLogEvent
{
    uint32            RecordNumber;
    string            Logfile;
    uint32            EventIdentifier;
    uint16            EventCode;
    string            SourceName;
    string            Type;
    uint16            Category;
    string            CategoryString;
    datetime          TimeGenerated;
    datetime          TimeWritten;
    string            ComputerName;
    string            User;
    string            Message;
    string            InsertionStrings[];
    Uint8             Data[];
};

The following table describes Win32_NTLogEvent class properties.

Property | Description
Category | Category specific to the event source.
CategoryString | Specifies the translation of the sub-category. The translation is source specific.
ComputerName | Variable-length, null-terminated string specifying the name of the computer that generated this event.
Data | Binary data that accompanies the report of the event.
EventCode | This property has the value of the lower 16-bits of the EventIdentifier property. It is present to match the value displayed in the NT Event Viewer. NOTE: Two events from the same source may have the same value for this property but may have different severity and EventIdentifier values.
EventIdentifier | Property that is used with the SourceName property to uniquely identify a Windows NT/Windows 2000 event type.
InsertionStrings One or more strings that accompany the report of the event.

These strings are sent with a particular instance of an event. An event can have a generic message that has a placeholder (or several placeholders) for insertion strings based on a particular event.

For example, the generic message "Port %1 is down," and the insertion string "23" will result in a the message "Port 23 is down."
Logfile | Property that is used with the RecordNumber property to uniquely identify an event within the Windows NT/Windows 2000 event log and a Win32_NTLogEvent instance.
Message Event message as it appears in the event log. This message consists of a standard message, plus zero or more insertion strings supplied by the event source. If this property is blank, a user interface application presenting information from this class should inform the user by displaying an appropriate message.

Note that messages are not recorded in events. A particular event ID represents a particular message.

Messages are read from resource DLLs supplied by the source. If an event ID does not translate into a message in a source's resource DLL, then the message will be blank.

Only insertion strings are supplied with an event.
RecordNumber | Property that is used with the Logfile property to uniquely identify an event in the Windows NT/Windows 2000 event log and a Win32_NTLogEvent instance.
SourceName | Variable-length null-terminated string specifying the component responsible for generating the Windows NT/Windows 2000 event. SourceName is used with the EventIdentifier property to uniquely identify a Windows NT/Windows 2000 event type.
TimeGenerated | Time at which the source generated the event.
TimeWritten | Time at which the event was written to the event log.
Type | Event type. Valid values are error, warning, information, audit success, and audit failure.
User | Name of the user that was logged on when the event occurred, or NULL if the user cannot be determined.


Event Log Association Classes

There are three association classes that a client of the Event Log Provider typically uses. All three classes link an instance of the Win32_NTLogEvent class with an instance of another class.

The Win32_NTLogEventLog association class links instances of Win32_NTLogEvent and Win32_NTEventlogFile classes. It is defined as follows:

class Win32_NTLogEventLog
{
    [key, read]  Win32_NTEventlogFile ref Log;
    [key, read]  Win32_NTLogEvent     ref Record;
}

The Win32_NTLogEventUser association class links instances of Win32_NTLogEvent and Win32_UserAccount, a class defined in the Win32 schema. Win32_NTLogEventUser is defined as follows:

class Win32_NTLogEventUser
{
    [key, read]  Win32_NTUserAccount  ref User;
    [key, read]  Win32_NTLogEvent     ref Record;
}

The Win32_NTLogEventComputer association class links instances of Win32_NTLogEvent and Win32_ComputerSystem, another class defined in the Win32 schema. Win32_NTLogEventComputer is defined as follows:

class Win32_NTLogEventComputer
{
    [key, read]  Win32_ComputerSystem  ref Computer;
    [key, read]  Win32_NTLogEvent      ref Record;
}


Troubleshooting the Event Log Provider

The following table presents some common problems that can occur in using the Event Log Provider and offers possible causes and solutions.

Problem | Possible cause and/or solution
Classes supported by the Event Log Provider do not appear in a namespace. | Only the Root\Cimv2 namespace is supported. Check that you are connected to the Root\Cimv2 namespace, and make the connection if you are not.
Classes supported by the Event Log Provider do not appear in the Root\Cimv2 namespace. | Use the MOF compiler to compile the MOF file that contains the missing classes. The target file is Ntevt.mof. This file can be found in the WMI installation directory.
No instances are returned after enumerating instances of any class. | Windows NT/Windows 2000 event logs are empty.
No instances are returned after enumerating instances of the Win32_NTLogEventUser class. | Not all Windows NT/Windows 2000 event log records contain user information. Typically only security event log records contain user information.
Enumerating instances takes a long time. | This behavior is reasonable if any of your event log files are large, because the instance provider enumerates all event logs and passes the results using COM.

When there is a total of 2,000 or more events in the event logs, you might observe a decline in the performance of the Event Log Provider. Under those conditions, viewing events with the standard Windows NT/Windows 2000 user interface can be faster.


Microsoft Windows Installer Provider

[This is preliminary documentation and subject to change.]

The Microsoft® Windows® Installer provider is one of the built-in providers. It allows WMI-enabled applications to access information collected when Windows Installer–compliant applications are installed.

The Installer provider mirrors the functionality of the Windows Installer. In Windows Installer technology, a software product is organized into parts, which in turn have subparts. The bits and pieces that make up a product are arranged in a hierarchy, with the largest pieces at the top, and the smallest at the bottom.

Each of these pieces contains properties of the installed software product. There can be dozens or even hundreds of them. Arranging the pieces in a hierarchy clarifies the nature of the software product installation.

The Installer provider can read any property of a software product installation. In addition, the Installer provider makes available to remote users the set of procedures that the Windows Installer makes available to users of stand-alone computers. Through WMI, you can perform a host of powerful tasks for application installation.

Note The Windows Installer provider requires Microsoft® Windows NT® version 4.0, Windows 2000, Windows 98, or Windows 95.


About the Installer Provider

[This is preliminary documentation and subject to change.]

The Windows Installer provider uses the WMI interface to provide the functionality of the Windows Installer. For more information about the Installer, see the Windows Installer Programmer's Reference section of the Platform SDK.

You can use the Installer provider to perform two types of tasks:

  • Finding attributes or properties of the applications you installed previously with the Windows Installer, and then supplying WMI with the details of these attributes or properties.
  • Performing the entire range of software installation functions, such as installing, maintaining, querying, upgrading, and uninstalling software packages.

Note The Installer provider is based on Windows Installer technology. This means that you can only use the Installer provider with software that meets the Windows Installer technology specification. The latest software packages use this new installation technology. For example, you can use this technology with Microsoft® Office 2000. To install a software package compatible with Windows Installer, double-click the appropriate *.msi file (not Setup.exe). Each software package installed by Windows Installer stores information in the Windows Installer database, which is where the Installer provider looks for information.


Software Product Organization

[This is preliminary documentation and subject to change.]

You can think of an installed software application as an instantiated object of the product class. Using the Windows Installer provider, you can "mine" the Windows Installer database, extracting meaningful information from the data it contains on any of its registered applications. You can use the Installer provider to get a snapshot of the current state of any aspect of one of these objects.

A product object has properties. It is made up of features, which have properties. Features are made up of elements, which also have properties.

According to Windows Installer technology, the bits and pieces that make up a product are arranged in a hierarchy, with the largest pieces at the top, and the smallest at the bottom. This structure helps make sense of the many different aspects a product object can have and how they all relate to one another. Such a hierarchy looks like the following.

As seen another way, a product encompasses a set of features that are built of elements. To view the entire set of properties that define a software product installation, you need to look at:

  • Properties of the product.
  • Properties of the features that make up that product.
  • Properties of the elements (components) that make up those features.

Instances of application installations are always handled in terms of the preceding three-tiered hierarchical model. The following illustration uses Office 2000 as an example.

The Office 2000 product breaks down into a logical set of components:

  • Features of this product are Microsoft® Word for Windows and Microsoft® Excel.
  • Subfeatures of Word for Windows are the Spell Checker and the Thesaurus.
  • Software elements are the Spell Checker Engine and Dictionaries.

Note In this example, two levels exist between product and elements, instead of the one level of features. It is simpler to say that Word for Windows is itself a product. However, Word for Windows is now thought of as a feature of Office 2000. Thus, the three-tiered model still holds if we consider Word for Windows as a feature, and Spell Checker as a subfeature.


Using Properties of an Application Installation

[This is preliminary documentation and subject to change.]

Using the Windows Installer provider, you can "mine" the Windows Installer database, extracting meaningful information from the data it contains on any of its registered applications. You can learn:

  • Which products have been installed on a WMI client computer.
  • Which features and elements have been installed.
  • The installation state of each product and subcomponent (local, run from-source, advertised, and so on). For more information about the Windows Installer, see the SDK (software development kit) documentation on the MSDN Web site at msdn.microsoft.com.
  • The relationship that exists between products and their subcomponents.
  • Which elements are shared between products, and how the presence or absence of elements affect neighboring products.


Application-Installation Procedures

[This is preliminary documentation and subject to change.]

Through WMI, you can perform local and remote software application installation and maintenance procedures such as:

  • Any type of product installation action, for example INSTALL, ADMIN, or ADVERTISE.
  • Product reinstallation.
  • Software feature reinstallation.
  • Product upgrade.
  • Installation modification.
  • Product removal/uninstallation.

Note Until the release of Windows 2000, existing applications were installed without using the Windows Installer technology. Such existing installations should not cause problems. However, no details about these installations exist in the Installer database.


Using the Installer Provider

[This is preliminary documentation and subject to change.]

Depending on what you want to do, you can access the Installer provider functionality from five different environments. For details on each, see the following sections:

  • For developers of management applications, see Using the COM API for WMI.
  • For system administrators and support personnel who want to create high-level scripts or browse existing installations, see Using the Scripting API.
  • For database developers who want to design system administration applications, see Using ODBC and WMI.
  • For system administrators who need to know about application installations, see WMI Object Browser.
  • For Web-page developers who want to design front-end system administration interfaces, see ActiveX Controls.


Registering the Installation Provider

[This is preliminary documentation and subject to change.]

Registrations are the instance definitions required for the provider to give information to the Common Information Model (CIM) Object Manager. Generally, registrations include instances of these system classes:

  • __Win32Provider
  • __InstanceProviderRegistration
  • __MethodProviderRegistration

These instance definitions tell the CIM Object Manager how to use the provider. Note that they do not provide Installer information themselves.

Note The Installer provider employs the standard registration process for providers. For a complete description of this process, see Registering a Provider.

The Installer provider is registered automatically as part of the installation process. There should be no need for you to register this provider for your applications. However, if an application requires the Installer provider to be registered and it is not, compile the Msi.mof file yourself using the MOF compiler, as described in Compiling the Msi.mof File and the topics following.


Compiling the Msi.mof File

[This is preliminary documentation and subject to change.]

You can manually register the Installer provider by compiling Msi.mof. Do this by typing the following at the command prompt:

C:\> WBEMinstalldir\mofcomp WBEMinstalldir\Msi.mof

where WBEMinstall dir represents the location of the core WMI installation.


Instance Enumeration

[This is preliminary documentation and subject to change.]

Registration of the __Win32Provider class, shown following, is a mandatory part of manually registering the Installer provider.

instance of __Win32Provider as $Z
{
Name = "MSIProv";
ClsId = "{BE0A9830-2B8B-11d1-A949-0060181EBBAD}";
ImpersonationLevel = 1;
PerUserInitialization = "TRUE";
};

After doing this, you perform instance retrieval and writing.


Instance Retrieval and Writing

[This is preliminary documentation and subject to change.]

As part of manually registering the Installer provider, you must identify the Installer provider as an instance provider. The following instance of the system class __InstanceProviderRegistration does so. This instance declares the instance provider operations supported by the Installer provider. All operations are supported, with the exception that the SupportsPut and SupportsDelete properties can be applied to selected classes only.

instance of __InstanceProviderRegistration
{
Provider = $Z;
SupportsGet = "TRUE";
SupportsEnumeration = "TRUE";
SupportsPut = "TRUE";
SupportsDelete = "TRUE";
};
  • The properties initialized preceding provide this functionality:
  • By using the SupportsGet property, you can get individual objects by name. Both SupportsGet and SupportsEnumeration are implemented for all objects.
  • By using the SupportsEnumeration property, you can enumerate all the instances of an object.
  • By using the SupportsPut property, you can permanently change the properties of the object (and what it represents). This property is currently supported for the Win32_Property class only, for the setting of productwide properties.
  • By using the SupportsDelete property, you can delete instances of a Product class, resulting in the uninstallation of the associated product.

After retrieving and writing the instance, you next identify the Installer provider as a method provider, detailed under Method Execution.


Method Execution

[This is preliminary documentation and subject to change.]

As part of manually registering the Installer provider, you must identify the Installer provider as a method provider. The following instance of the system class __MethodProviderRegistration does so. This declaration makes the Installer provider capable of handling method calls for the objects it provides instances for.

instance of __MethodProviderRegistration
{
Provider = $Z;
};


Installing Software from a Remote Location

[This is preliminary documentation and subject to change.]

You can use the Installer provider to install software packages remotely. You can install software on any computer in your enterprise. The following script examples demonstrate how you can use the Installer provider to install a software product from a remote location. In the following, the InstallSink object receives status messages from WMI regarding the installation. This example requires administrative privileges and must be run on a computer with Microsoft® Windows® 2000.

The first three subroutines following handle the various objects and messages that are returned by WMI to the calling script or application during an installation. Upon completion of installation, WMI signals the end of the operation by calling the following routine:

Sub INSTALLSINK_OnCompleted(hResult, pErrorObject, pAsyncContext)
    alert("Installation Complete")
End Sub

WMI receives progress messages from the Windows Installer, forwarding them to the script through calls to the following routine. In this routine, IUpperBound is the total units of work for the complete operation, and iCurrent is the amount of work completed so far.

Sub INSTALLSINK_OnProgress(iUpperBound, iCurrent, strMessage, objWbemAsyncContext)
    if iUpperBound > 0 then
        iComplete = (iCurrent * 100)/iUpperBound
        ProgBar.Value = iComplete
        alert(CStr(objObject.ReturnValue + "% Complete")
    end if
End Sub

Upon completion of the installation, WMI calls the following routine with the ReturnValue in objObject. Zero signifies success; all other return values are documented in the Windows Installer Programmer's Reference section of the Platform SDK.

Sub INSTALLSINK_OnObjectReady(objObject, objAsyncContext)
    if Not objObject.ReturnValue = 0 Then
        alert("Installation failed with following error: " + _
            CStr(objObject.ReturnValue))
    Else
        alert("Installation Succeeded")
    End If
End Sub

The body of the script is as follows:

Set InstallSink = WScript.CreateObject("WbemScripting.SWbemSink", _
    "INSTALLSINK_")

Gather user information.

package_location = InputBox("Enter the location of the package to be installed.")
remote_machine_name = InputBox("Enter the name of the machine on which the product " + _
    Chr(13) + "is to be installed.")
admin_user = InputBox("Enter the user name. " + Chr(13) + _
    "(User must have Administrative privileges.)")
admin_user_password = InputBox("Enter the users password. ")

Set Service = Locator.ConnectServer(remote_machine_name, "root\cimv2", _
    admin_user, admin_user_password)
Service.Security_.ImpersonationLevel=3
Set Product = Service.Get("Win32_Product")

Get method information.

Set Path = Product.Path_
Set Method = Product.Methods_.Item("Install")
Set InParams = Method.InParameters
Set MyIns = InParams.SpawnInstance_

Set input parameters.

MyIns.PackageLocation = package_location
MyIns.AllUsers = "TRUE"
MyIns.Options = ""

Call the installation method.

Service.ExecMethodAsync InstallSink, Path, "Install", MyIns, wbemFlagSendStatus

Note The wbemFlagSendStatus flag, used in calling the installation method preceding, has the value of 128. In some situations, it may be necessary to use the numeric value instead of the flag name. The method you use depends on the environment you are using. For example, if you are programming a Web-based application using Internet Information Services (IIS), use the numeric value. If you are writing command scripts, use the numeric value. If you are using Microsoft® Visual Basic® version 6.0, use the flag name.


Enumerating Installed Software

[This is preliminary documentation and subject to change.]

You can use the Windows Installer provider to build a list of software packages (product objects) currently installed on a standalone computer. This list shows each product's installed state.

The following script excerpt demonstrates how this is done.

for each Product in GetObject("winmgmts:{impersonationLevel=impersonate}").InstancesOf ("win32_product")
    WScript.Echo Product.name, " - ", Product.InstallState
next


Installer Provider Reference

[This is preliminary documentation and subject to change.]

The following sections describe the Installer provider classes, and how their class objects are used.

The base classes of the Installer provider are taken from the CIM model. The Windows Installer provider classes (that is, those with the prefix Win32_) are derived from classes of the CIM model (that is, those with the prefix CIM_).

The core classes are the classes at the heart of the Windows Installer provider schema. They make up the basic application-installation instance hierarchy. Use them to access the bulk of the information on any product installed by Windows Installer. You can extend the Windows Installer provider schema by deriving classes from these core classes.

Associations are used to relate the core classes to one another, whereas external associations are used to relate the core classes to objects outside the Windows Installer schema.

To access product information of a more detailed nature, Associations can be used to access the information in the Checks, Actions, and Settings classes.


Base Classes of the Installer Provider

[This is preliminary documentation and subject to change.]

The Windows Installer provider classes (that is, classes with names prefixed Win32_) are derived from classes of the CIM model (that is, classes with names prefixed CIM_). This derivation ensures that classes populated by the Installer provider adhere closely to the CIM version 2 specification. The Installer provider will populate the \Root\Cimv2 namespace.

The following is a listing of the CIM classes that make up the foundation of the Installer provider class hierarchy.

Class | Description
Action | Instances of this class represent operations that are part of a process to either create a software element in its next state, or to eliminate the software element in the current state.
Check | Instances of this class represent conditions or characteristics that should hold true when a software feature or element is installed.
Component | Instances of this generic association class establish "part-of" relationships between managed system elements. For example, the SystemComponent association class defines parts of a system.
CopyFileAction | Instances of this class represent existing files to be moved or copied to a new location.
CreateDirectoryAction | Instances of this class provide a reference to the directory to be created, as well as to other information (such as which software element will cause the creation by being installed/uninstalled).
Dependency | Instances of this generic association class establish dependency relationships between objects.
DirectoryAction | Instances of this classes are used to manage directories.
DirectorySpecification | Instances of this class capture the major directory structure of a software element. These instances are used to organize the files of a software unit into manageable units that can be relocated on a computer system.
ElementSetting | Instances of this class represent the settings used within a particular arrangement with regards to a specific managed system element.
InstalledSoftwareElement | Instances of this association class represent the computer system a software element is installed on.
FileAction | Instances of this class allow the user to locate files that already exist on the user's machine, and move or copy those files to a new location.
FileSpecification | Instances of this class identify a file that is either to be on or off the system.
Product | Instances of this concrete class represent a collection (acquired as a unit) of managed system elements and/or other products. Acquisition implies an agreement between supplier and consumer which may have implications to product licensing, support, and warranty.
ProductSoftwareFeatures | Instances of this association class represent the software features for a particular product.
RemoveDirectoryAction | Instances of this class provide a reference to the directory to be removed, as well as to other information (such as which software element will cause the removal by being installed/uninstalled).
RemoveFileAction | Instances of this class provide a reference to a file to be removed, as well as to other information (such as which software element will cause the removal by being installed/uninstalled).
ServiceAccessPoint | Instances of this class represent an entry point (command line, API) at which a service is made available to other entities for use.
SoftwareFeature | Instances of this class represent the set of capabilities a software product has. Captures the level of granularity meaningful to a user of a product, rather than the individual files that reflect how the feature is implemented (The CIM_SoftwareElement class provides this level of detail). Software features are always defined in the context of a CIM_Product class using the CIM_ProductSoftwareFeature association (because features are delivered through products).


Derived Classes That Make Up the Installer Provider

[This is preliminary documentation and subject to change.]

The Installer provider classes are derived from CIM base classes and are prefixed with Win32_. The Installer provider classes fall into the following categories.

Class category | Description
Actions | Classes derived from CIM_Action represent actions performed during an installation, upgrade, uninstall, or application maintenance.
Associations | Instances of this association class represent references to other Installer provider classes.
Checks | Classes derived from CIM_Check represent conditions that should hold true when a software feature or element is installed.
Core Classes | These are the most important classes. You will use classes from this category to access 90 percent of software installation information.
External Associations | Instances of this association class represent references to Microsoft® Win32® classes beyond the scope of the Installer provider classes.
Settings | Instances of settings capture a set of properties that are meaningful within the context of a particular environment (set-up).


Core Classes

[This is preliminary documentation and subject to change.]

The Core classes are the classes at the heart of the Windows Installer provider schema. They make up the basic application-installation instance hierarchy. You will use the following classes to access the bulk of the information on software application-installations.

Here is a listing of Core classes.

Class | Description
Product | A class representing an entire software application installation. Office 2000 is an example of a product.
SoftwareElement Instances of this class represent the logical subcomponents that make up a software feature.

For example, Spell Checker is made up of the software elements Spell Checker engine, and dictionaries. Software elements are of interest to software developers engineering software features.

Each software element is defined as a Win32_SoftwareElement instance. The association between a feature and its elements is defined in the Win32_SoftwareFeatureSoftwareElement association.

Any element can be shared between two or more software features.
SoftwareFeature Instances of this class represent distinct subsets of a product. For example, a product such as Word for Windows has two features called Spell Checker and Thesaurus.

Features consist of one or more software elements.

Software features are of interest to users of software products.


Checks

[This is preliminary documentation and subject to change.]

Checks are derived from the Distributed Management Task Force (DMTF) CIM_Check class. A check is a condition or characteristic that is expected to be true within the scope of a CIM_ComputerSystem instance. The CIM_Check class represents details to be checked when a software feature or element is installed. This information might specify that other software features should be installed, or that specific hardware requirements must be met. An example is a check to see if enough disk space is available.

Note These classes are always associated with software features and/or their associated elements.

Here is a listing of Check classes.

Class | Description
Condition | Instances of this class represent checks that must evaluate to TRUE in order to install a software feature at the corresponding level. Level may be set based upon any conditional statement, such as a test for a platform, an operating system, a particular property setting, and so on. For more information, see the Windows Installer documentation.
DirectorySpecification Instances of this class capture the major directory structure of a software element.

Instances of the SoftwareElement class (files) are organized into manageable units that can be relocated on a computer system.
EnvironmentSpecification | Instances of this class contain information about any environment variables that may need to be registered for their associated products installation.
FileSpecification | Instances of this class represent a file that should be either on or of the computer system.
IniFileSpecification | Instances of this class contain the application's .INI information. This data is written to an .INI file when the corresponding component has been selected to be installed (run locally or from source).
LaunchCondition | Instances of this class contain a list of conditions, all of which must be satisfied for the Installer to successfully launch.
ODBCDataSourceSpecification | Instances of this class represent any Data Sources (DSNs) that are to be registered as part of an installation.
ODBCDriverSpecification | Instances of this class represent any ODBC drivers that are to be installed as part of a particular product
ODBCTranslatorSpecification | Instances of this class represent any ODBC Translators that are included as part of a products installation
ProgIDSpecification | Instances of this class represent any ProgIDs that need to be registered during a given installation.
ReserveCost Instances of this optional class represent the amount of reserved disk space in any directory. This amount is dependant on the installation state of a component.

Reserving cost in this way could be useful if you want to be sure a minimum amount of disk space will be available after the installation is completed.

For example, this disk space might be reserved for user documents, or for application files (such as index files) that are created only after the application is launched (following installation).
ServiceSpecification | Instances of this class represent the services that are to be installed along with a product.
SoftwareElementCondition | Instances of this class represent conditional checks that must be evaluated to TRUE before their associated Win32_SoftwareElement objects can be installed.


Actions

[This is preliminary documentation and subject to change.]

Actions are derived from the DMTF CIM_Action class. An action is an operation that is part of a process to either create a software element in its next state, or to eliminate the software element in the current state. Functions derived from CIM_Action are those performed during an installation, upgrade, uninstall, or application maintenance.

The CIM_Action class can also supply details about actions that the Windows Installer will take if a product or feature is installed, upgraded, or uninstalled.

For example, if a shared element such as a Spell Checker were uninstalled, MSI might have to update other applications, such as word processors and email programs, to make sure that they no longer offer the Spell Checker feature.

Note These classes are always associated with software features and and/or their associated elements.

Here is a listing of Action classes.

Class | Description
BindImageAction | Instances of this class represent the binding of executables to their imported DLLs. The virtual address of each function that is imported from all DLLs is computed and saved in the importing image's Import Address Table (IAT).
ClassInfoAction | Instances of this class represent COM class information that are to be registered with the system.
CreateFolderAction | Instances of this class represent folders for software elements are to be installed locally.
DuplicateFileAction | Instances of this class represent duplicate copies of installed files. Files can be installed to a different directory, or to the same directory, provided you give the file a different name.
ExtensionInfoAction | Instances of this class represent extension related information to be registered with the system.
FontInfoAction Instances of this class represent installed fonts to be registered with the system.

The Font.FontTitle is mapped to the path of the font file installed.
MIMEInfoAction | Instances of this class represent the MIME-related registry information that is to be registered with the system.
MoveFileAction | Instances of this class represent files that already exist on the your computer, and are to be moved as part of an installation.
PublishComponentAction Instances of this class represent the advertisement of software elements that can be faulted-in by other products already installed on the computer system.

To fault-in a software element means a software element may already be installed in such a fashion that other products that require the same software element can use the installed version rather than installing a second copy. A spell checker is a good example.

In the Advertise mode, all software elements for which the corresponding feature is enabled are published.

Otherwise, software elements for which the corresponding feature is currently selected to be installed are published.
RegistryAction Instances of this class represent registry information that the application needs entered into the system registry.

The registry information is gated by objects of the SoftwareElement class. A registry value is written to the system registry if the corresponding component has been set to be installed either locally, or run from source.

By gated, we mean a registry action occurs depending on whether the software elements that are associated with it are installed.
RemoveFileAction Instances of this class represent previously installed files that must now be removed.

Each of these files is gated by a link to an entry in an object of the SoftwareElement class.
RemoveIniAction Instances of this class represent .INI file information that the application needs deleted from .INI files.

The deletion of the information is gated by an object of the SoftwareElement class.

An .INI value is deleted if the corresponding component has been set to be installed either locally, or run from source.
SelfRegModuleAction | Instances of this class represent modules that are to be (or have been) registered with the system (if installed).
ShortcutAction Instances of this class manage the creation of shortcuts.

In the Advertise mode, shortcuts to the key files of components of features that are enabled are created.

Advertised shortcuts have the Target property as a feature of the component, and a shell folder (or shell subfolder) for the directory of the shortcut .
TypeLibraryAction Instances of this class represent type-libraries that are to be registered with the system.

The action works on each associated file that is to be installed.


Settings

[This is preliminary documentation and subject to change.]

Settings contain additional information about installations or their components. Here is a listing of the Settings classes.

Class | Description
Binary | Instances of this class represent binary information such as bitmaps, icons, and executables that are used by an installation.
MSIResource | Instances of this class represent patches, upgrades, and binary data.
ODBCAttribute | Instances of this class describe an ODBC driver attribute that must to be set for an installation.
ODBCSourceAttribute | Instances of this class describe an ODBC datasource attribute that must to be set for an installation.
Patch | Instances of this class represent individual patches that apply to a particular file. The source of the patch resides at a specified location.
PatchPackage | Instances of this class describe the patch packages that apply to this product. For each patch package, the unique identifier for the patch is provided along with information about the media image on which the patch is located.
Property | Instances of this class represent the property names and values for all defined properties in the installation. Properties with NULL values are not represented.
ServiceControl | Instances of this class represent instructions for controlling both installed and uninstalled services.


Associations

[This is preliminary documentation and subject to change.]

Association classes exist so that relationships between software application-installation objects (products and software features, software elements, checks, and actions) can be represented. These associations are internal to the schema; they do not associate classes outside of the Windows Installer provider schema.

Here are two examples of association classes.

  • Win32_ProductSoftwareFeature links the Win32_Product and Win32_SoftwareFeature classes.
  • Win32_SoftwareFeatureSoftwareElement links the Win32_SoftwareFeature and Win32_SoftwareElement classes.

Here is a listing of Association classes.

Class | Description
ActionCheck | Instances of this association class relate an MSI action with its associated locational information in the form of a file and/or directory specification.
CheckCheck | Instances of this association class relate an application check with any locational information it requires. This location is in the form of a file and/or directory specification.
ODBCDriverSoftwareElement | Instances of this association class relate an ODBC driver with the software elements with which it is installed.
ProductCheck | Instances of this association class relate a product instance with its required checks.
ProductResource | Instances of this association class relate a product instance with its required resources.
ProductSoftwareFeatures | Instances of this association class identify a product instance's software features.
SettingCheck | Instances of this association class relate an application check with its associated setting information.
SoftwareElementAction | Instances of this association class relate a software element with an action that either accesses or configures the software element.
SoftwareElementCheck | Instances of this association class relate a software element with its associated condition or locational information.
SoftwareElementResource | Instances of this association class relate a software element with its associated installation resources.
SoftwareFeatureAction | Instances of this association class relate a feature with an action used to register and/or publish that feature.
SoftwareFeatureCheck | Instances of this association class relate a feature of a product with its associated condition or locational information.
SoftwareFeatureParent | Instances of this association class relate a software feature to it's parent feature.
SoftwareFeatureSoftwareElements | Instances of this association class identify the software elements that make up a software feature.


External Associations

[This is preliminary documentation and subject to change.]

External Association classes are like association classes except that they represent relationships between objects of Windows Installer classes and objects of standard Win32 classes. Examples of external associations are those that bind software element to a computer or service access point (SAP).

Note A CIM_ComputerSystem object represents the environment in which CIM_SoftwareElements either will be, or already are installed. If a software element is already installed, the CIM_InstalledSoftwareElement association is used to identify the CIM_ComputerSystem object that represents the "environment."

Here is a listing of External Association classes.

Class | Description
InstalledSoftwareElement | Instances of this association class allow you to identify the computer on which a particular software element is installed.
ServiceSpecificationService | Instances of this association class relate a Win32_ServiceSpecification instance from an installation package with its corresponding Win32_Service instance (provided such an instance exists).


Performance Counters Provider

[This is preliminary documentation and subject to change.]

The Performance Counters Provider is a High-Performance API Provider that provides raw counter data, such as the time a disk spends writing data. This provider is only available on the Microsoft® Windows® 2000 platform.

The counter objects are located in the Root\Cimv2 namespace and are derived from Win32_PerfRawData. The WMI class name for a counter object is of the form Win32_PerfRawData_<service_name>_<object_name>. For example, the WMI class name that contains the logical disk counters is Win32_PerfRawData_PerfDisk_LogicalDisk. For a complete list and description of the performance counter objects installed with Windows 2000, see Performance Counters in the Platform Software Development Kit (SDK) documentation at http://msdn.microsoft.com.

You can use IWbemServices or the High-Performance API to access the counter data. Using the High-Performance API causes the provider to be loaded in-process to the client, which provides faster access to the counter data than does IWbemServices. If you are writing clients where speed and a large sampling is important, use the High-Performance API. For details on how to use the High-Performance API to access the counter data, see High-Performance API Client.

The performance counter values are returned in their raw form. You need to apply statistical formulas to the raw data to present meaningful data to the user. For a complete list of the formulas, see Calculations For Raw Counter Data in the Platform Software Development Kit (SDK) documentation at http://msdn.microsoft.com. The list contains the formulas for each counter type.

You can find the counter's type documented in the description for each counter. The descriptions for these Windows 2000 counters are under Performance Counters in the Platform SDK. For those not listed, you can determine the type by looking up the counter's CounterType qualifier value in Winperf.h.

The AutoDiscovery/AutoPurge (ADAP) process collects and maintains the list of current performance counter objects in WMI that are registered on the computer. In addition, ADAP detects when new performance libraries are registered on a Windows 2000 computer and adds their performance counters to the Root\Cimv2 namespace. For more details on the ADAP process, see Maintaining Performance Counter Classes.


Maintaining Performance Counter Classes

[This is preliminary documentation and subject to change.]

The AutoDiscovery/AutoPurge (ADAP) process is responsible for collecting and maintaining performance counter objects in WMI that are registered on the computer. The ADAP process starts when the winmgmt service is started or when performance libraries, which contain the performance counters, are installed/uninstalled using the lodctr/unlodctr utilities. You can verify the current state of the ADAP process by examining the Status property of the __ADAPStatus system class.

The ADAP process compares the list of counter objects found in the performance libraries to the list of counter classes contained in WMI. Counter objects that currently do not exist in WMI as counter classes are added to WMI. Existing WMI counter classes are compared to the corresponding performance library counter objects, and are replaced if differences are detected. A WMI counter class is only deleted if ADAP detects that the performance library that contains the counter object has been uninstalled, or the class is no longer contained in the performance library.

For details on the rules ADAP uses to parse the performance library, see Parsing the Performance Library. For details on how you can view errors that are logged by ADAP in the event log, see Viewing ADAP Errors.


Parsing the Performance Library

[This is preliminary documentation and subject to change.]

A performance library is considered inactive if it is loaded, but is unable to provide information at that moment. This can occur if the Open function fails, the Collect function returns an empty BLOB, or the Open, Collect, or Close functions do not return within one minute (a timeout condition can occur when the library is trying to get data from a service that is not running).

A performance library is considered to be unloaded if it can no longer provide data. This can occur if the library has been removed or there are no registry values for First Counter, Last Counter, and Object List in the service's performance subkey. Unloaded performance libraries will have their corresponding performance objects removed from WMI.

A performance library is disabled if ADAP fails three times to load the performance library. This can occur if the ADAP process prematurely stops while processing the performance library. After the third time, the library is marked as disabled. The library is immediately marked as disabled if

  • The Open, Collect, or Close function of the performance library throws an exception.
  • A library entry point is invalid.
  • The collection buffer is invalid.

The library is marked by setting the WbemADAPStatus registry value to -1 in the service's performance subkey. The library is ignored until the library's file size and date change, at which time, ADAP will attempt to load the library.

ADAP logs events for libraries that time out or whose WbemADAPStatus value is set to -1. For details on how to view ADAP errors in the event log, see Viewing ADAP Errors.

WMI is not updated if the WMI class cannot be built from the performance library. ADAP logs events if it is unable to parse the object returned by a performance library. The following rules are enforced when ADAP parses the performance library's counter object. For definitions of the performance library terminology, such as Global and Costly BLOBs, see chapters 12 and 13 of the Windows NT 3.51 Resource Kit, volume 4.

  • Only the objects in the Global BLOB are processed when objects found in both the Global and Costly BLOBs use the same object index.
  • Costly BLOBs will always have "_Costly" appended to their class name.
  • You cannot have two different non-base property indexes with the same name.
  • A numerator can have only one base defined for it.
  • A base property will inherit the name of its numerator property. The base property will have the "_Base" suffix appended to its property name.
  • White space and non-alphanumeric characters are removed from the object and property indexes when the class and property names are generated. The following non-alphanumeric characters are converted as shown.
Original | Converted result
% | Percent
/ | Per
@ | At
& | And
# | Number

  • Localized versions of the class are generated for each language defined in the performance library's subkey.
  • To prevent duplicate counter object names in WMI, the service name is included in the WMI class name. For example, the performance library service name for the logical disk counter object is PerfDisk. ADAP uses PerfDisk to create the following WMI class name for the logical disk counter class: Win32_PerfRawData_PerfDisk_LogicalDisk. The service name is the key name found in the registry at HKEY_LOCAL_MACHINE\CurrentControlSet\Services\service_name.


Viewing ADAP Errors

[This is preliminary documentation and subject to change.]

Errors generated by the ADAP process are logged in the event log. If ADAP fails to create or update a counter object in WMI, look for the reason in the system Event Viewer, Eventvwr.exe. The winmgmt messages are located in the application log.

When the ADAP process determines that a performance library is inactive, the counter object is not reflected in WMI. In addition, ADAP does not log a message indicating the performance library's inactive state in the event log, unless the Open, Collect, or Close functions time-out. For more information on determining whether a performance library is inactive, see Parsing the Performance Library.


Performance Monitor Provider

The Performance Monitor Provider returns performance-related information to management applications. For the Performance Monitor Provider to be available, WMI must be running on a Microsoft® Windows NT®/Microsoft® Windows® 2000 platform.

The Performance Monitor Provider can be used as:

  • An instance provider
  • A property provider

As in instance provider, the Performance Monitor Provider supplies instances of Common Information Model (CIM) classes that represent performance information. As a property provider, the Performance Monitor Provider updates properties for a specific instance.

Note The Performance Monitor provider requires Windows NT version 4.0 or Windows 2000. This provider does not run on Windows 95 or Windows 98.


Registering the Performance Monitor Provider

Because the Performance Monitor Provider is not automatically registered with WMI when WMI installs, management applications wanting to use the Performance Monitor Provider must complete the registration process.

To register the Performance Monitor Provider, applications create instances of two system classes:

  • __Win32Provider
  • __InstanceProviderRegistration or __PropertyProviderRegistration

Regardless of whether the Performance Monitor Provider is registered as an instance or property provider, applications create a __Win32Provider instance. Applications create an __InstanceProviderRegistration instance to register the Performance Monitor Provider as an instance provider, and a __PropertyProviderRegistration to register it as a property provider.

To register the Performance Monitor Provider as an instance provider, create the following instances:

instance of __Win32Provider as $PMPInst
{
    Name  = "PerfProv";
    ClsId = "{f00b4404-f8f1-11ce-a5b6-00aa00680c3f}";
};

instance of __InstanceProviderRegistration
{
    Provider = $PMPInst;
    SupportsPut = FALSE;
    SupportsGet = TRUE;
    SupportsDelete = FALSE;
    SupportsEnumeration = TRUE;
};

To register the Performance Monitor Provider as a property provider, create these instances:

instance of __Win32Provider as $PMPProp
{
    Name = "PerfPropProv";
    Clsid = "{72967903-68EC-11d0-B729-00AA0062CBB7}";
};

instance of __PropertyProviderRegistration
{
    Provider = $PMPProp;
    SupportsGet = TRUE;
    SupportsPut = FALSE;
};

The following class must also be defined to use the Performance Monitor Provider as a property provider:

class PropPerf
{
  [KEY] string MyKey;
  real32 Available;
};

[DYNPROPS]
instance of PropPerf
{
  MyKey = "abc";
  [PropertyContext("local|memory|available bytes"), DYNAMIC,
   Provider("PerfPropProv")]
  Available;
};

The MOF file containing the definitions can be compiled as a stand-alone file or included in an application-specific MOF file. The application-specific MOF file typically contains classes and instances that are meant to store the performance data. For more information, see Defining Classes for the Performance Monitor Provider.

The Performance Monitor Provider employs the standard registration process for WMI providers. For a complete description of this process, see Registering a Provider.


Defining Classes for the Performance Monitor Provider

Applications using the Performance Monitor Provider must define a class for storing the data that the provider supplies. The NTProcesses class that follows is an example of such a class. This class has four WMI Standard Qualifiers:

  • The Provider qualifier to specify the Performance Monitor Provider as the dynamic provider responsible for managing the data for the class.
  • The ClassContext qualifier to specify information needed by the Performance Monitor Provider to access the data.
  • The PropertyContext qualifiers to identify the Performance Monitor values to be stored in each property.
  • The Key qualifier to specify the property that serves as the key for the class.
[dynamic, provider("PerfProv"), ClassContext("local|Process")]
class NTProcesses
{
    [key]
       String Process;
    [PropertyContext("ID Process")]
         uint32 ID;
    [PropertyContext("Elapsed Time")]
         real32 Time;
    [PropertyContext("Handle Count")]
         uint32 Handles;
    [PropertyContext("Working Set")]
         uint32 WorkingSet;
    [PropertyContext("Working Set Peak")]
         uint32 WorkingSetPeak;
    [PropertyContext("Virtual Bytes")]
         uint32 VirtualBytes;
    [PropertyContext("Virtual Bytes Peak")]
         uint32 VirtualBytesPeak;
    [PropertyContext("Thread Count")]
         uint32 Threads;
    [PropertyContext("Priority Base")]
         uint32 Base;
};

Some of the counter types available from the Performance Monitor Provider cannot be returned as instances. To use these counters in an application, create a singleton class by attaching the Singleton standard qualifier to the class as shown below. Note the lack of a key property.

[Singleton, Dynamic, Provider("PerfProv"),
ClassContext("local|Memory")]
class memory
{
    [PropertyContext("Available Bytes")]
         uint32 Avail;
    [PropertyContext("Cache Bytes")]
         uint32 Cache;
};


Registry Provider

The Registry Provider enables management applications to retrieve and modify data in the system registry, and to receive notifications when changes occur. The registry can reside on either a local or remote computer.

The Registry Provider can be used as an instance provider, a property provider, or an event provider. The Registry instance provider supplies instances of classes representing registry keys. For example, the Registry instance Provider can provide access to data that is specific to Microsoft® Windows NT®/Microsoft® Windows® 2000 computers. It is located under the registry key HKEY_LOCAL_MACHINE\Hardware\ResourceMap.

The Registry property provider retrieves and updates individual values for a particular key. The Registry event provider sends notifications when changes occur to keys and key hierarchies and to individual registry values. The notifications do not include specific information about the change. They only report that a change of some type occurred to the target tree, key, or value.

To use any of the Registry providers, applications must complete the registration process for each provider.

To use the Registry instance or property provider, applications must define classes that are used to hold the registry data.

To use the Registry event provider, applications must register as a consumer by specifying the particular events for which they want to be notified.

Note The Registry provider requires Windows NT version 4.0, Windows 2000, or Windows 98. This provider does not run on Windows 95.


Registering the Registry Provider

Because the Registry Provider is not registered automatically with WMI as part of the WMI installation process, applications wanting to use it must complete the registration. An application registers the Registry Provider by creating a Managed Object Format (MOF) file with instances of registration classes and then either compiling it as a stand-alone file or including it at the top of an application-specific MOF file. The application-specific MOF file contains the classes and instances used to access the registry data.

The newly-created MOF file contains an instance of the __Win32Provider class and one of the following instances, depending on whether the application intends to use the Registry Provider as an instance, property, or event provider:

  • __InstanceProviderRegistration
  • __PropertyProviderRegistration
  • __EventProviderRegistration
  • __MethodProviderRegistration

The __Win32Provider instance describes the name of the provider and its class identifier (CLSID). The other instances describe the features of the different providers. For the instance and class providers, features include the ability to support data modification, deletion, enumeration, retrieval, and query processing. For the event provider, the features include the specific event classes that are supported.

The following instances can be used to register the Registry Provider as an instance provider:

// Instance provider
instance of __Win32Provider as $InstProv
{
    Name    = "RegProv" ;
    ClsId   = "{fe9af5c0-d3b6-11ce-a5b6-00aa00680c3f}" ;
};

instance of __InstanceProviderRegistration
{
    Provider = $InstProv;
    SupportsPut = TRUE;
    SupportsGet = TRUE;
    SupportsDelete = FALSE;
    SupportsEnumeration = TRUE;
};

The following instances can be used to register the Registry Provider as a property provider:

// Property provider
instance of __Win32Provider as $PropProv
{
    Name = "RegPropProv";
    Clsid = "{72967901-68EC-11d0-B729-00AA0062CBB7}";
};

instance of __PropertyProviderRegistration
{
    Provider = $PropProv;
    SupportsPut = TRUE;
    SupportsGet = TRUE;
};

The following instances can be used to register the Registry Provider as an event provider:

// Event provider
instance of __Win32Provider as $RegEvent
{
    Name = "RegistryEventProvider";
    Clsid = "{fa77a74e-e109-11d0-ad6e-00c04fd8fdff}";
};

instance of __EventProviderRegistration
{
    Provider = $RegEvent;
    EventQueryList = {
            "select * from RegistryKeyChangeEvent",
            "select * from RegistryValueChangeEvent",
            "select * from RegistryTreeChangeEvent"};
};

The following instances can be used to register the Registry Provider as an method provider:

// Method provider
instance of __Win32Provider as $RegMethod
{
    Name = "RegistryMethodProvider";
    Clsid = "{44DE513E-60C2-11d3-AF33-00C04F79FEB1}";
};

instance of __MethodProviderRegistration
{
    Provider = $RegMethod;
};

The Regevent.mof file that is provided with the WMI SDK contains the __Win32Provider and __EventProviderRegistration instances that are needed to register the Registry Provider as an event provider.

The Registry Provider employs the standard registration process for WMI providers. For a complete description of this process, see Registering a Provider.

For information about the three registry event classes, see Registering for Registry Events.


Defining Classes for the Registry Provider

Management applications using the Registry Provider define classes with properties that represent registry data for particular keys and store the classes in the Common Information Model (CIM) repository. The properties must be created with a data type that maps to the registry data type. For example, if an application is retrieving REG_DWORD data from the registry, its class must include a property that is defined as Uint32.

The following table lists the mapping between registry and WMI data types.

Registry data type | WMI data type
REG_BINARY | Uint8 array
REG_DWORD | Uint32
REG_SZ, REG_EXPAND_SZ | String
REG_MULTI_SZ | String array
REG_RESOURCE_LIST | As appropriate (see Resource Descriptor Data)

The classes that are used to hold registry data are defined with several standard qualifiers. The particular qualifiers and their placement depends on whether the Registry Provider is used as an instance provider or a property provider.

The Dynamic qualifier can be attached to either a class or an instance. It marks the class or instance as being managed dynamically by a provider. When Dynamic appears on a class or instance, the Provider qualifier must also appear. The Provider qualifier identifies the particular provider that is responsible for managing the dynamic class or instance.

The ClassContext qualifier is attached to a class. It specifies the path to the registry key that contains the information the class represents. The ClassContext qualifier has the following format:

MACHINE_NAME|Subtree\\KeyPath

The value for KeyPath can be long if it includes keys with subkeys. For example, the following ClassContext qualifier contains the path to a particular computer's transport devices:

Machine_Name|HKEY_LOCAL_MACHINE\\SOFTWARE\\MICROSOFT\\WBEM
\\TRANSPORTS

The following template for a class definition illustrates the use of the Dynamic, Provider, and ClassContext qualifiers. The provider named by the Provider qualifier is the instance Registry Provider. Note that registry paths are case-insensitive, as are qualifier names.

[dynamic, provider("RegProv"), ClassContext("local|hkey_local_machine\\software\\microsoft\\WBEM\\
transports\\Network Transport Modules")]

class RegTrans
{
  [key] string  TransportsGUID;
  [PropertyContext("Name")] string Name;
  [PropertyContext("Independent")] uint32 Enabled;
};

Management applications can use the Registry Provider to retrieve and modify registry data for a particular key. To use the Registry Provider as a property provider, applications define classes that are marked with the DynProps, Provider, and PropertyText standard qualifiers.

The DynProps qualifier identifies a class as having properties that are maintained by the property provider identified by the Provider qualifier. The PropertyContext qualifier specifies the name of the registry value to be stored by the property. The format of the PropertyContext qualifier is the same as the format of the ClassContext qualifier with additional valuename and expression values:

MACHINE_NAME | Subtree\\KeyPath [|valuename [expression]]

Both valuename and expression are optional. The valuename setting is only used if the registry value has a name. expression is also optional and is used for resource descriptor data.

The following class uses the Registry Provider as a property provider to maintain its non-key properties:

[DYNPROPS]
class PropReg {

    [KEY]  STRING  MyKey;
    STRING Logging;
    STRING Events;
    uint32 Resource1;
};

[DYNPROPS]
instance of PropReg
{
  MyKey = "a";

  [PropertyContext("local|hkey_local_Machine\\software\\microsoft\\
   wbem\\cimom|Logging"), Dynamic, Provider("RegPropProv")]  Logging;

  [PropertyContext("local|hkey_local_Machine\\software\\microsoft\\
   wbem\\cimom|EnableEvents"), Dynamic, Provider("RegPropProv")]
   Events;

  [PropertyContext("local|hkey_local_Machine\\hardware\\
   ResourceMap\\Hardware Abstraction Layer\\PC Compatible Eisa/isa
   hal|.raw(\"Internal\")(0)(0)(\"interrupt.vector\")"), Dynamic,
   Provider("RegPropProv")]  Resource1;
};


Resource Descriptor Data

The system registry contains resource-related data for computers that run Windows NT/Windows 2000. This data is located under the registry key HKEY_LOCAL_MACHINE\Hardware\ResourceMap, and is kept in a special registry data type named REG_RESOURCE_LIST. Applications can obtain the resource-related data through the Registry Provider, one of the built-in providers that is included with the WMI SDK.

To store resource-related data in the system registry, specify a string that contains the following fields.

Field | Description
Interface type | One of the following values are valid: Internal, Isa, Eisa, MicroChannel, TurboChannel, PCIBus, VMEBus, NuBus, PCMCIABus, CBus, MPIBus, or MPSABus.
Bus number | An integer specifying the bus number.
Partial descriptor number | An integer specifying the descriptor number.
Offset or union type | One of the following values are valid: Port.Start, Port.PhysicalAddress, Port.Length, Interrupt.Level, Interrupt.Vector, Interrupt.Affinity, Memory.Start, Memory.PhysicalAddress, Memory.Length, Dma.Channel, Dma.Port, Dma.Reserved1, DeviceSpecificData.DataSize, DeviceSpecificData.Reserved1, or DeviceSpecificData.Reserved2.

For example, the following resource descriptor illustrates a valid string:

local|hkey_local_machine\hardware\resourcemap\
  hardware abstraction layer\
  pc compatible eisa/isa HAL|.raw("eisa",0,0,"interrupt.affinity")


Registering for Registry Events

To receive notifications from the Registry Provider, a management application must register as a temporary event consumer. Registering as a temporary event consumer involves:

  1. Implementing the IWbemObjectSink interface. The Registry Event Provider calls the methods of this interface to deliver event notifications and report status.
  2. Calling the COM function CoInitializeSecurity to initialize Distributed COM (DCOM) security.
  3. Calling the IWbemServices::ExecNotificationQueryAsync method to register to be notified of particular the types of registry events.

The bstrQuery parameter of ExecNotificationQueryAsync must be set to one or more valid event queries that specify an event class that is supported by the Registry Event Provider. The Registry Event Provider supports three classes of events:

Event class | Description
RegistryTreeChangeEvent | Monitors changes to a hierarchy of keys.
RegistryKeyChangeEvent | Monitors changes to a single key.
RegistryValueChangeEvent | Monitors changes to a single value.

All three of these classes have a property called Hive that identifies the hierarchy of keys to be monitored for change, such as HKEY_LOCAL_MACHINE. The location of the tree, key, or value to be monitored is specified in the RootPath property of the RegistryTreeChangeEvent class, the KeyPath property of the RegistryKeyChangeEvent class, and the KeyPath and ValueName properties of the RegistryValueChange class.

Each event query in the bstrQuery parameter of ExecNotificationQueryAsync must contain a WHERE clause that includes each of the properties in the specified event class. For example, set bstrQuery as follows to register for tree change events in the "HKEY_LOCAL_MACHINE\Software" tree:

SELECT * FROM RegistryTreeChangeEvent
    WHERE Hive = "HKEY_LOCAL_MACHINE" AND Rootpath = "Software"

It is important that the event query be explicit. The provider should be able to infer from the query a list of possible values for every property in the event class. For example, the following event query correctly registers for tree change events:

SELECT * FROM RegistryTreeChangeEvent
    WHERE (hive = "hkey_local_machine" AND rootpath = "software")
    OR    (hive = "hkey_current_user" AND rootpath = "console")

The following query is an example of an incorrect registration:

SELECT * FROM RegistryTreeChangeEvent
    WHERE hive = hkey_local_machine" OR rootpath ="software"

Because there is no way to evaluate the possible values for each of the properties, WMI rejects the query with the error WBEM_E_TOO_BROAD. This error is returned if the WHERE clause in an event query is missing or is too broad to be of use.

The Registry Event Provider attempts to send one notification for every event that occurs, but there is no guarantee. Consumers are guaranteed, however, to receive one notification for each event registration. For example, suppose a consumer registers for two tree change events, each with the same Hive value but a different RootPath value. If keys in both paths change multiple times, the consumer is guaranteed to receive notifications of at least two events, one for each path. Depending on the response time of the registry and the Registry Event Provider, the consumer may receive as many notifications as there were occurrences of events.

For more information about registration, see Temporary Event Consumers.

For more information about constructing valid queries, see Event Queries.

Note The WITHIN clause must be included in event queries to be used on Windows 95 and Windows 98 platforms. This clause is unnecessary on Windows NT/Windows 2000 platforms. For information about the WITHIN clause, see WITHIN Clause.


Accessing Unnamed Registry Values

The default, or unnamed value of a registry key is shown as "(Default)" or "<No Name>" in the registry editors (Regedit and RegEdt32). To retrieve this unnamed value, define a property and set its PropertyContext qualifier to an empty string. For example, the following class defines properties to hold values for the key specified by the ClassContext qualifier. The default value is stored in the Default property:

[dynamic, provider("RegProv"), ClassContext("local|hkey_local_machine\\software\\microsoft\\Active Setup\\Installed Components")]

class RegTrans{
  [key]                                     String Transports="";
  [PropertyContext("")]         String Default;
  [PropertyContext("ComponentId")] String ComponentID;
  [PropertyContext("Locale")]  String Locale;
};

The Transports key does not use the unnamed value, so compilation of this MOF file does not produce any value for the Default property unless you use a registry editing tool to change the unnamed value.

To get a description of bitmap files, which is an unnamed value, you need to set the PropertyContext qualifier as follows:

Local|hkey_classes_root\\.bmp


WDM Provider

The Windows Driver Model (WDM) provider allows you to access the classes, instances, methods, and events of Windows Management Instrumentation for the Windows Driver Model (WMI for WDM).

WMI for WDM is a set of extensions to WDM, an operating system interface through which hardware components can provide information and notification of events. WMI for WDM simplifies the instrumentation of drivers and applications written for Microsoft® Windows® operating systems. It provides detailed and extensible information that is consistent across different vendors' products and enables consistent access to Windows instrumentation from non-Windows environments.

The WDM provider is a group of standard WMI providers that are included with the WMI SDK. These providers allow management applications access to data and events from WMI-for-WDM – enabled device drivers. For information on writing WMI-for-WDM – enabled device drivers, see http://www.microsoft.com/ddk.

The WDM provider group consists of the following types of providers:

  • Class provider
  • Instance provider
  • Method provider
  • Event provider

The WMI for WDM class provider stores class definitions in the Common Information Model (CIM) repository during its initialization process. These definitions are taken from binary Managed Object Format (MOF) data that is supplied by WMI for WDM drivers. After initialization, the WMI for WDM class provider relies on WMI to handle all requests from applications. The class definitions remain static until a request is made. The class provider determines whether the data being requested is current and updates the repository, if necessary. The WDM class provider is designed as a push provider. For more information about provider models, see Pull and Push Providers.

The WMI for WDM instance provider supplies instances of classes defined by the WMI for WDM class provider. The WMI for WDM instance provider is a dynamic provider; it supplies instances created by device drivers and user mode applications. Applications can use the WMI for WDM instance provider to update information in a WMI for WDM driver if that driver supports dynamic modification.

The WMI for WDM method provider enables applications to invoke methods that are defined in WMI for WDM drivers.

The WMI for WDM event provider receives events from WMI for WDM devices and translates them into a specific type of WMI event. This WMI event type is represented by the WMIEvent class, a subclass of the __ExtrinsicEvent system class. To communicate with WMI for WDM user mode applications and kernel mode devices, the WDM providers use two components called the User Mode Agent and the Kernel Mode Agent. These agents provide a private gateway between the two modes of the operating system. The hardware interface in the kernel mode is used by device driver vendors to retrieve information from the devices.

The following diagram shows how applications interact with WMI for WDM device drivers through WMI and the WDM providers. The dynamic instance, method, and event providers communicate with the WMI for WDM devices through the WMICORE dynamic-link library (DLL).

Note The WDM provider requires Windows 98 or Windows 2000. This provider does not run on Windows 95 or Microsoft® Windows NT® version 4.0.


Registering the WDM Provider

The WMI for WDM class, instance, method, and event providers are registered automatically when WMI is installed. It is not necessary for a client application to complete the standard registration process for providers. Each of the registered WDM providers has an associated entry in the compiled Wmi.mof file (included with the WMI SDK). This file contains all of the instances required for registration. There are two instances of the __Win32Provider system class, one for the data and method providers and another for the event provider, and instances of the following four classes:

__ClassProviderRegistration

__InstanceProviderRegistration

__MethodProviderRegistration

__EventProviderRegistration

The WMI for WDM class, instance, and method providers are registered with the following instances:

instance of __Win32Provider as $WMIData
{
  Name = "WMIProv";
  ClsId   = "{D2D588B5-D081-11d0-99E0-00C04FC2F8EC}" ;
  PerUserInitialization = "TRUE";
};

instance of __ClassProviderRegistration
{
  Provider = $WMIData;
  InteractionType = 1;
  ResultSetQueries = {"select * from meta_class"};
  ReferencedSetQueries ={"select * from meta_class"};
  UnsupportedQueries = NULL;
  SupportsGet = "TRUE";
  SupportsPut = "FALSE";
  SupportsEnumeration = "TRUE";
  SupportsDelete = "FALSE";
};

instance of __InstanceProviderRegistration
{
  Provider = $WMIData;
  SupportsGet = "TRUE";
  SupportsPut = "TRUE";
  SupportsEnumeration = "TRUE";
  SupportsDelete = "FALSE";
};

instance of __MethodProviderRegistration
{
  Provider = $WMIData;
};

The WMI for WDM event provider is registered with these instances:

instance of __Win32Provider as $WMIEvent
{
  Name = "WMIEventProv";
  ClsId   = "{0725C3CB-FEFB-11d0-99F9-00C04FC2F8EC}";
};

instance of __EventProviderRegistration
{
  Provider = $WMIEvent;
  EventQueryList = {"select * from WMIEvent"};
};

The WDM provider employs the standard registration process for WMI providers. For a complete description of this process, see Registering a Provider.


Registering for WDM Events

The WMI for WDM event provider supports one class of extrinsic event: WMIEvent. To register to receive notifications of this type of event from the WMI for WDM event provider, create an event filter as follows where the globally unique identifier (GUID) value in the Name property is replaced by a valid class identifier (CLSID):

Instance of __EventFilter
{
  Name = "{GUID}";
  Query = "select * from WMIEvent";
  QueryLanguage = "WQL";
}

After registration, temporary consumers can receive notifications of WMI for WDM events synchronously by calling IWbemServices::ExecNotification or asynchronously by calling CoInitializeSecurity and then IWbemServices::ExecNotificationAsync. For more information, see Registering as a Temporary Consumer.

Permanent consumers can also receive notifications of WMI for WDM events. Registering as a permanent consumer is a more complicated process than registering as a temporary consumer. For information about permanent consumers, see Registering as a Permanent Consumer.


WMIBinaryMofResource Class

The WMIBinaryMofResource class in the Root\WMI namespace supports the WMI for WDM class provider in the task of keeping track of the status of data in the CIM repository. The WMIBinaryMofResource class is defined as follows:

class WMIBinaryMofResource
{
    [read,key]     string Name;
    [read,key]     uint32 LowDateTime ;
    [read,key]     uint32 HighDateTime ;
};

Each WMI-for-WDM class provider creates an instance of this class when it compiles the binary mof which defines the class. The Name property gives the name of the WMI-for-WDM – enabled driver that compiled the mof file. The LowDateTime and HighDateTime properties hold the timestamp of the provider. Whenever the provider is initialized, it compares its time-stamp with the time-stamp of the mof file. If they differ, it compiles the mof file again; otherwise, it does nothing.


Win32 Provider

The Microsoft® Win32® Provider retrieves and updates data relevant to Win32 systems—data such as the current settings of environment variables and the attributes of a logical disk. With the Win32 Provider, management applications can use WMI to easily access this data. The Win32 provider retrieves its information by making Win32 function calls and querying the system registry.

The Win32 Provider defines the classes used to describe hardware or software available on Win32 systems and the relationships between them. The Win32 classes ultimately derive from Common Information Model (CIM) classes, which describe components present in all management environments.

The Win32 classes follow the WMI naming convention. The schema name appears first followed by an underscore and then a descriptive name. For example, an instance of Win32_PointingDevice class represents a device that is used to point to regions on a Win32 system display, and an instance of the Win32_Processor class represents a device that can interpret a sequence of Win32 system machine instructions. Although most of the classes apply to any Win32 system, some classes and their properties are specific to the Microsoft® Windows NT®, Microsoft® Windows® 2000, Windows 95, and Windows 98 operating systems.


Registering the Win32 Provider

Because the Microsoft Win32 Provider is registered automatically as part of the WMI installation process, applications typically need not register it independently. All of the Win32 class definitions are stored in the CIM repository and made available through the WMI API. However, if an application does need to register the Win32 Provider, it does so by compiling the Cimwin32.mof file using the MOF compiler. To compile the Cimwin32.mof file at the command prompt, use the following syntax where <WBEM install dir> represents the location of the WMI installation, for example: C:\WINNT\System32\WBEM.

C:\> <WBEM install dir>\mofcomp <WBEM install dir>\cimwin32.mof

The following definitions can be used to register the Win32 Provider:

instance of __Win32Provider as $WinProv
{
    Name = "CIMWin32";
    ClsId = "{d63a5850-8f16-11cf-9f47-00aa00bf345c}";
};
instance of __InstanceProviderRegistration
{
    Provider = $WinProv;
    SupportsGet = "TRUE";
    SupportsPut = "TRUE";
    SupportsDelete = "TRUE";
    SupportsEnumeration = "TRUE";
    QuerySupportLevels = {"WQL:UnarySelect"};
};
instance of __MethodProviderRegistration
{
    Provider = $WinProv;
};

The Win32 Provider employs the standard registration process for WMI providers. For a complete description of this process, see Registering a Provider.


Setting Win32 Provider Properties

Most of the properties defined in the Win32 classes are read-only. Applications using the Win32 Provider cannot change them. However, there are several properties that are not read-only. The following classes contain properties that can be set by client applications:

Win32_ComputerSystem

Win32_Environment

Win32_LogicalDisk

Win32_OperatingSystem

Win32_OSRecoveryConfiguration

Win32_PageFileSetting

Win32_Registry


Setting Properties in the Win32_ComputerSystem Class

The Win32_ComputerSystem class represents computer systems operating in the Win32 environment. The Win32 Provider calls WritePrivateProfileSection and WritePrivateProfileString functions to update the information. To retrieve the information, the Win32 Provider calls a variety of Win32 functions such as GetPrivateProfileSection, GetSystemInfo, and GetSystemMetrics.

The Win32_ComputerSystem class has two properties that can be modified SystemStartupDelay and SystemStartupSetting. SystemStartupDelay is the number of seconds before the computer's default operating system is started. The user can select an alternate operating system in the seconds before this timer expires.

SystemStartupSetting is the index value for the entry in the Boot.ini file that contains the default operating system to be started when the computer boots up. When a client application calls IWbemServices::GetObject or GetObjectAsync to retrieve the current value of this property, the Win32 Provider always returns 0, indicating the first entry in the file. This is because the Boot.ini file always has the default operating system in the first position. When PutInstance or PutInstanceAsync is called to modify the SystemStartupSetting property and change default operating system, the Boot.ini file places the entry that corresponds to the specified index in the first position.

The data types of the SystemStartupDelay and SystemStartupSetting properties are listed in the following table.

Property | Data type
SystemStartupDelay | Uint16
SystemStartupSetting | Uint8


Setting Properties in the Win32_Environment Class

The Win32_Environment class represents environments or system environment variables on a Windows NT/Windows 2000 Win32 system. The Win32 Provider uses registry functions to retrieve and set the environment variables represented by this class. Only Windows NT/Windows 2000 systems can set environment variables.

The following Win32_Environment properties can be modified:

  • UserName
  • Name
  • VariableValue

The UserName property is a character string that specifies the user to which the environment variable identified by Name applies. If the variable is a system environment variable, indicated by SystemVariable being set to TRUE, UserName must be set to <SYSTEM>. Otherwise, UserName is set to the name of a specific user.

The Name property is a character string specifying the name of a Win32 environment variable. By specifying the name of a variable that does not yet exist, an application can create a new environment variable.

The VariableValue property is a character string that specifies the value of the environment variable identified by the Name property.


Setting Properties in the Win32_LogicalDisk Class

The Win32_LogicalDisk class represents logical disks on a Win32 system. It has a single modifiable property: VolumeName. VolumeName is a string that specifies the name of the volume on a logical disk. The volume name must be 11 characters or less for a disk drive on a FAT file system and 32 characters or less for an NTFS disk drive. The Win32 Provider calls the Win32 function GetVolumeInformation to retrieve volume information for a logical disk and the SetVolumeLabel function to update it.


Setting Properties in the Win32_OperatingSystem Class

The Win32_OperatingSystem class represents a Win32 operating system. The values for the writeable properties in this class are stored under Win32PrioritySeparation value for the following registry key:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\PriorityControl

The Win32 Provider calls GetCurrentKeyValue to retrieve the Win32_OperatingSystem properties and RegSetValueEx to set the modifiable properties. There are three modifiable properties in the Win32_OperatingSystem class:

  • ForegroundApplicationBoost
  • QuantumLength
  • QuantumType

The ForegroundApplicationBoost property is an 8-bit number that specifies the number of points that need to be added to an application's priority when that application is brought to the foreground. By default, the foreground application has a base process priority that is one point higher than the background application. The ForegroundApplicationBoost property can be set to 0, 1, or 2.

The QuantumLength and QuantumType properties concern the amount of processing time that the operating system scheduler assigns to an application. Processing time is allotted in units of clock ticks called quantums. Quantums are used to prevent CPU-bound threads from monopolizing the processor. When a thread has been running for one quantum, the kernel preempts it and moves it to the end of the ready queue for its priority.

The QuantumLength property is an 8-bit number that specifies the number of clock ticks before an application is swapped out. The actual length of a thread's quantum currently varies from 15 milliseconds to 30 milliseconds across different Windows NT/Windows 2000 platforms. QuantumLength can be set to 0, 1, or 2.

The QuantumType property is an 8-bit number that specifies either fixed or variable length quantums. Windows NT Workstation/Windows 2000 Professional defaults to variable length quantums where the foreground application has a longer quantum than the background applications. Windows NT Server/Windows 2000 Server defaults to fixed length quantums. QuantumType can be set to 0, 1, or 2.


Setting Properties in the Win32_OSRecoveryConfiguration Class

The Win32_OSRecoveryConfiguration class contains information about the recovery of a Win32 system in the event of a failure. Because the properties of this class are registry key values, the Win32 Provider calls GetCurrentKeyValue to retrieve relevant information.

The Win32_OSRecoveryConfiguration class has the following modifiable properties:

  • AutoReboot
  • DebugFilePath
  • OverWriteExistingDebugFile
  • SendAdminAlert
  • WriteDebugInfo
  • WriteToSystemLog

The AutoReboot property is a Boolean value that specifies whether a system can be automatically rebooted during a recovery operation. If it is set to TRUE, the system is automatically rebooted; otherwise, it is FALSE.

The AutoReboot property is stored as the AutoReboot value for the following registry key:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\CrashControl

When an application calls IWbemServices::PutInstance or IWbemServices::PutInstanceAsync to update the AutoReboot property, the Win32 Provider calls the registry function RegSetValueEx.

The DebugFilePath property indicates the full path to the debug file.

The OverwriteExistingDebugFile property determines whether or not to overwrite an existing debug file. This property is valid only if the WriteDebugInfo property is set to TRUE. If OverwriteExistingDebugFile is set to TRUE, the existing debug file is overwritten. If set to FALSE, the file is not overwritten.

The SendAdminAlert property determines whether or not an alert message will sent to the system administrator in the event of an operating system failure. If SendAdminAlert is set to TRUE, the system sends an alert. If set to FALSE, no alert is sent.

The WriteDebugInfo property determines whether or not debug information will be written to a file. If WriteDebugInfo is set to TRUE, debug information is written. If set to FALSE, no information is written.

The WriteToSystemLog property determines whether system failure information will be written to a system log file. If WriteToSystemLog is set to TRUE, system failure information is written to a log file. If set to FALSE, no information is written.


Setting Properties in the Win32_PageFileSetting Class

The Win32_PageFileSetting class represents data files that describe the paging characteristics of a Windows NT/Windows 2000 system. Each instance of the Win32_PageFileSetting class represents a different page file. The Win32_PageFileSetting class has three modifiable properties:

  • Name
  • InitialSize
  • MaximumSize

These properties are read/write only on Windows NT/Windows 2000 systems because on Windows 95 systems there is a single page file. The name of this single page file is stored in the System.ini initialization file.

The Win32 Provider retrieves an array of information about each existing page file by making calls to the system registry. Changes to the page file do not take effect until after the system is restarted.

The Name property is a character string containing the name of a page file. By specifying the name of a file that does not yet exist, an application can create a new page file on the computer. The name must be a complete file name, including the drive letter and directory hierarchy. The Win32 Provider does not validate the specified name. The application ensures that all parts in the name are valid.

The InitialSize and MaximumSize properties are 32-bit integers. InitialSize specifies the number of megabytes that a page file contains when it is first created. MaximumSize specifies the maximum number of megabytes that a page file can ever contain.


Setting Properties in the Win32_Registry Class

The Win32_Registry class represents the system registry. With the Win32_Registry class, management applications can use the Win32 Provider to access registry data through WMI. The Win32 Provider calls Windows NT/Windows 2000 internal functions to retrieve information for all of the properties of the Win32_Registry class. There is only one modifiable property: ProposedSize. The Win32 Provider calls RegSetValueEx to modify it.

The ProposedSize property is a 32-bit integer that specifies the maximum number of megabytes for the registry. A change to the proposed maximum size of the registry takes effect only after the system is restarted.


Calling Win32 Provider Methods

The Win32 Provider Win32_OperatingSystem class includes three methods:

  • Shutdown
  • Reboot
  • Win32Shutdown


Calling the Shutdown Method

The Win32_OperatingSystem class implements the Shutdown method. Management applications running on Windows NT/Windows 2000 systems can use this method to request a shutdown of the operating system. The return value should be 0 if the request was successfully executed, 1 if the request is not supported, and some other value if an error occurred. After a successful shutdown, it is safe to turn the power off.

It is up to the Win32_OperatingSystem subclass to establish dependencies between the Shutdown and Reboot methods, and, for example, to provide more sophisticated capabilities such as scheduled shutdown and reboot.

The Shutdown method is defined as follows:

uint32 Shutdown ([in] sint32 Flags, [in] sint32 Reserved = 0);

The Win32 Provider calls the ExitWindowsEx function to implement the Shutdown method. For more information, see the documentation of the ExitWindowsEx function in the Win32 SDK.


Calling the Reboot Method

Win32_OperatingSystem class implements the Reboot method. Management applications running on Windows NT/Windows 2000 systems can use this method to request a reboot of the operating system. The Reboot method is defined as follows:

uint32 Reboot ();

If the request was successfully executed, Reboot returns 0. If the request is not supported or an error occurs, Reboot returns 1.


Calling the Win32Shutdown Method

The Win32_OperatingSystem class implements the Win32Shutdown method. Management applications running on Windows NT/Windows 2000 systems can use this method to initiate a shutdown with the full set of options supported by Win32 operating systems. The Shutdown method is defined as follows:

uint32 Shutdown ([in] sint32 Flags, [in] sint32 Reserved = 0);

To call Win32Shutdown, an application invokes IWbemServices::ExecMethod or IWbemServices::ExecMethodAsync. The application then sets the MethodName parameter to "Shutdown" and the pInParams parameter to point to an IWbemClassObject implementation. This implementation provides access to a bitmask of flags that are used to control the shutdown operation. This bitmask is the Flags parameter in Win32Shutdown, and it can be set to one or more of the following values:

EXW_FORCE

EXW_LOGOFF

EXW_POWEROFF

EXW_REBOOT

EXW_SHUTDOWN

The Win32 Provider calls the ExitWindowsEx function to implement the Win32Shutdown method. For more information, see the documentation of the ExitWindowsEx function in the Win32 SDK.


Power Management Event Provider

[This is preliminary documentation and subject to change.]

Power management is an important component of Microsoft® Windows® 2000. Power management is targeted at laptop computers, but also is viable for desktop and server systems. System power management and device power management work together to effectively and efficiently reduce the power consumed on a given system.

The Win32_PowerManagementEvent class represents power management events resulting from power state changes. These state changes are associated with either the Advanced Power Management (APM) or the Advanced Configuration and Power Interface (ACPI) system management protocols.

For details on how you use the following query to subscribe for power management events, see Event Notification.

SELECT * FROM Win32_PowerManagementEvent


Security Provider

[This is preliminary documentation and subject to change.]

The Security Provider allows you to retrieve or change security settings that control ownership, auditing, and access rights to Microsoft® Windows NT®/Microsoft® Windows® 2000 file system (NTFS) files, directories, and shares.

Information about the Security Provider is contained in the following sections:

  • About the Security Provider

    This section presents an overview of the Security Provider, describes security descriptors, and lists the classes supported by the Security Provider.

  • Using the Security Provider

    This section shows you how to register the Security Provider and gives examples that show how to get and set security descriptors.

Note The Security Provider requires Windows NT version 4.0 or Windows 2000. This provider does not run on Windows 95 or Windows 98.


About the Security Provider

[This is preliminary documentation and subject to change.]

The Security Provider provides access to the security descriptor for specific securable objects. These objects are NTFS files, directories, and shares. You cannot use the Security Provider to retrieve or edit the security descriptor for other securable objects such as the following:

  • Mail slots and named pipes
  • Local or remote printers
  • Local or remote Microsoft® Win32® services
  • Registry keys
  • Semaphores, events, mutexes, and waitable timers
  • Processes, threads, and file-mapping objects

Note You can also modify NTFS security descriptors and file permissions using the Win32 Provider and the methods of the CIM_LogicalFile and Win32_Directory classes. The ChangeSecurityPermissions methods of the Win32_Directory and CIM_LogicalFile classes are similar to the SetSecurityDescriptor method of the Win32_LogicalFileSecuritySetting class supported by the Security Provider.


Security Descriptors

[This is preliminary documentation and subject to change.]

Windows NT/Windows 2000 objects with associated security attributes are called securable objects. Examples of securable objects are files, named pipes, registry keys, user objects, kernel objects, and private objects. The security attributes of securable objects are described by a security descriptor, which contains information about the owner of the object and the object's primary group. The security descriptor also contains two access control lists (ACL). The first list is called the discretionary ACL (DACL) and describes who should have access to an object and what type of access to grant. The second list is called the system ACL (SACL) and defines what type of auditing to record for an object.

Each entry in a DACL or SACL is in the form of an access-control entry (ACE). ACE entries in a DACL are either of type ACCESS_ALLOWED_ACE, or ACCES_DENIED_ACE. ACE entries in a SACL are always of type SYSTEM_AUDIT_ACE.

Each ACE entry contains these properties: AceType, AceFlags, and AccessMask. The AceType property indicates to which of the two types of ACE (ACCESS_ALLOWED_ACE, or ACCESS_DENIED_ACE) the ACE belongs. The AceFlags property indicates how the ACE should be inherited. The AccessMask property indicates what type of access (read, write, execute, view or edit security settings, and so on) the user or group has to the object.

When a DACL is present but empty, no access rights have been explicitly granted. Therefore, access to the object is implicitly denied. However, when an object does not have a DACL, the object does not have any assigned protection and, therefore, any user or group can gain access.

When a SACL is present but empty, or when a SACL is not present at all, there will not be an audit of access to the object.


Security Descriptor Objects

[This is preliminary documentation and subject to change.]

Security descriptor objects are represented by instances of the class Win32_SecurityDescriptor and contain five properties.

Group
Specifies the rights for the group to which this secured object belongs. This property contains an instance of Win32_Trustee.
Owner
Specifies the rights for the owner of this secured object. This property contains an instance of Win32_Trustee.
Control Flags
Set of control bits that qualify the meaning of a security descriptor or its individual members.
DACL
Discretionary access control list (DACL). Controlled by the owner of an object, this property describes the access users or groups have to a secured object and contains an array of Win32_ACE instances. Each user that has been assigned rights for a secured object is represented by an instance of the Win32_ACE class. Instances of the Win32_ACE class contain seven properties, including instances of the Win32_Trustee class. For more information, see Win32_ACE Example.
SACL
System access control list (SACL). Controlled by the system administrator, this property describes the type of access attempts that generate audit records for users or groups and contains an array of Win32_ACE instances. Each user that is being audited for a secured object is represented by an instance of the Win32_ACE class

The following example shows the security descriptor for a file and how the classes are associated.


Win32_ACE Example

[This is preliminary documentation and subject to change.]

Instances of the Win32_ACE class describe the auditing and rights a user or group has to a secured object. The Group and Owner properties of Win32_SecurityDescriptor instances contain instances of Win32_ACE. The DACL and SACL of a security descriptor contains an array of Win32_ACE objects. Instances of Win32_ACE contain an embedded instance of the CIM class Win32_Trustee. Shown below is an example of a Win32_ACE instance.


AccessMask Property

[This is preliminary documentation and subject to change.]

Auditing and the access granted to a trustee is governed by the value of the AccessMask property. When AccessMask is part of a SACL, this number defines what actions by this trustee on a secured object will be audited. Examples of actions that can be audited are reading or executing a secured object. When AccessMask is part of a DACL, this number is a combination of flags that grant read, write, execute, change permission, and take ownership rights. You can combine these flags by taking the logical OR value of the flags for the rights to grant. The actual value of AccessMask depends on the type of object the mask refers to.


Impersonation Level and the Security Provider

[This is preliminary documentation and subject to change.]

You must set the Distributed COM (DCOM) impersonation level of your calls to the Security Provider to the appropriate level. Otherwise, these calls may fail or give you incomplete information. If the Security Provider is running on a Windows NT/Windows 2000 system, you must specify an impersonation level of Delegate to retrieve or set some properties. In Windows NT 4.0, you can use this provider with an impersonation level of Impersonate. However, you may not be able to retrieve full information from remote computers that are running Windows NT/Windows 2000.

For more information about DCOM impersonation, see Setting the DCOM Impersonation Level for the Scripting API.


Administrator Privileges and the Security Provider

[This is preliminary documentation and subject to change.]

If the client using the Security Provider is not logged on with system administrator privileges, some or all the information returned in the SACL of a security descriptor may be NULL, even though actual values may exist in the security descriptor.

If the client does have administrator privileges, no SACL information is returned unless the DACL contains an entry for the client, or an entry for the group to which the client belongs, indicating that the user can access the SACL. This is to prevent the Security Provider from compromising the system's security. Additionally, the client must have security privileges enabled.


Security Provider Classes

[This is preliminary documentation and subject to change.]

The Security Provider defines classes that describe the security settings of securable objects and their associations with other schema classes.

The Security Provider uses the following CIM classes.

Class | Description
Win32_AccountSID | Associates a security account (represented by instances of Win32_Account) and a security descriptor (represented by instances of Win32_SID) instance.
Win32_Ace | Represents an access control entry (ACE).
Win32_SID | Represents an arbitrary SID.
Win32_LogicalFileAccess | Associates the security settings of a file or directory (represented by instances of Win32_LogicalFileSecuritySetting) and one member of its DACL (represented by instances of Win32_SID). The Win32_LogicalFileAccess class represents the ACEs contained within the file's DACL in an instance of Win32_LogicalFileSecuritySetting.
Win32_LogicalFileAuditing | Associates the security settings of a file (represented by instances of Win32_LogicalFileSecuritySetting) and one member of its SACL (represented by instances of Win32_SID). Instances of Win32_LogicalFileAuditing represent ACEs contained within the file's SACL.
Win32_LogicalFileGroup | Associates the security settings of a file (represented by instances of Win32_LogicalFileSecuritySetting) and the security settings for the group the file belongs to (represented by instances of Win32_SID).
Win32_LogicalFileOwner | Associates the security settings of a file (represented by instances of Win32_LogicalFileSecuritySetting) and the security settings of the owner of the file (represented by instances of Win32_SID).
Win32_LogicalFileSecuritySetting | Represents security settings for a logical file.
Win32_SecurityDescriptor | Represents the security descriptor for a securable object. Embedded within this class are instances of Win32_Trustee and Win32_Ace.
Win32_SecuritySettingOfLogicalFile | Associates a CIM_LogicalFile instance and a Win32_LogicalFileSecuritySetting instance.
Win32_SecuritySettingOfLogicalShare | Associates a Win32_Share instance and a Win32_LogicalShareSecuritySetting instance.
Win32_Trustee | Represents a Windows NT/Windows 2000 trustee.

A subset of these classes are listed below in two groups:

  • Security descriptor components

    Classes that represent a security descriptor or parts of the security descriptor.

    • Win32_SecurityDescriptor
    • Win32_Trustee
    • Win32_ACE
  • Classes used to manage security descriptors

    Classes that can be used to retrieve the security descriptors associated with securable objects such as NTFS files, directories, and shares.

    • Win32_LogicalFileSecuritySetting
    • Win32_LogicalShareSecuritySetting


Win32_AccountSid Security Class

[This is preliminary documentation and subject to change.]

The Win32_AccountSid class associates a security account instance (Win32_Account) with a security descriptor instance (Win32_SID).

Properties

The following table lists the properties for Win32_AccountSid.

Property | Type | Description
Element | ref | Reference to an instance of Win32_Account.
Setting | ref | Reference to an instance of Win32_SID.


Win32_ACE Security Class

[This is preliminary documentation and subject to change.]

The Win32_ACE class represents an access control entry (ACE).

Properties

The following table lists the properties for Win32_ACE.

Property | Type | Description
Trustee | Win32_Trustee | User account, group account, or logon session to which an ACE applies.
AceType | Unit32 | Type of access this ACE controls; for example, ACCESS_DENIED_ACE or SYSTEM_AUDIT_ACE.
AceFlags | Unit32 | Specifies how an ACE is inherited.
AccessMask | Long | Access permissions granted or denied for this object.
GuidObjectType | String | Type of object to which the ACE applies (Windows 2000 only).
GuidInheritedObjectType | String | Type of child objects that can inherit the ACE (Windows 2000 only).


Win32_LogicalFileAccess Security Class

[This is preliminary documentation and subject to change.]

The Win32_LogicalFileAccess class associates the security settings of a file or directory (represented by instances of the Win32_LogicalFileSecuritySetting class) and one member of its DACL (represented by instances of the Win32_SID class). The Win32_LogicalFileAccess class represents the access control entry (ACEs) contained within the file's DACL in an instance of the Win32_LogicalFileSecuritySetting class. This class inherits all its properties from the abstract class Win32_SecuritySettingAccess.

Properties

The following table lists the properties for Win32_LogicalFileAccess.

Property | Type | Description
AccessMask | String | Bit flags specifying what permissions are affected.
GuidInheritedObjectType | String | GUID of the type of object from which this object inherits from.
GuidObjectType | String | GUID of the type of object to which the security settings are applied.
Inheritance | uint32 | Bit flags specifying how the access rights are inherited.
SecuritySetting | Ref | Reference to an instance of Win32_LogicalShareSecuritySetting. This property contains the security settings of the file or directory object.
Trustee | Ref | Reference to an instance of Win32_SID. This property contains an entry on the object's DACL.
Type | uint32 | Type of access specified for the trustee.


Win32_LogicalFileAuditing Security Class

[This is preliminary documentation and subject to change.]

The Win32_LogicalFileAuditing class associates the security auditing settings of a file (represented by instances of the Win32_LogicalFileSecuritySetting class) and one member of its DACL (represented by instances of the Win32_SID class). You can use this class to determine the auditing for a given trustee and a file or directory. This class inherits all its properties from the abstract class Win32_SecuritySettingAuditing.

Properties

The following table lists the properties for Win32_LogicalFileAuditing.

Property | Type | Description
AuditedAccessMask | uint32 | Bit flags specifying what activities are audited.
GuidInheritedObjectType | String | GUID of the type of object from which this object inherits.
GuidObjectType | String | GUID of the type of object to which the security settings are applied.
Inheritance | uint32 | Bit flags specifying how the access rights are inherited.
SecuritySetting | ref | Reference to an instance of Win32_LogicalFileSecuritySetting. This property contains the security settings of the file or directory object.
Trustee | ref | Reference to an instance of Win32_SID. This property contains an entry on the object's DACL.
Type | uint32 | Type of access specified for the trustee.


Win32_LogicalFileGroup Security Class

[This is preliminary documentation and subject to change.]

The Win32_LogicalFileGroup represents an association between the security settings of a file or directory and the security settings of the group to which the file or directory belongs.

Properties

The following table lists the properties for Win32_LogicalFileGroup.

Property | Type | Description
Group | ref | Reference to an instance of Win32_SID. This instance represents the security setting of the group.
SecuritySetting | ref | Reference to an instance of Win32_LogicalFileSecuritySetting. This instance represents the security settings of the file.


Win32_LogicalFileOwner Security Class

[This is preliminary documentation and subject to change.]

The Win32_LogicalFileOwner class represents an association between the security settings of a file or directory, and the security settings of the owner of the file.

Properties

The following table lists the properties for Win32_LogicalFileOwner.

Property | Type | Description
Owner | ref | Reference to an instance of Win32_SID. This instance represents the security setting of the owner.
SecuritySetting | ref | Reference to an instance of Win32_LogicalFileSecuritySetting. This instance represents the security settings of the file.


Win32_LogicalFileSecuritySetting Security Class

[This is preliminary documentation and subject to change.]

The Win32_LogicalFileSecuritySetting class represents security settings for a logical file or directory.

Properties

The following table lists the properties for Win32_LogicalFileSecuritySetting.

Property | Type | Description
Caption | String | Short description of the CIM_Setting object.
ControlFlags | uint32 | Inheritance-related flags.
Description | String | Description of the CIM_Setting object.
OwnerPermissions | Boolean | Indicates whether the caller has Owner permissions to the object.
Path | String | Full path of the file or directory.
SettingID | String | Identifier by which the CIM_Setting object is known.

Methods

The following table lists the methods for Win32_LogicalFileSecuritySetting.

Method | Description
GetSecurityDescriptor (Descriptor) | This method gets the properties and embedded objects of a descriptor object that you provide as a input parameter. If the method is successful, you can examine the properties of the descriptor object to determine the specific security settings for the file.
SetSecurityDescriptor (Descriptor) | This method sets the properties and embedded properties for a file based on the descriptor object that you provide as an input parameter.


Win32_LogicalShareAccess Security Class

[This is preliminary documentation and subject to change.]

The Win32_LogicalShareAccess class that associates the security settings of a share (represented by instances of the Win32_LogicalShareSecuritySetting class) and one member of its SACL (represented by instances of the Win32_SID class). The Win32_LogicalShareAccess class represents the access control entry (ACEs) contained within the share's DACL in an instance of the Win32_LogicalShareSecuritySetting class. This class inherits all its properties from the abstract class Win32_SecuritySettingAccess.

Properties

The following table lists the properties for Win32_LogicalShareAccess.

Property | Type | Description
AccessMask | String | Bit flags specifying what permissions are affected.
GuidInheritedObjectType | String | GUID of the type of object from which this object inherits.
GuidObjectType | String | GUID of the type of object to which the security settings are applied.
Inheritance | uint32 | Bit flags specifying how the access rights are inherited.
SecuritySetting | ref | Reference to an instance of Win32_LogicalShareSecuritySetting. This property contains the security settings of the file or directory object.
Trustee | ref | Reference to an instance of Win32_SID. This property contains an entry on the object's DACL.
Type | uint32 | Type of access specified for the trustee.


Win32_LogicalShareAuditing Security Class

[This is preliminary documentation and subject to change.]

The Win32_LogicalShareAuditing class associates the security auditing settings of a share (represented by instances of the Win32_LogicalShareSecuritySetting class) and one member of its SACL (represented by instances of the Win32_SID class). You can use this class to determine the auditing for a given trustee and a share. This class inherits all its properties from the abstract class Win32_SecuritySettingAuditing.

Properties

The following table lists the properties for Win32_LogicalShareAuditing.

Property | Type | Description
AccessMask | String | Bit flags specifying what activities are audited.
GuidInheritedObjectType | String | GUID of the type of object from which this object inherits.
GuidObjectType | String | GUID of the type of object to which the security settings are applied.
Inheritance | uint32 | Bit flags specifying how the access rights are inherited.
SecuritySetting | ref | Reference to an instance of Win32_LogicalShareSecuritySetting. This property contains the security settings of the share object.
Trustee | ref | Reference to an instance of Win32_SID. This property contains an entry on the object's DACL.
Type | uint32 | Type of access specified for the trustee.


Win32_LogicalShareSecuritySetting Security Class

[This is preliminary documentation and subject to change.]

The Win32_LogicalShareSecuritySetting class represents the security settings for a Windows NT/Windows 2000 share.

Properties

The following table lists the properties for Win32_LogicalShareSecuritySetting.

Property | Type | Description
Caption | String | Short description of the CIM_Setting object.
ControlFlags | uint32 | Inheritance-related flags.
Description | String | Description of the CIM_Setting object.
Name | String | Name of the share.
SettingID | String | Identifier by which the CIM_Setting object is known.

Methods

The following table lists the methods for Win32_LogicalShareSecuritySetting.

Method | Description
GetSecurityDescriptor (Descriptor) | This method gets the properties and embedded objects of a descriptor object that you provide as a input parameter. If the method is successful, you can examine the properties of the descriptor object to determine the specific security settings for the share.
SetSecurityDescriptor (Descriptor) | This method sets the properties and embedded properties for an object based on the descriptor object that you provide as an input parameter.


Win32_SecurityDescriptor Security Class

[This is preliminary documentation and subject to change.]

The Win32_SecurityDescriptor class represents the security descriptor for a securable object. The parts of this class are as follows.

Properties

The following table lists the properties for Win32_SecurityDescriptor.

Property | Type | Description
Owner | Win32_Trustee | Specifies the owner of an object.
Group | Win32_Trustee | Specifies the group that owns this object.
DACL | Array of Win32_ACE | Array of Win32_ACE objects. Each array entry defines the types of object access that the system grants to a specific user or group.
SACL | Array of Win32_ACE | Array of Win32_ACE objects. Each array entry defines the types of access attempts that generate audit records a specific user or group.
ControlFlags | unit32 | Set of control bits that qualify the meaning of a security descriptor or its individual members.

The trustees in a DACL are in no specific order and may change if the rights for a specific trustee change.

For an example of a security descriptor for a file, see Security Descriptor Objects.


Win32_SecuritySettingOfLogicalFile Security Class

[This is preliminary documentation and subject to change.]

The Win32_SecuritySettingOfLogicalFile class associates an instance of CIM_LogicalFile with an instance of Win32_LogicalFileSecuritySetting.

Properties

The following table lists the properties for Win32_SecuritySettingOfLogicalFile.

Property | Type | Description
Element | ref | Reference to an instance of CIM_LogicalFile.
Setting | ref | Reference to an instance of Win32_LogicalFileSecuritySetting.


Win32_SecuritySettingOfLogicalShare Security Class

[This is preliminary documentation and subject to change.]

The Win32_SecuritySettingOfLogicalShare class associates an instance of Win32_Share with an instance of Win32_LogicalShareSecuritySetting.

Properties

The following table lists the properties for Win32_SecuritySettingOfLogicalShare.

Property | Type | Description
Element | ref | Reference to an instance of Win32_Share.
Setting | ref | Reference to an instance of Win32_LogicalShareSecuritySetting.


Win32_SID Security Class

[This is preliminary documentation and subject to change.]

The Win32_SID class contains an array of integers that uniquely identify a user or group. An instance of this class is embedded in Win32_Trustee instances.

Properties

The following table lists the properties for Win32_SID.

Property | Type | Description
AccountName | String | Name of the account associated with the SID.
BinaryRepresentation | Array of Unit8 | Binary formatted version of the SID.
ReferencedDomainName | String | Domain of the account associated with the SID.
Sid | String | String-formatted version of the SID. The format of the string is: S-R-I-S-S... In this notation, the literal character S identifies the series of digits as a SID, R is the revision level, I is the identifier-authority value, and S... is one or more subauthority values.
SidLength | Unit32 | Length of the SID in bytes.


Win32_Trustee Security Class

[This is preliminary documentation and subject to change.]

The Win32_Trustee class represents a Windows NT/Windows 2000 trustee.

Properties

The following table lists the properties for Win32_Trustee.

Property | Type | Description
Domain | String | Domain to which the trustee belongs.
Name | String | Specifies a trustee. This can be a user account, group account, or logon session.
Sid | Array of Unit8 | Array of integers that uniquely identifies a user or group.
SidLength | Variant | Variant containing the number of bytes in the SID.
Sidstring | String | Represents the security for a SID as a string. The format of the string is : S-R-I-S-S... In this notation, the literal character S identifies the series of digits as a SID, R is the revision level, I is the identifier-authority value, and S... is one or more subauthority values.


Using the Security Provider

[This is preliminary documentation and subject to change.]

This section provides specific information about how to register the Security Provider and how to work with security descriptors. These topics are discussed:

  • Registering the Security Provider
  • Getting Security Descriptors
  • Setting Security Descriptors


Registering the Security Provider

[This is preliminary documentation and subject to change.]

The Security Provider DLL and classes are registered with Windows Management Instrumentation (WMI) automatically during the WMI installation process. If it is necessary to reregister this provider classes, you can compile the Secrcw32.mof file using the Managed Object Format (MOF) compiler. To compile the Secrcw32.mof file at the command prompt, use the following syntax where <WBEM install dir> represents the location of the WMI installation. for example, C:\WINNT\system32\WBEM:

C:\> <WBEM install dir>\mofcomp <WMI install dir>\secrcw32.mof

The Security Provider is registered with WMI with the following MOF code:

Instance of __Win32Provider as $P
{
    Name = "SECRCW32" ;
    ClsId = "{672460A0-607C-11d1-B327-00A0C967A503}" ;
    ImpersonationLevel = 1;
    PerUserInitialization = "TRUE";
} ;

instance of __InstanceProviderRegistration
{
    Provider = $P;

    SupportsGet = "TRUE";
    SupportsPut = "TRUE";
    SupportsDelete = "TRUE";
    SupportsEnumeration = "TRUE";

    QuerySupportLevels = {"WQL:UnarySelect"};
};

instance of __MethodProviderRegistration
{
    Provider = $P;
};


Getting Security Descriptors

[This is preliminary documentation and subject to change.]

A security descriptor object is a Common Information Model (CIM) object based on the class Win32_SecurityDescriptor. You can get the security descriptor for a securable object by getting an instance of Win32_LogicalFileSecuritySetting or Win32_LogicalShareSecuritySetting and executing the GetSecurityDescriptor method. The properties of the security descriptor object will then contain information about the file, share, or directory.

The following Microsoft® Visual Basic® example retrieves the security descriptor for a file and stores it in the object objDescriptor.

Private Sub Cmd_getdescriptor_Click()
'*******************************************************************
'   Name    :  Cmd_getdescriptor_Click
'
'   Purpose :  This example gets the security descriptor for a file
'              called test.txt from a subdirectory called test on the
'              "D:" drive.
'********************************************************************

   Dim instance As SWbemObject
   Dim objDescriptor As SWbemObject
   On Error Resume Next

   Set instance = _
             GetObject("winmgmts:{impersonationLevel=impersonate}" _
                 & "!root/cimv2:Win32_LogicalFileSecuritySetting=" _
                 & "'D:\\test\\test.txt'")
   If instance Is Nothing Then
      MsgBox ("Unable to retrieve instance")
   Else
      retval = instance.GetSecurityDescriptor(objDescriptor)
      If retval = 0 And Err.Number = 0 Then
         MsgBox ("The security descriptor was obtained")
      Else
         MsgBox ("Error# " & Str(Err.Number) & ": " _
                 & Err.Description & _
                 "occurred when retrieving the security descriptor")
      End If
   End If

End Sub


Setting Security Descriptors

[This is preliminary documentation and subject to change.]

To change the security descriptor for a file, directory, or network share, you need a security descriptor object. You can get a descriptor object based the current security descriptor using a call to the GetSecurityDescriptor method for an instance of Win32_LogicalFileSecuritySetting or Win32_LogicalShareSecuritySetting. After you have the security descriptor object, you can modify its properties and save the changes to the file, directory, or share using the SetSecurityDescriptor method.

You can change the security descriptor property values, but the values you choose must be valid. If you set the values incorrectly, you may lose access to the file, directory, or share.

This example gets the security descriptor for a file on a remote system and stores the DACL, SACL, group, owner, and control flags. Then the AccessMask property for the trustee "Everyone" is set to full access.

'*******************************************************************
'   Name    :  Change_Access
'
'   Purpose :  This example gets the security descriptor for a file
'              called test.txt from a subdirectory called test on the
'              "E:" drive of a remote system. It then grants the
'              group "Everyone" full access. This program will fail
'              if the specified file does not already have rights
'              associated with the group "Everyone".
'********************************************************************
Private Sub Change_Access()

Dim instance As SWbemObject
Dim DACL As SWbemProperty
Dim found As Boolean
Dim accessmask As Long
Dim controlFlags As Long
Dim Group As SWbemProperty
Dim Owner As SWbemProperty
Dim SACL As SWbemProperty
Const FULLACCESS As Long = 2032127
Const ImpLevel = "{impersonationLevel=impersonate}"
Const namespace = "!\\rburns\root\cimv2:"
Const NOTFOUND = -2147217406
Const objectpath = _
       "Win32_LogicalFileSecuritySetting=""E:\\test\\test.txt"""
    strMoniker = "winmgmts:" & ImpLevel & namespace & objectpath
    On Error GoTo errhndlr
    Set instance = GetObject(strMoniker)
     If instance Is Nothing Then
       MsgBox ("Unable to retrieve instance")
       Exit Sub
    End If
  ' Get the security descriptor and store it in objDescriptor
    retval = instance.getsecuritydescriptor(objDescriptor)

      ' get information from the security descriptor.
    Set DACL = objDescriptor.Properties_.Item("dacl") ' get dacl
    controlFlags = objDescriptor.Properties_.Item("controlflags")
    Set Group = objDescriptor.Properties_.Item("Group")
    Set Owner = objDescriptor.Properties_.Item("Owner")
    Set SACL = objDescriptor.Properties_.Item("Sacl")

    number_of_trustees = UBound(DACL.Value)

    For i = 0 To number_of_trustees
        Set trustee_name = DACL.Value(i).Properties_.Item _
               ("trustee").Value.Properties_.Item("name")
        ' get trustee named "Everyone" and set the access mask
        If trustee_name = "Everyone" Then
            found = True
            accessmask = DACL.Value(i).Properties_.Item _
                   ("AccessMask").Value  ' Save the accessmask
            MsgBox ("Accessmask for trustee " & trustee_name _
                   & " is currently: " & accessmask)
            MsgBox ("Accessmask for trustee " & trustee_name _
                   & " will be set to: " & FULLACCESS)
            ' set the accessmask property in the descriptor object
            objDescriptor.Properties_.Item("dacl").Value(i) _
                   .Properties_.Item("AccessMask").Value = FULLACCESS
        End If
    Next i
    If found Then 'save the descriptor
        retval = instance.setsecuritydescriptor(objDescriptor)
          If retval = 0 Then
             MsgBox "success!"
          Else
             MsgBox "Unable to save security descriptor"
          End If
    Else
        MsgBox ("The trustee ""Everyone"" was not found")
    End If

Exit Sub

errhndlr:
If Err.Number = NOTFOUND Then
    MsgBox "The file you are attempting to change permissions could" _
            & " not be found. "
Else
    MsgBox "Error# " & Str(Err.Number) & ": " & Err.Description & _
              " occurred"
End If

End Sub


Creating a Share With the Scripting API

This example creates and sets the security descriptor for a new share with the following steps:

1) Connect to Windows Management.

2) Set the impersonation level and the NT privilege that lets you set DACLs and SACL's.

3) Create a new security descriptor and set up a couple of ACE's for the new share.

4) Create a new share with the new security descriptor.

 '*******************************************************************
'   Name    :  CreateShare.vbs
'
'   Purpose :  This example creates a new share and sets the
'              security descriptor for the new share.
'********************************************************************

'*****       Connect to WMI and set security settings.         ******
    Set objservices = GetObject("WINMGMTS:" _
                              & "{impersonationLevel=impersonate,(Security)}" _
                              & "!\\myserver\ROOT\CIMV2")
'***   Substitute the name of the remote system for "myserver"  *****
'***** Get the Win32_SecurityDescriptor class and spawn a new instance ****
    Set objclass = objservices.Get("Win32_SecurityDescriptor")
    Set objSecDescriptor = objclass.SpawnInstance_()

'******   Prepare the security descriptor for the new share   ******
    objSecDescriptor.Properties_.Item("ControlFlags") = 4
    Set ACE1 = SetACE(2032127, _
                      3, _
                      0, _
                      SetTrustee("myserver", _
                                 "Rburns", _
                                 Array(1, 5, 0, 0, 0, 0, 0, 5, 21, _
                                       0, 0, 0, 160, 101, 207, 126, _
                                       120, 75, 155, 95, 231, 124, _
                                       135, 112, 119, 238, 0, 0)))

    Set ACE2 = SetACE(2032127, _
                           3, _
                           0, _
                           SetTrustee(Null, _
                                      "EVERYONE", _
                                      Array(1, 1, 0, 0, 0, 0, 0, 1, 0, _
                                            0, 0, 0)))

    objSecDescriptor.Properties_.Item("DACL") = Array(ACE1, ACE2)

'************************ Create the new share *********************

    Set objShare = objservices.Get("Win32_Share")
    Set objInParam = objShare.Methods_("Create").InParameters.SpawnInstance_()
    objInParam.Properties_.Item("Access") = objSecDescriptor
    objInParam.Properties_.Item("Description") = "New share created by WMI script"
    objInParam.Properties_.Item("Name") = "NewShare"
    objInParam.Properties_.Item("Path") = "C:\temp"
    objInParam.Properties_.Item("Type") = 0

    'objInParam.Properties_.item("MaximumAllowed") = 10     'optional - default is 'max allowed'
    'objInParam.Properties_.item("Password") = "Password"   'optional - default is no password

'************************ Execute the method **********************
    Set objOutParams = objShare.ExecMethod_("Create", objInParam)
    If objOutParams.ReturnValue = 0 Then
        wscript.echo "Share created successfully"
    Else
      If objOutParams.ReturnValue = 22 Then
        wscript.echo "Share may already exist"
      Else
        wscript.echo "Unable to create share, return value was : " _
            & objOutParams.ReturnValue
      End If
    End If

'************************* HELPER FUNCTIONS *********************
Function SetTrustee(strDomain, strName, SID)
     Set objTrustee = GetObject("Winmgmts:{impersonationlevel=impersonate}!root/cimv2:Win32_Trustee").SpawnInstance_
     objTrustee.Domain = strDomain
     objTrustee.Name = strName
     objTrustee.Properties_.Item("SID") = SID
     Set SetTrustee = objTrustee
End Function

Function SetACE(AccessMask, AceFlags, AceType, objTrustee)
    Set objACE = GetObject("Winmgmts:{impersonationlevel=impersonate}!root/cimv2:Win32_Ace").SpawnInstance_
     objACE.Properties_.Item("AccessMask") = AccessMask
     objACE.Properties_.Item("AceFlags") = AceFlags
     objACE.Properties_.Item("AceType") = AceType
     objACE.Properties_.Item("Trustee") = objTrustee
     Set SetACE = objACE
End Function
'******************************************************************


SNMP Providers

The Simple Network Management Protocol (SNMP) providers in the Windows Management Instrumentation (WMI) SDK allow client applications to access static and dynamic SNMP information through WMI.

There are two SNMP data providers that allow applications to access and modify the data relating to SNMP devices and two SNMP event providers that generate WMI events from SNMP traps and notifications. The data providers are class and instance providers.

The two event providers report the same types of events, but they report them in a different format. The event providers support separate sets of extrinsic event classes to represent the event information. Consumers choose a format by registering for a particular class of events. The two event providers are called the SNMP Encapsulated Event Provider (SEEP) and the SNMP Referent Event Provider (SREP).

This section contains the following topics:

  • Installing SNMP Providers
  • RFC MIB Files in the WMI SDK
  • Setting up the SNMP Providers
  • SNMP Event Providers
  • Logging Support

For detailed information about how the SNMP providers map device data to CIM classes, see one of the following topics:

  • Enumerating SNMP Class Definitions
  • Instantiating SNMP Class Definitions
  • Enumerating SNMP Class Instances
  • Instantiating SNMP Class Instances
  • Retrieving SNMP Class Instances


Installing SNMP Providers

SNMP providers are not installed by default with the other standard WMI providers. If your computer uses the Microsoft® Windows NT® version 4.0 operating system, you have the option to install the SNMP providers when installing the WMI core or from the Internet at http://msdn.microsoft.com/developer/sdk/wmisdk/download.asp.

If your computer uses the Microsoft® Windows® 2000 operating system, you can install the SNMP providers by running the SNMP provider setup program, Wbemsnnp.exe, from the \i386 directory of the Windows 2000 installation CD.

Note The SNMP providers require Windows NT 4.0 or Windows 2000. These providers do not run on Windows 95 or Windows 98.


RFC MIB Files in the WMI SDK

The Windows Management Instrumentation (WMI) SDK includes a set of SNMPv1 Request for Comments (RFC) Management Information Bases (MIBs) (including MIB-II definition, RFC 1213). These MIBs have been mapped to CIM schema definitions for use with the Simple Network Management Protocol (SNMP) providers. The mapped information is in two forms:

  • Static Managed Object Format (MOF) files

    These files are located in <WMI-directory>\snmp\mofs\snmpv1\rfcs, where <WMI-directory> is the directory in which WMI is installed. The classes defined in these files are compiled using the MOF compiler and placed in the CIM repository for static use. Before these classes can be used by a client, the MOF files must first be loaded into the specific WMI namespace where the SNMP providers reside.

  • SMIR MOF files

    These files are located in <WMI-directory>\snmp\smir_mofs\snmpv1\rfcs. They contain definitions of dynamic classes. To use these classes, the SMIR MOF files must first be loaded into the SNMP schema database and then into the specific WMI namespace where the SNMP providers reside. The SNMP schema database is called the SNMP Module Information Repository (SMIR).

Note that the MIB text files are also included with the SDK in the <WMISDK-directory>\snmp\mibs\snmpv1 directory. You can also use the SNMP MIB compiler to convert MIB files that are not included in the WMI SDK into MOF files. For more information, see SNMP Information Module Compiler.

For instructions on loading MOF and SMIR MOF files into WMI or the SMIR, see Loading Static MOF Files and SMIR MOF Files.


Setting Up the SNMP Providers

Each Simple Network Management Protocol (SNMP) device is represented within Windows Management Instrumentation (WMI) using a proxy namespace. Each proxy namespace contains a set of instance qualifiers that describe the transport characteristics associated with the device.

WMI automatically uses a Managed Object Format (MOF) file called Snmpreg.mof to create the \\.\root\snmp\localhost namespace. This namespace is set up to work with the local machine and contains the registration for each of the SNMP providers. Users wanting to create their own namespace can recompile the Snmpreg.mof file after specifying the name of the new namespace for the AgentAddress qualifier and the Name property of the __Namespace instance. Remember that the AgentAddress qualifier can be overridden at any time using a context object with an "AgentAddress" property that has the address or computer name of the device to which a connection should be made.

The following sample is an excerpt from the Snmpreg.mof file. The name of the namespace is set to "localhost" as is the value of the AgentAddress qualifier:

[AgentAddress ( "localhost" )]
instance of __Namespace
{
  Name = "localhost" ;
} ;

To allow the SNMP providers to work with an alternate namespace, change the Snmpreg.mof file as follows:

[AgentAddress ( "MySNMPDevice" )]
instance of __Namespace
{
  Name = "MySNMPDevice" ;
} ;

These steps summarize the tasks necessary to set the SNMP providers up to work in a particular namespace:

  1. Create a namespace for each SNMP MIB view associated with an SNMP device of interest.
  2. Register the appropriate providers with WMI for the newly created namespace.
  3. Load the MOF files Snmpreg.mof and Snmpsmir.mof into the namespace. These files are located in the WMI installation directory. Use the following commands:
    mofcomp snmpreg.mof
mofcomp snmpsmir.mof

    Applications monitoring an SNMP device that provides device-specific traps must update the SMIR with definitions of the traps. Static trap classes are not supported. Applications can use one of the following two techniques to dynamically update the SMIR:

  • Compile a MIB file into the SMIR. The MIB file should contain the SNMPv1 trap or SNMPv2C notification definitions. If it does not contain the definitions, contact the manufacturer of the device. The SNMP event providers treat device-specific traps that are lacking a definition as unknown trap types by generating generic WMI SNMP events.
  • Load a MOF file that contains trap definitions into the SMIR.

For information on compiling a MIB file into the SMIR, see SNMP Information Module Compiler.


Loading Static MOF Files and SMIR MOF Files

A static MOF file does not contain the name of its associated namespace, which must be specified when loading the file into WMI. A SMIR MOF file, however, does contain the name of its associated namespace. The following two procedures explain how to load MOF files.

To load a static MOF file into a namespace

  1. Create the namespace if you have not already done so. For instructions, see Creating an SNMP Namespace.
  2. Run the MOF compiler on the MOF file, specifying the namespace created in step 1. Use the following command:

    mofcomp -n:<object-path> <MOF-file>

    The object-path can be either relative to the current namespace or fully qualified (for example, \\Myserver\Root\Mynamespace).

To load a SMIR MOF file into the SMIR

Run the MOF compiler on the SMIR MOF file using the following command:

mofcomp <SMIR-MOF-file>


Creating an SNMP Namespace

An SNMP namespace defines a view of a network device. SNMP namespaces can be created through the WMI Common Information Model (CIM) Studio application, by compiling a MOF file, or programmatically with the WMI API. Because an SNMP namespace is represented by the __Namespace system class, you create a new namespace by creating an instance of this class. Associated with the instance must be at least one descriptor known as a qualifier. Qualifiers contain implementation-specific context information, transport properties that define how the SNMP providers access an SNMP agent.

The following list describes the qualifiers for the SNMP providers. Note that in the current release, only one of these qualifiers, AgentAddress, is mandatory.

AgentAddress (CIM_STRING, mandatory)
Transport address associated with the SNMP agent, such as an IP address or DNS name. AgentAddress should be set to a valid unicast host address or a domain host name that can be resolved through the operating system's domain-name resolution process. There is no default value.
AgentTransport (CIM_STRING, optional)
Transport protocol used to communicate with the SNMP agent. Currently the only valid values are Internet Protocol (IP) and Internet Packet Exchange (IPX). The default value is IP.
AgentReadCommunityName (CIM_STRING, optional)
Variable-length octet string that is used by the SNMP agent to authenticate an SNMP Protocol Data Unit (PDU) during a read operation (SNMP GET/GET NEXT requests). The community name must be mapped to a Unicode string and is limited to alphanumeric characters. The default value is public.
AgentWriteCommunityName (CIM_STRING, optional)
Variable-length octet string that is used by the SNMP agent to authenticate an SNMP Protocol Data Unit (PDU) during a read operation (SNMP SET request). The community name must be mapped to a Unicode string and is limited to alphanumeric characters. The default value is public.
AgentRetryCount (CIM_SINT32, optional)
Number of times a single SNMP request can be retried when there is no response from the SNMP agent before the request is deemed to have failed. AgentRetryCount must be set to an integer between 0 and 2^32-1. To generate the signed integer representation, perform the two's-complement operation. The default value is 1.
AgentRetryTimeout (CIM_SINT32, optional)
Time in milliseconds before the SNMP Protocol Data Unit (PDU) is considered to have been dropped. This is the number of milliseconds to wait for a response to an SNMP request sent to the SNMP agent. AgentRetryTimeout must be set to an integer between 0 and 2^32-1. To generate the signed integer representation, perform the two's-complement operation. The default value is 500.
AgentVarBindsPerPdu (CIM_SINT32, optional)
Maximum number of variable bindings contained within a single SNMP PDU. Every SNMP request sent to the SNMP agent contains one or more SNMP variables. This parameter specifies the largest number of variables that can be included in a single request. AgentVarBindsPerPdu can be set to 0 to cause the implementation to determine the optimal variable bindings or to an integer between 1 and 2^32-1. To generate the signed integer representation, perform the two's-complement operation. Note that while increasing this value can improve performance, some agents and networks cannot deal with the resulting request. The default value is 10.
AgentFlowControlWindowSize (CIM_SINT32, optional)
Maximum number of concurrently outstanding SNMP requests that can be sent to this agent while a response has not yet been received. A SNMP request is considered outstanding until a PDU response has been received or it has timed out. A large window size generally improves performance, but some agents might not work well under a heavy load. AgentFlowControlWindowSize can be set to 0 to indicate an infinite window size or to an integer between 1 and 2^32-1. To generate the signed integer representation, perform the two's-complement operation. The default value is 10.
AgentSNMPVersion (CIM_STRING, optional)
Version of the SNMP protocol to be used when communicating with the SNMP agent. Currently, the only valid values are 1 (for SNMPv1) and 2C (for SNMPv2C). The default value is 1.

The following example defines a namespace called snmp that sets most of the qualifiers associated with an SNMP namespace. The SNMP agent is proxied in the \\.\Root\Snmp namespace.

 // Load classes and instances into <\\.\root> namespace

#pragma namespace("\\\\.\\root")

[ AgentAddress( "localhost" ), AgentReadCommunityName( "public"),
  AgentWriteCommunityName( "private"), AgentRetryCount( 1 ),
  AgentRetryTimeout( 500 ), AgentVarBindsPerPdu( 10 ),
  AgentFlowControlWindowSize ( 3 ) ]

  instance of __Namespace
  {
      Name = "snmp" ;
  };


Registering to Receive SNMP Events

Consumers that want to register to receive SNMP events must create an instance of the __EventFilter system class, setting the Query property to a query that requests data from an event class supported by one of the SNMP event providers. Typically, consumers register for all events that are described by either the SnmpNotification class and its subclasses or the SnmpExtendedNotification class and its subclasses. Because these classes are the base classes for all events supported by the SNMP providers, consumers specifying them in their event filter will receive all types of SNMP events. However, consumers can also register to receive particular SNMP events by specifying a subclass of SnmpNotification or SnmpExtendedNotification.

The following event filter instances show how to register for all events from either the SNMP Encapsulated Event Provider (SEEP) or the SNMP Referent Event Provider (SREP):

  // Register for SNMP Encapsulated Event Provider (SEEP) events
  Instance of __EventFilter
  {
    Name = "{7ca44681-045f-11d1-ae97-00c04fb68820}";
    Query =
           "select * from SnmpNotification";
    QueryLanguage = "WQL";
  }

  // Receive for SNMP Referent Event Provider (SREP) events
  Instance of __EventFilter
  {
    Name = "{7ca44681-045f-11d1-ae97-00c04fb68820}";
    Query =
           "select * from SnmpExtendedNotification";
    QueryLanguage = "WQL";
  }

To register to receive notifications of link-up events only from the SEEP, a consumer could create this instance of __EventFilter:

  Instance of __EventFilter
  {
    Name = "{7ca44681-045f-11d1-ae97-00c04fb68820}";
    Query =
           "select * from SnmpLinkUpNotification"
    QueryLanguage = "WQL";
  }

Consumers intent on using the event information they receive to update values in the SNMP devices that they monitor need to register for the SnmpExtendedNotification events. The information from the SnmpNotification events is not reusable.

For more information about the SNMP event class hierarchy, see one of the following topics:

Generic SNMP Events

Enterprise Specific SNMP Events

Enterprise Non-Specific SNMP Events

For more information about event filters, see Creating an Event Filter.


Registering the SNMP Providers

Registration provides WMI with information about a provider's capabilities and its location. Because the SNMP providers are not automatically registered with WMI when WMI is installed, client applications must complete the registration process if they want to use one or more of the SNMP providers.

All of the SNMP providers must create an instance of the __Win32Provider system class. Depending on the type of provider, one of the following instances must also be created.

Provider type | Instance to be created
Class provider | __ClassProviderRegistration
Instance provider | __InstanceProviderRegistration
Event provider | __EventProviderRegistration

For general information about registering WMI providers, see Registering a Provider.


Registering the SNMP Instance Provider

The SNMP instance provider registers against a namespace and returns instances associated with a class definition that conforms to the mapping described in Mapping SNMP to the CIM Schema. A namespace registered with only the SNMP instance provider should contain static classes that also conform to this mapping.

The SNMP instance provider is registered with an instance of the __Win32Provider system class and an instance of the __InstanceProviderRegistration class. To register the SNMP instance provider, submit a file to the MOF compiler that specifies a target namespace and contains the following instances:

#pragma namespace("\\\\.\\root\\snmp")

instance of __Win32Provider as $PInst
{
    Name = "MS_SNMP_INSTANCE_PROVIDER";
    Clsid = "{1F517A23-B29C-11cf-8C8D-00AA00A4086C}";
};

instance of __InstanceProviderRegistration
{
    Provider = $PInst;
    SupportsGet = TRUE;
    SupportsPut = TRUE;
    SupportsDelete = FALSE;
    SupportsEnumeration = TRUE;
    QuerySupportLevels = { "WQL:UnarySelect" } ;
};

The __Win32Provider instance specifies the name of the SNMP instance provider and its class identifier (CLSID). The CLSID allows WMI to locate the provider when it is needed.

The __InstanceProviderRegistration instance describes the features of the SNMP instance provider. The instance provider supports data retrieval, enumeration, and modification. The instance provider also supports queries that use the basic SELECT statement syntax.

The SNMP instance provider provides support for the following methods of the IWbemServices interface:

  • GetObjectAsync
  • ExecQueryAsync
  • PutInstanceAsync

Any WMI client can call these methods to interact with the SNMP agent.

The WMI SDK includes a number of static MOF files that can be loaded into the proxy namespace. For more information, see RFC MIB Files in the WMI SDK.

For information about registering instance providers in general, see Registering Class and Instance Providers.


Registering the SNMP Class Provider

The SNMP class provider registers against a namespace and returns classes that conform to the mapping described in Mapping SNMP to the CIM Schema.

The SNMP class provider is registered with an instance of the __Win32Provider class and an instance of the __ClassProviderRegistration class. To register the SNMP class provider, submit a file to the MOF compiler that specifies a target namespace and contains the following instances:

#pragma namespace("\\\\.\\root\\snmp")

instance of __Win32Provider as $PClass
{
    Name = "MS_SNMP_CLASS_PROVIDER";
    Clsid = "{70426720-F78F-11cf-9151-00AA00A4086C}";
};

instance of __ClassProviderRegistration
{
    Provider = $PClass;
    SupportsGet = TRUE;
    SupportsPut = FALSE;
    SupportsDelete = FALSE;
    SupportsEnumeration = TRUE;
    QuerySupportLevels = NULL ;
    ResultSetQueries = { "Select * From meta_class Where __this isa SnmpMacro" } ;
} ;

The __Win32Provider instance specifies the name of the SNMP class provider and its CLSID. The CLSID allows WMI to locate the provider when it is needed.

The __ClassProviderRegistration instance describes the features of the SNMP class provider. The class provider supports the retrieval of class definitions and class enumeration but does not support class modification, class deletion, or query processing.

The SNMP class provider provides support for the following methods of the IWbemServices interface:

  • GetObjectAsync
  • CreateClassEnumAsync
  • PutInstanceAsync

Any WMI client can call these methods to interact with the SNMP agent.

The SNMP class provider operates in two modes: correlated and non-correlated. In correlated mode, the provider checks the class definitions in \\.\root\snmp\smir and returns only those classes that are supported by the SNMP agent. In non-correlated mode, the provider returns all classes in \\.\root\snmp\smir. The WMI SDK includes a number of SMIR MOF files that can be loaded into the \\.\root\snmp\smir namespace. See RFC MIB Files in the WMI SDK for more information.

When a namespace is registered with both the SNMP instance provider and the SNMP class provider, the namespace does not need to contain static classes. In this case, the SNMP class provider presents a set of dynamic classes to WMI. These class definitions must conform to the mapping described in Mapping SNMP to the CIM Schema.

For information about registering class providers in general, see Registering Class and Instance Providers.


Sample Registration for the SNMP Instance and Class Providers

The following MOF file registers the SNMP instance and class providers in the namespace Root\Snmp. This allows a WMI client to enumerate SNMP class and instance definitions found in this namespace.

To use this sample, copy the text to a file with a .MOF extension and compile it using the MOF compiler. Then load a MOF file from the \Snmp\Smir_mofs\Snmpv1\Sfcs directory. The MOF file you choose depends on the type of agent you want to proxy; Rfc1213.mof is recommended as a starting point.

#pragma namespace("\\\\.\\root")

[AgentAddress ( "localhost" )]
instance of __Namespace
{
    Name = "snmp" ;
} ;

#pragma namespace("\\\\.\\root\\snmp")

instance of __Win32Provider as $PClass
{
    Name = "MS_SNMP_CLASS_PROVIDER";
    Clsid = "{70426720-F78F-11cf-9151-00AA00A4086C}";
};

instance of __ClassProviderRegistration
{
    Provider = $PClass;
    SupportsGet = TRUE;
    SupportsPut = FALSE;
    SupportsDelete = FALSE;
    SupportsEnumeration = TRUE;

    QuerySupportLevels = NULL ;

    ResultSetQueries = { "Select * From meta_class Where __this isa SnmpMacro" } ;
} ;

instance of __Win32Provider as $PInst
{
    Name = "MS_SNMP_INSTANCE_PROVIDER";
    Clsid = "{1F517A23-B29C-11cf-8C8D-00AA00A4086C}";
};

instance of __InstanceProviderRegistration
{
    Provider = $PInst;
    SupportsGet = TRUE;
    SupportsPut = TRUE;
    SupportsDelete = TRUE;
    SupportsEnumeration = TRUE;

    QuerySupportLevels = { "WQL:UnarySelect" } ;
};


Registering the SNMP Event Providers

The two SNMP event providers are each registered with an instance of the __Win32Provider class and an instance of the __EventProviderRegistration class. Applications that do not receive events from SNMP devices do not need to register the SNMP event providers.

To register the SEEP, submit a file to the MOF compiler that specifies a target namespace and contains the following instances:

#pragma namespace("\\\\.\\root\\default\\SMIR")

instance of __Win32Provider as $EncapEventProv
{
    Name = "MS_SNMP_ENCAPSULATED_EVENT_PROVIDER";
    Clsid = "{19C813AC-FEE7-11D0-AB22-00C04FD9159E}";
};

instance of __EventProviderRegistration
{
    Provider = $EncapEventProv;
    EventQueryList = {"select * from SnmpNotification"};
};

The __Win32Provider instance specifies the name of this event provider and its class identifier (CLSID). The CLSID allows WMI to locate the provider when it is needed.

The __EventProviderRegistration instance describes the events supported by the SEEP. The SEEP supports all events that are described by the SnmpNotification class and all of its subclasses. For more information about the SnmpNotification class and its subclasses, see one of the following topics:

Generic SNMP Events

Enterprise Specific SNMP Events

Enterprise Non-Specific SNMP Events

To register the SREP, create a MOF file that contains these instances and submit it to the MOF compiler:

instance of __Win32Provider as $EventProv
{
    Name = "MS_SNMP_REFERENT_EVENT_PROVIDER";
    ClsId = "{9D5BED16-0765-11d1-AB2C-00C04FD9159E}";
};

instance of __EventProviderRegistration
{
    Provider = $EventProv;
    EventQueryList = {"select * from SnmpExtendedNotification"} ;
};

The __Win32Provider instance specifies the name of this event provider and its CLSID. The __EventProviderRegistration instance describes the events supported by the SREP. The SREP supports all events that are described by the SnmpExtendedNotification class and all of its subclasses. For more information about the SnmpNotification class and its subclasses, see one of the following topics:

Generic SNMP Events

Enterprise Specific SNMP Events

Enterprise Non-Specific SNMP Events

For more information about registering event providers, see Registering an Event Provider.


SNMP Event Providers

Windows Management Instrumentation (WMI) includes two Simple Network Management Protocol (SNMP) event providers:

  • SNMP Encapsulated Event Provider (SEEP)
  • SNMP Referent Event Provider (SREP)

Both event providers receive SNMP event packets from the WINSNMP stack and translate the information included in these packets into WMI events. Regardless of whether the SNMP event was an SNMPv1 trap or an SNMPv2C notification, the stack reports it as an SNMP v2 notification. Therefore, the event providers process all SNMP events as SNMP v2 notifications.

To describe the SNMP events to WMI consumers, each event provider supports a hierarchy of classes that derives from the __ExtrinsicEvent system class. The SNMPNotification class is the parent class for the SEEP hierarchy; the SNMPExtendedNotification class is the parent class for the SREP hierarchy. The properties of these classes, which are described in the following table, are read-only and contain information relevant to all SNMP events:

Property | Description
TimeStamp | Time in hundredths of a second since the network management portion of the agent was last re-initialized.
Identification | Authoritative identification of this notification. Maps directly to the SnmpTrapOID variable binding.
AgentAddress | Network address of the entity that created the notification. This is the actual address of the device.
AgentTransportAddress | Network address of the entity that sent the notification. This is the address of the last entity that forwarded the notification.
AgentTransportProtocol | Transport protocol used by the sending entity.
Community | Security context used to send the notification.

The SNMP event providers support three types of SNMP v1 traps and SNMP v2 notifications: generic, enterprise specific, and enterprise non-specific. The generic traps and notifications correspond to named events such as link up and cold start. Generic traps and notifications are represented by classes such as SnmpLinkUpNotification and SnmpWarmStartExtendedNotification that contain the name of the trap in the class name. These classes are subclasses of subclasses of SNMPNotification and SNMPExtendedNotification. For more information about the classes used to represent generic traps and notifications, see Generic SNMP Events.

Enterprise specific traps and notifications correspond to events that are represented by a WMI class that is not a subclass of SNMPNotification and SNMPExtendedNotification. To support enterprise specific traps and notifications, a consumer must define classes by compiling MIB definitions using the SNMP MIB compiler. For more information about enterprise specific traps and notifications, see Enterprise Specific SNMP Events.

Enterprise non-specific traps and notifications do not correspond to any of the generic event types or enterprise-specific event types. Enterprise non-specific traps and notifications have not had their MIB definitions compiled into the SMIR. Enterprise non-specific traps and notifications are represented by the SnmpV1Notification, SnmpV2Notification, SnmpV1ExtendedNotification, and SnmpV2ExtendedNotification subclasses of SNMPNotification and SNMPExtendedNotification. For more information about enterprise non-specific traps and notifications, see Enterprise Non-Specific SNMP Events.


Generic SNMP Events

The SEEP and SREP support all types of generic SNMP v1 traps and SNMP v2 notifications. Generic SNMP events are represented by subclasses of the SNMPNotification and SNMPExtendedNotification classes. Both SNMP event providers support the following types of generic SNMP events:

  • Authentication failure
  • Exterior Gateway Protocol (EGP) neighbor loss
  • Cold start
  • Warm start
  • Link up
  • Link down

Each event type is represented by one SEEP class and one SREP class. The SEEP classes derive from SnmpNotification; the SREP classes derive from SnmpExtendedNotification. The event providers require different classes because they use different mechanisms in the presentation of the SNMP event data.

The SEEP converts the SNMP event data directly to WMI class properties whereas the SREP does not. The SREP adds a level of indirection to the interpretation required to use the WMI properties. The properties of the SREP SnmpExtendedNotification subclasses are instances of SNMP classes; the properties of the SEEP SnmpNotification subclasses are integers and strings.

For example, the SnmpLinkUpNotification and SnmpLinkUpExtendedNotification classes describe the link-up event. Both classes include the ifIndex, ifAdminStatus, and ifOperStatus properties, but they have very different types. The properties in the SnmpLinkUpNotification class are of type SINT32 and STRING. The properties in the SnmpLinkUpExtendedNotification class are the embedded object type IETF_SNMP_RFC1213_MIB_ifTable.

The generic events with their corresponding event classes are:

  • Authentication failure: SnmpAuthenticationFailureNotification and SnmpAuthenticationFailureExtendedNotification classes
  • EGP neighbor loss: SnmpEGPNeighborLossNotification and SnmpEGPNeighborLossExtendedNotification classes
  • Cold start: SnmpColdStartNotification and SnmpColdStartExtendedNotification classes
  • Warm start: SnmpWarmStartNotification and SnmpWarmStartExtendedNotification classes
  • Link up: SnmpLinkUpNotification and SnmpLinkUpExtendedNotification classes
  • Link down: SnmpLinkDownNotification and SnmpLinkDownExtendedNotification classes


Enterprise Specific SNMP Events

The SEEP and SREP support any enterprise specific traps and notifications that have been compiled into the SMIR. To receive enterprise specific events, consumers must have the MIB definitions from the device responsible for generating the corresponding traps or notifications and compile the definitions using the SNMP MIB compiler.

If the SNMP event providers receive a specific trap or notification for which there is no class, they generate an enterprise non-specific event using one of the SnmpV1Notification, SnmpV2Notification, SnmpV1ExtendedNotification, or SnmpV2ExtendedNotification classes.

When the MIB definitions for an enterprise-specific event are compiled, the command-line options provide information about the type of classes to be generated by the compiler. Specifically, the options can instruct the compiler to:

  • Create only SnmpNotification subclasses from the definitions.
  • Create only SnmpExtendedNotification subclasses from the definitions.
  • Create both SnmpNotification and SnmpExtendedNotification subclasses from the definitions.


Enterprise Non-Specific SNMP Events

When an SNMP event provider cannot map an SNMP v1 trap or SNMP v2 notification to either one of the subclasses of SnmpNotification or SnmpExtendedNotification or a class that represents an enterprise specific event, it produces an enterprise non-specific event. Enterprise non-specific traps and notifications are represented by instances of the SNMPV1Notification or SNMPV2Notification classes when handled by the SEEP and by instances of the SNMPV1ExtendedNotification or SNMPV2ExtendedNotification classes when handled by the SREP.

All four of the enterprise non-specific classes derive from either SnmpNotification or SnmpExtendedNotification and have the same format. They have one property: VarBindList. This property is an array of instances of the SnmpVarBind class, a base class supported by the SNMP event providers to represent an instance of an SNMP variable binding. The SnmpVarBind class contains the following properties:

Property | Description
Encoding | A string that indicates the Abstract Syntax Notation One (ASN.1) type of the variable in the Value property.
ObjectIdentifier | A string that identifies the variable in the Value property.
Value | Raw data in octets.

In the SnmpV1Notification and SnmpV2Notification classes, the variable binding order from the SNMP event has been preserved with the exception of the first two variable bindings, TimeStamp and SnmpTrapOID. These bindings have been removed and are stored in the TimeStamp and Identification properties of the SnmpNotification or SnmpExtendedNotification parent class.


Logging Support

The Simple Network Management Protocol (SNMP) providers support writing to log files and to the debugger. A number of registry keys and values define the level and type of logging currently being generated.

The following registry key contains the logging value that indicates whether or not information can be written to the debugger:

HKEY_LOCAL_MACHINE\SOFTWARE\MICROSOFT\WBEM\PROVIDERS\LOGGING

The logging value is set either to 0 to disable debugging output or 1 to enable it. Logging is a REG_DWORD value.

The following registry key holds all of the logging information specific to the SNMP providers:

HKEY_LOCAL_MACHINE\SOFTWARE\MICROSOFT\WBEM\PROVIDERS\LOGGING\WBEMSNMP

The following values are associated with this key:

Value | Type | Description
Type | REG_SZ | Takes one of the following values: 'File' Default. Sends debugging output to a file. 'Debugger' Sends debugging output to the debugger.
MaxFileSize | REG_DWORD | Takes integer values from 1024 to 2^32-1. The value is the maximum allowed size in bytes for the log file. If a value less than 1024 is entered, a value of 1024 is used by the logging mechanism. A minimum size of 8 KB is recommended for this value. When the file reaches the size specified by MaxFileSize, the filename is prepended with a '~' character and a new file is created. Therefore, the maximum diskspace required for logging is twice this value.
File | REG_SZ | Defines the name of the file to which the debugging output is sent when the logging Type is set to 'File'. The default value is '<WBEMLOGS>\wbemsnmp.log.' If the <WBEMLOGS> directory cannot be determined from the WMI registry section, the value will default to 'c:\wbemsnmp.log'. If a share is used, such as \\machine\share\wbemsnmp.log or M:\wbemsnmp.log where M: is \\machine\share, the local SYSTEM account on which WMI runs must have READ\WRITE access rights to the \\machine\share.
Level | REG_DWORD | Takes integer values from 0 through 2^32-1. The value is a logical mask consisting of 32 bits. The following bit masks are combined to define the type of debugging output generated: Bit/Description 0 SNMP class provider IWbemServices method invocations 1 SNMP class provider implementation 2 SNMP instance provider IWbemServices method invocations 3 SNMP instance provider implementation 4 SNMP class library 5 SNMP SMIR 6 SNMP correlator 7 SNMP type mapping code 8 SNMP threading code 9 SNMP event provider interfaces and implementation Set the Level to (2^0 + 2^8=) 257 for logon operations, operations involving calling the SNMP class provider's IWbemServices methods, and operations using SNMP threading code.


SNMP Information Module Compiler

The Simple Network Management Protocol (SNMP) information module compiler compiles SNMP management information, defined in a Management Information Base (MIB), into the equivalent Common Information Model (CIM) schema definitions that can be used with SNMP providers. This CIM schema can exist as output in a Managed Object Format (MOF) file. The CIM schema also can be loaded directly into an SNMP schema database known as the SNMP Module Information Repository (SMIR). The SNMP dynamic class provider uses the SMIR to retrieve and create instances of class definitions automatically.

The SNMP compiler runs as a single executable file in the command-line mode. It accepts one SNMP information module as input, and it accepts any additional modules that might be required to resolve external references. An SNMP information module is a collection of management information that typically includes a combination of the following:

  • MIB modules (collections of related MIB objects).
  • AGENT-CAPABILITIES statements that describe an agent's minimal level of compliance to the set of MIB modules it supports.
  • MODULE-COMPLIANCE statements that describe the agent's capabilities with respect to object definitions.

SNMP information modules are written in a subset of the Abstract Syntax Notation One (ASN.1) language called the Structure of Management Information (SMI). The SNMP compiler loads data from an SNMP information module into the SMIR. Otherwise, the compiler creates an intermediate MOF file either in a format suitable for loading into the SMIR at a later date or in a format suitable for loading as static classes into a Windows Management Instrumentation (WMI) namespace at a later date. A SMIR MOF file contains the name of its associated namespace. A static MOF file does not contain this information. With a static MOF file, you must specify the namespace when you load the MOF file.

The compiler performs the following functions:

  • Performs checking operations on the information module. For example, it checks the local syntax and it checks external references against information in the subsidiary modules.
  • Removes all previously-loaded data from the SMIR, or removes data loaded from one information module.
  • Returns the ASN.1 module name of a specified file or returns the ASN.1 module names of all imported modules in a specified file.
  • Returns the ASN.1 module names of all SNMP information modules currently loaded in the SMIR.
  • Performs automatic resolution of imported modules rather than requiring users to manually specify the required modules.
  • Performs a silent-loading mode of operation that does not generate any output, but can be used to load data into the SMIR during an installation operation.


MIB Lookup Table

When parsing an SNMP MIB file, the compiler sometimes encounters definitions or declarations that are external to the file being processed. Definitions and declarations are specified in modules that are referenced by the IMPORTS statement in the file being processed. The compiler must access these modules and retrieve the definitions and declarations in order to complete the file processing.

The compiler maintains a lookup table in the registry that maps ASN.1 module names to MIB file locations. This lookup table allows you to quickly compile an information module without manually locating and specifying dependent files on the command line. When run in auto-resolution mode, the compiler uses the lookup table to locate the MIB files referenced by the IMPORTS statement. The compiler then processes these MIB files and any other modules referenced by the MIB files to obtain a consistent set of definitions or declarations for use in processing the original SNMP MIB file.


Registry Configuration

All compiler configuration information stored in the registry is located under the root key:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WBEM\PROVIDERS\SNMP\COMPILER

The following values are associated with this key:

Value name | Data type | Description | Default value at installation
File Path | REG_MULTI_SZ | An ordered list of strings, each specifying a directory in which the compiler searches for MIB files. The compiler searches from left to right. The directories are always stored as fully qualified path names. Relative path names in the registry are ignored. |
File Suffixes | REG_MULTI_SZ | An ordered list of file suffixes that the compiler uses to determine whether a file contains a MIB module. The ordering is significant when there are two files for the same MIB module in a directory and each of these files has a different extension. In this case, the file whose extension occurs first in this list is considered to be the file that corresponds to the MIB module. | mib

The following example shows sample registry entries for the SNMP compiler configuration settings described above:

There is a further subkey called MIB under the root key defined above. This subkey stores the MIB lookup table. For each MIB in the lookup table, a value is created and placed under this subkey. The name of the value is the ASN.1 module name of the MIB and the actual value is as defined below:

Value name | Data type | Description
MIB Module Name | REG_SZ | The full path name of the file containing the MIB module.

The following example shows sample registry entries for a MIB lookup table:


Running the SNMP Compiler

The command-line syntax for running the compiler is as follows:

smi2smir [<DiagnosticArgs>] [<VersionArgs>] <CommandArgs> <MIB file> [<Import Files>]

smi2smir [<DiagnosticArgs>] <RegistryArgs> [<Directory>]

smi2smir <ModuleInfoArgs> <MIB file>

smi2smir <HelpArgs>

The compiler command accepts the following arguments:

DiagnosticArgs | Meaning
/m <diagnostic-level> | Specifies the kind of diagnostics to display: 0 (silent), 1 (fatal), 2 (fatal and warning), or 3 (fatal, warning, and information messages). The default is 2.
/c <count> | Specifies the maximum number of fatal and warning messages to display; count must be a positive decimal integer. If /c is not specified, there is no limit to the number of errors that can be reported.
VersionArgs |
/v1 | Specifies strict conformance to the SNMPv1 SMI. The compiler reports an error if it detects non-SNMPv1 statements.
/v2c | Specifies strict conformance to the SNMPv2 SMI. The compiler reports an error if it detects non-SNMPv2 statements.
CommandArgs |
/d | Deletes the specified module from the SMIR.
/p | Deletes all modules in the SMIR.
/l | Lists all modules in the SMIR.
/lc | Performs a local syntax check on the module.
/ec [<CommandModifier>] | Performs local and external checks on the module.
/a [<CommandModifier>] | Performs local and external checks and loads the module into the SMIR.
/sa [<CommandModifier>] | Same as /a, but works silently.
/g [<CommandModifier>] | Generates a SMIR MOF file that can be loaded later into Windows Management Instrumentation (WMI) (using the MOF compiler). Used by the SNMP class provider to dynamically provide classes to one or more namespaces. Use this option when you do not know which MIBs are supported by the SNMP devices being managed. The SNMP class provider checks the device at runtime for the presence of this MIB and supplies the classes dynamically to the namespace. See Loading Static MOF Files and SMIR MOF Files for information on loading the MOF file into WMI.
/gc [<CommandModifier>] | Generates a static MOF file that can be loaded later into WMI as static classes for a particular namespace. Use this option when you know which MIBs are supported by the SNMP devices being managed. Do not use with /ext /o. See Loading Static MOF Files and SMIR MOF Files for information on loading the MOF file into WMI.
CommandModifiers |
/i <directory> | Specifies a directory to be searched for dependent MIB modules. Use with /a, /ec, /g, /gc, and /sa. The /i option can appear multiple times on the command line; directories are searched in the order specified on the command line.
/ch | Generates context information, such as the date, time, host, or user, in the MOF file header. Use with /g and /gc.
/t | Also generates SnmpNotification classes. Use with /a, /g, and /sa.
/ext | Also generates SnmpExtendedNotification classes. Use with /a, /g, and /sa.
/t /o | Generates only SnmpNotification classes. Use with /a, /g, and /sa.
/ext /o | Generates only SnmpExtendedNotification classes. Use with /a, /g, and /sa.
/s | Does not map the text of the DESCRIPTION clause. Use with /a, /g, /gc, and /sa. Use this option when you want to minimize storage requirements.
/auto | Rebuilds the MIB lookup table before completing <CommandArg> switch. Use with /a, /ec, /g, and /gc.
RegistryArgs |
/pa | Adds the specified directory to the registry. The default is current directory.
/pd | Deletes the specified directory from the registry. The default is current directory.
/pl | Lists the MIB lookup directories in the registry.
/r | Rebuilds the entire MIB lookup table.
ModuleInfoArgs |
/n | Returns the ASN.1 name of the specified module.
/ni | Returns the ASN.1 names of all import modules referred to by the input module.
HelpArgs |
/h | Displays help on the SNMP compiler syntax.
/? | Displays help on the SNMP compiler syntax.

For details on the error messages generated by the compiler, see SNMP Compiler Error Messages.


Loading MOF Files

The SNMP compiler can generate MOF files in a format suitable for loading into the SMIR, or in a format suitable for loading such as static classes into a CIM namespace. A SMIR MOF file contains the name of its associated namespace. A static MOF file does not contain this information, and the namespace must be specified when loading the MOF file.

For instructions on loading MOF and SMIR MOF files, see Loading Static MOF Files and SMIR MOF Files.


Directory Services Provider

[This is preliminary documentation and subject to change.]

The Directory Services (DS) Provider is a built-in provider that comes with the Windows Management Instrumentation (WMI) SDK. The DS Provider provides access to the Microsoft® Windows® 2000 Active Directory only. Understanding the DS Provider requires some familiarity with the Microsoft® Active Directory™.

The DS Provider topics are covered in the following sections:

  • About the DS Provider
  • Using the DS Provider
  • DS Provider Reference

Note The Directory Services Provider requires Windows NT version 4.0, Windows 2000, or Windows 98. This provider does not run on Windows 95.


About the DS Provider

[This is preliminary documentation and subject to change.]

The DS Provider makes the classes and objects in the Active Directory available to WMI management applications.

This section contains information on:

  • Active Directory
  • DS Provider Architecture
  • How the Active Directory is Mapped to WMI
  • DS Provider Parts
  • Registration of DS Provider Parts


Active Directory

[This is preliminary documentation and subject to change.]

The Active Directory is the main store of information on Windows 2000. The Active Directory catalogues the resources of an entire computer network domain. The directory service is the part of the Active Directory that is used for organizing, managing, and locating interesting objects in a computer network domain. Objects of interest include users, security policies, printers, distributed components, and other resources. The name Active Directory refers to the directory service and the directory itself.

Active Directory benefits users, administrators, and vendors in the following ways:

  • Users do not need several logons for the domains they access. A single logon and password authenticates users to all systems, files, printers, applications, databases, and other services in the Windows 2000 organization.
  • Administrators can manage network-wide resources (residing anywhere in the world) from any network location.
  • Vendors can design applications that can locate and interact with users, computers, or resources across a computer network organization.

Using the COM API for WMI, you can use the DS provider to create WMI-enabled applications that can access the wealth of information contained in the Active Directory. You can use the DS provider to create and delete instances, modify properties of instances, and enumerate classes. You cannot use the DS Provider to access events or methods.

For more information, see:

  • WMI and ADSI
  • Accessing the Active Directory with WMI


WMI and ADSI

[This is preliminary documentation and subject to change.]

Objects contained in any directory (not just the Active Directory) are only accessible with the Active Directory Services Interfaces (ADSI) API. You can use these public access functions to programmatically:

  • Retrieve classes and instances
  • Enumerate (generate a listing of) classes and instances
  • Create new instances
  • Modify existing instances
  • Query the Active Directory to generate views (sorted filtered listings) of the Active Directory's contents

Management applications access the Active Directory indirectly. The chain of events looks like this:

  1. The management application interfaces with the WMI API and makes a request for Active Directory information.
  2. The WMI API, by granting public access to the CIM Object Manager, passes the request along to WMI.
  3. The CIM Object Manager interprets the request and translates it into a set of DS Provider calls.
  4. The DS Provider interfaces with the ADSI API, and translates each operation into a set of ADSI calls.
  5. The ADSI API, by granting public access to the Active Directory, retrieves the information from the Active Directory.

For information on ADSI, see "Active Directory Services Interface (ADSI): Frequently Asked Questions" in the MSDN library.


Accessing the Active Directory with WMI

[This is preliminary documentation and subject to change.]

The Active Directory is made accessible through WMI by creating a set of references to every class and object contained in the Active Directory.

Since the Lightweight Directory Access Protocol manipulates the Active Directory, the name LDAP represents the Active Directory in the DS provider schema.

In the WMI schema, directory representations, such as the one in the following diagram, are presented as namespaces beneath the Root namespace. The Root namespace is beneath another namespace called directory. Logically, the relationship looks like this:

Generally, you can access the Active Directory belonging to the Windows 2000 domain you usually log on to. You can also use WMI to get information about any Active Directory by connecting remotely a computer in another domain. When connecting remotely to an Active Directory other than the one in your current domain, you must specify the name of a computer that is already a member of the domain that belongs to the Active Directory you want. For example:

\\MyComputer\root\directory\LDAP

This example shows that there are two parts that make up a fully qualified namespace name. The first part (\\MyComputer) represents the computer that is already a member of the domain that belongs to the Active Directory you want. The second part (\root\directory\LDAP) represents the Active Directory in the DS provider schema.

The structure of the WMI namespace looks like this:

The DS Provider is both a dynamic class and a dynamic instance provider. The DS Provider maps all information in the Active Directory to WMI (represented by the LDAP namespace). References or aliases of every object in the Active Directory now exist in WMI, as shown in the following diagram.

For information on the Active Directory and ADSI, see the SDK documentation on the MSDN Web site on http://www.microsoft.com.


DS Provider Architecture

[This is preliminary documentation and subject to change.]

Unlike the other standard providers, the DS Provider is both a class provider and an instance provider. Management applications requesting Active Directory information from WMI receive it dynamically through the DS Provider in the following way:

  • Class operations are directed by WMI to the DS class provider part of the DS provider. The DS class provider part accesses only the schema part of the Active Directory.
  • Instance operations are directed by WMI to the DS instance provider part of the DS Provider. The DS instance provider part accesses only the part of the Active Directory that contains information pertaining to instances.

The DS class associations provider and the DS instance associations provider both support instance operations.

The DS Provider has a logical structure that is different from the other standard providers. Its class information is not stored in the CIM Repository. In the DS Provider, class and instance information is dynamic.

The following diagram shows the relationship between WMI and the Active Directory.


How the Active Directory is Mapped to WMI

[This is preliminary documentation and subject to change.]

Classes and instances of classes that exist in the Active Directory are mirrored in WMI. Because of fundamental differences in the two environments, simply renaming classes and instances of classes was insufficient. Instead, naming rules were created to preserve the relationships that exist between classes and instances of classes.

Mapping rules specific to the four parts of the DS Provider can be found in the following sections:

  • Class Provider Mapping
  • Instance Provider Mapping
  • Class Associations Provider Mapping
  • Instance Associations Provider Mapping


Class Provider Mapping

[This is preliminary documentation and subject to change.]

This section contains information on:

  • Mapping of Classes
  • Mapping of Attributes


Mapping of Classes

[This is preliminary documentation and subject to change.]

Each class in the Active Directory schema is mapped to a single class in the appropriate WMI namespace as follows:

The name of the class will be the same as the mangled value of the property "Ldap-Display-Name" name of the Active Directory class. If the "Sub-Class-Of" property is present on the Active Directory class, then this WMI-mapped class is derived from the class specified, otherwise it is derived from the class "LDAP_BASE_CLASS" specified in the MOF in CIM Object Manager interaction. Note that this class has a keyed property of name "ADSIPath" and type VT_BSTR which is the unique ADSI path that identifies this instance. The Active Directory supports only single-inheritance, so this works fine. A qualifier "dynamic" of type VT_BOOL, and flavor WBEM_FLAVOR_FLAG_PROPAGATE_TO_INSTANCE | WBEM_FLAVOR_FLAG_PROPAGATE_TO_DERIVED_CLASS set to TRUE is created for every class. This is a standard CIM Object Manager qualifier that indicates that the instances of this class are provided dynamically. A qualifier "Provider" of type VT_BSTR BOOL, and flavor WBEM_FLAVOR_FLAG_PROPAGATE_TO_INSTANCE | WBEM_FLAVOR_FLAG_PROPAGATE_TO_DERIVED_CLASS set to "DS Instance Provider" are created for every class. This is a standard CIM Object Manager qualifier that indicates the name of the provider that dynamically provides the instances of this class.

The rest of the ADSI properties are mapped to class qualifiers and properties as shown in the following tables. Standard CIM Object Manager and CIM qualifiers will be used as far as possible, in that order of preference. The following table lists the ADSI class properties that get mapped to WMI Class Qualifiers. All the qualifiers are mapped with a qualifier flag value of WBEM_FLAVOR_FLAG_PROPAGATE_TO_INSTANCE | WBEM_FLAVOR_FLAG_PROPAGATE_TO_DERIVED_CLASS.

The following table shows the mapping information for the Active Directory class.

Active Directory Property | WMI Qualifier Name | WMI Qualifier Type | Mapping Information
Common-Name | "CommonName" | VT_BSTR | Mapped directly from the string value.
Governs-Id | "GovernsId" | VT_BSTR | Mapped from the string representation of the OID, for example, "{ 1 3 3 6 }".
Schema-ID-Guid | "SchmaIDGuid" | VT_BSTR | Mapped from the string representation of the GUID, for example,, "{9d298efe-2d5a-11d2-93a8-00805f853771 }".
MAPI-Display-Type | "MAPIDisplayType" | VT_I4 | Mapped from the Boolean value.
RDN-ATT-ID | "RDNATTID" | VT_BSTR | Mapped from the string representation of the OID value, for example, "{ 1 3 3 6 }" In addition, the property identified here is annotated with the standard CIM Object Manager qualifier "indexed" set to TRUE.
System-Auxiliary-Class and Auxiliary-Class | "AuxiliaryDerivedFrom" | VT_BSTR | Formed by concatenating each of the strings in the two arrays with a blank used as a separator, for example, "auxClass1 auxClass2 auxClass3". In addition, the union set of the properties of these auxiliary classes are also made the properties of this class.
Default-Security-Descriptor | "DefaultSecurityDescriptor" | VT_BSTR | Mapped directly form the string value.
Object-Class-Category | "ObjectClassCategory" | VT_I4 | Mapped directly from the integer value. In addition, if the value is Abstract(2), then the standard CIM Object Manager VT_BOOL qualifier "Abstract" is also created.
System-Only | "SystemOnly" | VT_BO)L | Mapped directly from the Boolean value.
Object-Class | N/A | N/A | Not mapped.
NT-Security-Descriptor | NTSecurityDescriptor | VT_BSTR | Mapped from the string representation of its value.
Default-Object-Category | DefaultObjectCategory | VT_BSTR | Mapped directly from its string value.

The following table lists the Active Directory class properties mapped to WMI Class Properties.

Active Directory Class Property | Mapping to WMI
May-Contain | Each property in this list is mapped to a WMI property.
System-May-Contain | Each property in this list is mapped to a WMI property. In addition, each property is annotated with a qualifier "system", set to TRUE.
Must-Contain | Each property in this list is mapped to a WMI property. The standard CIM Object Manager qualifier "NotNull" is created for each of these.
System-Must-Contain | Each property in this list is mapped to a WMI property. The standard CIM Object Manager qualifier "NotNull" is created for each of these. In addition, each property is annotated with a qualifier "system", set to TRUE


Mapping of Attributes

[This is preliminary documentation and subject to change.]

Each attribute of an Active Directory class is mapped to exactly one property of the corresponding WMI class according to the rules in this section.

The name of the WMI property is the same as the "Ldap-Display-Name" value of the Active Directory attribute, mangled.

The mapping of the Active Directory syntaxes to WBEM Property type is detailed in the following table. If the Active Directory property "Is-Single-Valued" is FALSE, then this WMI property is combined with the OR operator with CIM_FLAG_ARRAY. Note that each property is tagged with the VT_BSTR qualifier "ADSyntax" that represents the underlying Active Directory syntax.

The following table shows the mapping of Active Directory syntax to WMI.

Active Directory Syntax | WMI Syntax | Property Qualifier "ADSyntax"
Undefined | N/A | N/A
Distinguished Name | CIM_STRING | "DistinguishedName"
Object Id | CIM_STRING | "Object ID"
Case Sensitive String | CIM_STRING | "Case Sensitive String"
Case Insensitive String | CIM_STRING | "Case Insensitive String"
Print Case String | CIMS_STRING | "Print Case String"
Numeric String | CIM_STRING | "Numeric String"
OR Name | CIM_STRING | "OR Name"
Boolean | CIM_BOOLEAN | "Boolean"
Integer | CIM_SINT32 | "Integer"
Octet String | Embedded object of Class Uint8Array defined below | "Octet String"
Time | CIM_DATETIME | "Time"
Unicode String | CINM_STRING | "Unicode String"
Presentation-Address | CIM_STRING | "Presentation-Address"
Access-Point | CIM_STRING | "Access-Point"
Windows NT Security Descriptor | Embedded object of Class Uint8Array defined below | "NT Security Descriptor"
Large Integer | CIM_STRING | "Large Integer". In addition the standard CIM qualifier CIMTYPE is set to "sint64"
SID | ?? | "SID"

The OctetString syntax, which basically refers to an array of Unit8 values, presents a problem when mapped to WMI because WMI allows properties of types UINT8 and Arrays of UINT8, whereas the DS allows properties of type OctetString as well as arrays of OctetString. For purposes of mapping the properties of type Array of OctetString, the following class is defined:

Class Uint8Array
{
    uint8 values[];
    uint32 numberOfValues;
};

All DS Property values of type OctetString are mapped to embedded instances of this class. Similarly, DS Property values of type Arrays of OctetString are mapped to arrays of embedded objects of this class, Uin8Array.

The rest of the Active Directory Attribute interface properties are mapped to WMI property qualifiers as detailed in the following table. All qualifiers are mapped with a qualifier flavor of WBEM_FLAVOR_FLAG_PROPAGATE_TO_INSTANCE | WBEM_FLAVOR_FLAG_PROPAGATE_TO_DERIVED_CLASS

The following table shows the WMI property qualifiers for an Active Directory attribute.

Active Directory Attribute property name | WMI Qualifier Name | WMI Qualifier type | Mapping Information
Common-Name | "CommonName" | VT_BSTR | Mapped from its string value.
Attribute-Id | "AttributeId" | VT_BSTR | Mapped form the string representation of the OID.
Schema-ID-Guid | "SchemaIDGuid" | VT_BSTR | Mapped from the string representation of the GUID.
MAPI-Display-Type | MAPIDisplayType | VT_I4 | Mapped from its integer value.
Attribute-Security-Guid | "AttributeSecurityGUID" | VT_BSTR | Mapped from the string representation of the GUID.
OM-Syntax | "OMSyntax" | VT_I4 | Mapped from its integer value.
Extended-Chars-Allowed | ExtendedCharsAllowed | VT_BOOL | Mapped from its Boolean value.
Range-Lower | "RangeLower" | VT_I4 | Mapped from the integer value.
Range-Upper | "RangeUpper" | VT_I4 | Mapped from the long value.
Search-Flags | "Indexed" | VT_BOOL | If the value is 1, then this Boolean qualifier is created.
System-Only | "SystemOnly" | VT_BOOL | Mapped from the Boolean value.
Object-Class | N/A | N/A | Not mapped.


Instance Provider Mapping

[This is preliminary documentation and subject to change.]

This section contains information on:

  • Mapping of namespaces
  • Mapping of Instances
  • Mapping of Attribute Values


Mapping of namespaces

[This is preliminary documentation and subject to change.]

Each of the namespaces in ADSI are mapped one-to-one to namespaces in the WMI namespace "root\directory". The name of the WMI namespace is the same as the ProgId of the ADSI provider that provides the namespace. Specifically, the Active Directory is mapped to the "LDAP" namespace in the "root\directory" namespace. This namespace is created statically as a part of the class provider registration MOF in section the CIM Object Manager section.


Mapping of Instances

[This is preliminary documentation and subject to change.]

Each Active Directory object maps to exactly one WMI instance. The WMI class corresponding to the WMI instance is the same as the class provided by the class provider from the corresponding Active Directory class. The key property "ADSIPath " of each instance is filled in with the ADSI path of the object.


Mapping of Attribute Values

[This is preliminary documentation and subject to change.]

Each attribute of an Active Directory object is mapped to exactly one WMI property. Property values are created as detailed in the following table. The various Active Directory syntaxes are taken into consideration.

Active Directory Syntax | WMI Syntax | WMI Property Value
Undefined | N/A | N/A
Distinguished Name | CIM_STRING | Mapped from the value of the string.
Object Id | CIM_STRING | Mapped from the string representation of the OID. Example: "1.3.3.4".
Case Sensitive String | CIM_STRING | Mapped from the value of the string.
Case Insensitive String | CIM_STRING | Mapped from the value of the string.
Print Case String | CIMS_STRING | Mapped from the value of the string.
Numeric String | CIM_STRING | Mapped from the value of the string.
OR Name | CIM_STRING | Mapped from the value of the string.
Boolean | CIM_BOOLEAN | Mapped directly to the appropriate Boolean value.
Integer | CIM_SINT32 | Mapped directly to the integer value.
Octet String | Embedded object of Class Uint8Array | Mapped to instances of the class, Uint8Array, as defined in Mapping of ATTRIBUTES.
Time | CIM_DATETIME | Converted to the CIM_DATETIME representation and mapped.
Unicode String | CIM_STRING | Mapped from the value of the string.
Presentation-Address | CIM_STRING | Mapped from the value of the string.
Access-Point | CIM_STRING | Mapped from the value of the string.
NT Security Descriptor | Embedded object of Class Uint8Array | Mapped to instances of the class Uint8Array as defined in Mapping of ATTRIBUTES.
SID | ?? | "SID"


Class Associations Provider Mapping

[This is preliminary documentation and subject to change.]

The DS is essentially a hierarchical store of objects. Those objects that can appear at a non-leaf level in the hierarchy are called containers. The structure of this hierarchy is further controlled by the "Poss-Superiors" and "System-Poss-Superiors" properties of a class in the schema. These, taken together, specify the set of classes whose instances can be contained within an instance of a container class. This specification can be modeled as a CIM association in the following way as instances of the static association class "DS_LDAP_Class_Containment" defined in the MOF below. The MOF also contains the provider registration information for this provider called "Class Associations Provider" that provides instances of this class.

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
//////  DS Class Associations Provider ////////////////////////////////
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////
// Create a class of which instances are provided by this provider
///////////////////////////////////////////////////////////////////////
[
    Association : ToInstance,
    dynamic,
    HasClassRefs,
    provider("Microsoft|DSLDAPClassAssociationProvider|V1.0")
]
class DS_LDAP_Class_Containment
{
    [key,classref{"DS_LDAP_Root_Class"} : ToInstance ToSubclass]
        object Ref ChildClass; // The child DS Class
    [key,classref{"DS_LDAP_Root_Class"} : ToInstance ToSubclass]
        object Ref ParentClass; // The parent DS Class

};

///////////////////////////////////////////////////////////////////////
// Create an instance of the provider class for registration
///////////////////////////////////////////////////////////////////////
instance of __Win32Provider as $AssociationsProvider
{
    Name = "Microsoft|DSLDAPClassAssociationProvider|V1.0";
    Clsid = "{33831ED4-42B8-11d2-93AD-00805F853771}";
    ImpersonationLevel = 1;
};

///////////////////////////////////////////////////////////////////////
// Specification of the instances and operation provided by the provider
///////////////////////////////////////////////////////////////////////
instance of __InstanceProviderRegistration
{
    Provider = $AssociationsProvider;
    SupportsGet = TRUE;
    SupportsPut = FALSE;
    SupportsDelete = FALSE;
    SupportsEnumeration = TRUE;
};

The "Class Associations Provider" provides instances of this class. Obviously, only GetObjectAsync and CreateClassEnumAsync are supported on this class.


Instance Associations Provider Mapping

[This is preliminary documentation and subject to change.]

The containment relationship in the instance hierarchy of the Active Directory is modeled as instances of the association class described by the following MOF. The MOF also contains the registration information for the provider that provides instances of this class. This provider is the same as the provider described in the instance provider part.

[
Association : ToInstance,
Dynamic,
provider("Microsoft|DSLDAPInstanceProvider|V1.0")
]
class DS_LDAP_Instance_Containment
{
[KEY] object ref ChildInstance; // The child DS Instance
    [KEY] object ref ParentInstance; // The parent DS Instance
};

On this class, the following operations are provided:

  • GetObjectAsync
  • ExecuteQueryAsync

Not all forms of querying will be supported. Only those forms of querying that help a client navigate the object hierarchy are supported. That means that only one of the following three kinds of queries will be allowed:

  • A query in which the child instance is specified: A query of the form :
    "select * form DS_LDAP_Instance_Containment where ChildInstance=<InstancePath>"
  • A query in which the parent instance is specified: A query of the form:
    "select * form DS_LDAP_Instance_Containment where ParentInstance=<InstancePath>"
  • A query in which the child instance and parent instance are specified: A query of the form:
    "select * form DS_LDAP_Instance_Containment where ChildInstance=<InstancePath> and ParentInstance=<InstancePath>"


DS Provider Parts

[This is preliminary documentation and subject to change.]

The DS provider is implemented using the following four parts; each one providing access to a specific kind of information:

DS Provider Part | Provides
Class provider | Classes.
Class associations provider | Associations between classes.
Instance provider | Instances. Provides both instances and associations between instances.
Instance associations provider | Associations between instances (handled by the Instance provider).


Class Provider

[This is preliminary documentation and subject to change.]

The class provider part of the DS Provider gives you access to the classes in the Windows 2000 Active Directory schema. An example of a class is DS_User, as shown in the following diagram.

The class provider part supports the following operations:

  • Get
  • Enumeration

The class provider part does not support the following operations:

  • Put
  • Delete
  • Query

The Managed Object Format (MOF) file contains registration information for this part of the DS Provider. For more information, see the DS class provider registration section.


Instance Provider

[This is preliminary documentation and subject to change.]

The instance provider part of the DS Provider gives you access to the instances of the classes in the Windows 2000 Active Directory schema. For example, enumerating instances of the class DS_USER produces a list of users in your domain.

The instance provider part supports the following operations:

  • Get
  • Put
  • Delete
  • Enumeration
  • Execute Query

The MOF contains registration information for this part of the DS Provider. For more information, see the DS instance provider registration section for more information.


Class Associations Provider

[This is preliminary documentation and subject to change.]

The class associations provider part of the DS Provider gives you access to the class associations in the Active Directory. The Active Directory is a hierarchical store of objects. Objects that appear at the non-leaf level (nodes, as opposed to branch ends) in the hierarchy are called containers. A container is represented as an instance of an association class.

The structure of this hierarchy is further defined by the Poss-Superiors and System-Poss-Superiors properties which specify the set of classes whose instances can be contained within an instance of a container class.

This specification is modeled as a CIM static association class DS_LDAP_Class_Containment, as shown in the following diagram.

The class associations provider part supports the following operations:

  • Get
  • Enumeration

Note WMI filters queries for this provider part.

The Class Associations Provider does not support the following operations:

  • Put
  • Delete

The MOF contains registration information for this part of the DS Provider. For more information, see the DS Class Provider registration section.


Instance Associations Provider

[This is preliminary documentation and subject to change.]

The instance associations provider part of the DS Provider gives you access to instances of the DS_LDAP_Instance_Containment association class. This class models relationships between instances in the Windows 2000 Active Directory schema.

Note The DS instance provider part provides the DS instances associations; there is no separate instances associations provider. The class, DS_LDAP_Instance_Containment, appears in the DS Provider schema because the class exists, but the provider does not. For this reason, the MOF does not contain registration information for this part of the DS Provider.

The following diagram shows where the DS_LDAP_Instance_Containment class appears in the DS Provider schema.

The instance associations provider part supports the following operations:

  • Get
  • Limited Querying


Registration of DS Provider Parts

[This is preliminary documentation and subject to change.]

When the DS Provider is registered, the following registration processes are executed in sequence. Each of the four parts of the DS Provider is registered as though it were a separate provider. The following topics discuss the registration process for the provider parts:

  • Preliminary Registrations
  • DS Class Provider
  • DS Instance Provider
  • DS Class Associations Provider


Preliminary Registrations

[This is preliminary documentation and subject to change.]

The following code is used to create a parent namespace for the DS provider namespace. This namespace acts as a parent namespace for child namespaces that represent other directories (of which the Active Directory/LDAP namespace is one).

#pragma namespace("\\\\.\\root")
instance of __Namespace
{
    Name = "directory" ;
};

The following code is used to create a namespace for the DS Provider.

#pragma namespace("\\\\.\\root\\directory")
instance of __Namespace
{
    Name = "LDAP" ;
};
#pragma namespace("\\\\.\\root\\directory\\LDAP")


DS Class Provider

[This is preliminary documentation and subject to change.]

The following code is used to create a class to model Uint8 arrays such as Octet String, and security descriptor arrays.

Class Uint8Array
{
    uint8 values[];
};

The following code is used to create a class to act as the base class of all classes provided by the DS Provider.

[Abstract]
    class DS_LDAP_Root_Class
{
    [KEY]  string ADSIPath;  // The key for any DS object.
};

The following code is used to create an instance of the provider class for registration.

instance of __Win32Provider as $ClassProvider
{
    Name                            =        "Microsoft|DSLDAPClassProvider|V1.0";
    Clsid                            =        "{1EF94880-01A8-11d2-A90B-00AA00BF3363}";
    ImpersonationLevel        =        1;
    PerUserInitialization    =        TRUE;
};

The following code is used to create a specification of the classes and operations provided by the provider.

instance of __ClassProviderRegistration
{
    Provider               =    $ClassProvider;
    SupportsGet            =    TRUE;
    SupportsPut            =    FALSE;
    SupportsDelete         =    FALSE;
    SupportsEnumeration    =    TRUE;
    ResultSetQueries       =    { "Select * From meta_class Where __this isa DS_LDAP_Root_Class" } ;    // Provide all classes derived from the base class
    UnsupportedQueries     =    { "Select * From meta_class Where __Class = \"DS_LDAP_Root_Class\"" };  // Except the base class itself, which is static
};

The following are two classes created to model ADSI object datatypes DN-String and DN-Binary.

class DN_With_String
{
  string dnString;
  string value;
};

class DN_With_Binary
{
  string dnString;
  uint8 value[];
};


DS Instance Provider

[This is preliminary documentation and subject to change.]

The following code is used to create an instance of the provider class for registration.

[
    Association : ToInstance,
    dynamic,
    provider("Microsoft|DSLDAPInstanceProvider|V1.0")
]

instance of __Win32Provider as $InstanceProvider
{
    Name    =    "Microsoft|DSLDAPInstanceProvider|V1.0";
    Clsid   =    "{AA527A40-4D9A-11d2-93AD-00805F853771}";
    PerUserInitialization = TRUE;
    ImpersonationLevel    =   1;
};

The following code is used to create a specification of the instances and operation provided by the provider.

instance of __InstanceProviderRegistration
{
    Provider              =   $InstanceProvider;
    SupportsGet           =   TRUE;
    SupportsPut           =   TRUE;
    SupportsDelete        =   TRUE;
    SupportsEnumeration   =   TRUE;
    QuerySupportLevels    =   { "WQL:UnarySelect" };
};


DS Class Associations Provider

[This is preliminary documentation and subject to change.]

The following code is used to create an instance of the provider class for registration.

[
    Association : ToInstance,
    dynamic,
    provider("Microsoft|DSLDAPClassAssociationProvider|V1.0")
]

instance of __Win32Provider as $AssociationsProvider
{
    Name  = "Microsoft|DSLDAPClassAssociationProvider|V1.0";
    Clsid = "{33831ED4-42B8-11d2-93AD-00805F853771}";
    ImpersonationLevel   =   1;
};

The following code is used to create a specification of the instances and operations provided by the provider.

instance of __InstanceProviderRegistration
{
    Provider              =   $AssociationsProvider;
    SupportsGet           =   TRUE;
    SupportsPut           =   FALSE;
    SupportsDelete        =   FALSE;
    SupportsEnumeration   =   TRUE;
};


Using the DS Provider

[This is preliminary documentation and subject to change.]

The DS Provider is a dynamic class provider and a dynamic instance provider, which means you can use the DS Provider to perform both class and instance operations. Class operations are read-only operations and include Enumerate, Get, and Query. Instance operations are both read and write operations and include Enumerate, Get, Query, Put, Modify, and Delete.

This section contains information on:

  • Executing Class Operations
  • Executing Instance Operations
  • Executing Class and Instance Operations using C++• Specifying the LDAP ADSI Path

For background information on the DS Provider, please see How the Active Directory is Mapped to WMI.


Executing Class Operations

[This is preliminary documentation and subject to change.]

This section contains information on:

  • Getting Class Information
  • Enumerating Classes


Getting Class Information

[This is preliminary documentation and subject to change.]

This section contains information on:

  • Using CIM Studio to Get Class Information
  • Getting a Class with C++


Using CIM Studio to Get Class Information

[This is preliminary documentation and subject to change.]

The name of the class you want and the name of the class to seach for will be different. This is because the Active Directory classes have been mapped to WMI and the mapping process changes the class names slightly. For example, to get the User Active Directory class, search for the DS_User class. For more information, see How the Active Directory is Mapped to WMI.

The following steps describe how to get class information using CIM Studio.

To get class information using CIM Studio

  1. Start CIM Studio.

    For information on how to use CIM Studio, see WMI CIM Studio.

  2. Connect to the root\directory\LDAP namespace on your computer.

  3. If you know the name of the class you want, click Search and type the name of the class.
  4. If you do not know the name of the class you want, browse the class hierarchy in the class explorer pane.
  5. Click the class you want in the navigation pane.

    The properties, methods and associations for the class appear in the information pane on the right.


Getting a Class with C++

[This is preliminary documentation and subject to change.]

The following code sample shows how you can use C++ to get an Active Directory class.

//-----------------------------------------------------------------------------------------
void GetAClass(IWbemServices *pServices)
{
    HRESULT result = S_OK;

    // Get an Active Directory class from the DS Provider.
    // Get the Active Directory class called person. This class changes to ds_person when it maps to WMI.

    BSTR strClassName = SysAllocString(L"ds_person");
    IWbemClassObject *pClass = NULL;
    if (SUCCEEDED(result = pServices->GetObject(strClassName, 0, NULL, &pClass, NULL)))
    {
        wprintf(L"Got the class %s successfully!\n", strClassName);

        // Browse the properties of the class by using the
        // IWbemClassbject functions...

        // Then release the class.
        pClass->Release();

    }

    else
        wprintf(L"Get class operation on %s failed because of WMI error %x\n", strClassName, result);

    SysFreeString(strClassName);
}


Enumerating Classes

[This is preliminary documentation and subject to change.]

This section contains information on:

  • Using CIM Studio to Enumerate Classes
  • Enumerating Subclasses of a Class with C++


Using CIM Studio to Enumerate Classes

[This is preliminary documentation and subject to change.]

The following steps describe how to enumerate classes using CIM Studio.

To enumerate classes using CIM Studio

  1. Start CIM Studio.

    For information on how to use CIM Studio, see WMI CIM Studio.

  2. Connect to the root\directory\LDAP namespace on your computer.

    The class explorer pane appears, showing a hierarchical list of the classes in the LDAP namespace.

Here is an example of DS Provider root classes enumerated on a remote computer. Note that there are five system classes and nine classes specific to the DS Provider.

You will normally have no need for the information contained in the system classes. The classes specific to the DS Provider (DN_With_String, DN_With_Binary, RootDSE, DN_Class, DN_Class, DSClass_To_DNInstance, DS_LDAP_Class_Containment, DS_LDAP_Instance_Containment, and Uint8Array) contain auxiliary (non essential) information. The class, DS_LDAP_Root_Class, is the the most important class in the LDAP namespace. It is the base class for every mapped Active Directory class. Expanding this class reveals the entire hierarchy.


Enumerating Subclasses of a Class with C++

[This is preliminary documentation and subject to change.]

The following code sample shows how to list all classes beneath a DS root class.

//-----------------------------------------------------------------------------------------
void EnumerateSubClassesOfAClass(IWbemServices *pServices)
{
    HRESULT result = S_OK;

    // See the classes derived in the Active Directoy Schema
    // from the Active Directory class called person.
    // Perform a deep enumeration of
    // all the subclasses of the ds_user WMI class.
    BSTR strSuperClassName = SysAllocString(L"ds_person");
    IEnumWbemClassObject *pEnumClasses = NULL;
    if ( SUCCEEDED(result = pServices->CreateClassEnum(strSuperClassName, WBEM_FLAG_DEEP, NULL, &pEnumClasses)))
    {
        // Walk through the enumeration and examine each class.
        IWbemClassObject *pNextSubClass = NULL;
        ULONG dwCount = 0;
        ULONG dwNextReturned = 0;
        while (SUCCEEDED(result = pEnumClasses->Next( WBEM_INFINITE, 1, &pNextSubClass, &dwNextReturned)) &&
            dwNextReturned == 1)
        {

            // Browse the properties of the sub class by using the
            // IWbemClassbject functions ...

            pNextSubClass->Release();
            dwCount ++;
        }
        wprintf(L"The class %s has %d subclasses!\n", strSuperClassName, dwCount);
        // Release the enumerator when done.
        pEnumClasses->Release();
    }
    else
        wprintf(L"The subclass enumeration operation failed on %s because of WMI error %x\n", strSuperClassName, result);
    SysFreeString(strSuperClassName);
}


Executing Instance Operations

[This is preliminary documentation and subject to change.]

This section contains information on:

  • Enumerating Instances
  • Getting Instance Information
  • Querying for Instances


Enumerating Instances

[This is preliminary documentation and subject to change.]

This section contains information on:

  • Enumerating Users in a Domain with VBScript
  • Enumerating User Groups in a Domain with VBScript
  • Enumerating Instances of a Class with C++


Enumerating Users in a Domain with VBScript

[This is preliminary documentation and subject to change.]

The following Microsoft Visual Basic Scripting Edition (VBScript) script lists the users in this domain.

' This is a general routine that enumerates instances of a given class.
' The script calls the EnumerateInstances routine for the ds_user class.
'----------------------------------------------------------------------------

Sub EnumerateInstances ( objService , objClass )

    On Error Resume Next

    Dim objInstance
    Dim objEnumerator
    Set objEnumerator = objService.InstancesOf ( objClass )
    If Err = 0 Then

        For Each objInstance In objEnumerator

            Dim propertyEnumerator
            Set propertyEnumerator = objInstance.Properties_
            WScript.Echo propertyEnumerator.Item("DS_sAMAccountName")

        Next
    Else
        WScript.Echo "Err = " + Err.Number
    End If

End Sub

'----------------------------------------------------------------------------
' Start of script.
' Create a locator and connect to the namespace where the DS Provider operates.

Dim objLocator
Set objLocator = CreateObject("WbemScripting.SWbemLocator")
Dim objService
Set objService = objLocator.ConnectServer(".", "root\directory\LDAP")

'----------------------------------------------------------------------------
' Set the impersonation level.

objService.Security_.ImpersonationLevel = 3

'----------------------------------------------------------------------------
' Enumerate the instances of the ds_user class.

EnumerateInstances objService , "ds_user"


Enumerating User Groups in a Domain with VBScript

[This is preliminary documentation and subject to change.]

The following VBScript script lists the user-groups in this domain.

' This is a general routine that enumerate instances of a given class.
' The script calls the EnumerateInstances routine for the ds_group class.
'----------------------------------------------------------------------------

Sub EnumerateInstances ( objService , objClass )

    On Error Resume Next

    Dim objInstance
    Dim objEnumerator
    Set objEnumerator = objService.InstancesOf ( objClass )
    If Err = 0 Then

        For Each objInstance In objEnumerator

            Dim propertyEnumerator
            Set propertyEnumerator = objInstance.Properties_
            WScript.Echo propertyEnumerator.Item("DS_sAMAccountName")

        Next
    Else
        WScript.Echo "Err = " + Err.Number
    End If

End Sub

'----------------------------------------------------------------------------
'
' Start of script.
' Create a locator and connect to the namespace where the DS Provider operates.

Dim objLocator
Set objLocator = CreateObject("WbemScripting.SWbemLocator")
Dim objService
Set objService = objLocator.ConnectServer(".", "root\directory\LDAP")

'----------------------------------------------------------------------------
' Set the impersonation level.

objService.Security_.ImpersonationLevel = 3

'----------------------------------------------------------------------------
' Enumerate the instances of the ds_group class.

EnumerateInstances objService , "ds_group"


Enumerating Instances of a Class with C++

[This is preliminary documentation and subject to change.]

The following code sample shows how to enumerate instances of a class with C++.

//-----------------------------------------------------------------------------------------
void EnumerateInstancesOfAClass(IWbemServices *pServices)
{
    HRESULT result = S_OK;

    // Find out how many users are in the domain.
    // Enumerate the instances of the ds_user class.
    BSTR strClassName = SysAllocString(L"ds_user");
    IEnumWbemClassObject *pEnumInstances = NULL;
    if ( SUCCEEDED(result = pServices->CreateInstanceEnum(strClassName, WBEM_FLAG_SHALLOW, NULL, &pEnumInstances)))
    {
        // Iterate through the enumeration, printing the class names.
        IWbemClassObject *pNextInstance = NULL;
        ULONG dwCount = 0;
        ULONG dwNextReturned = 0;
        pEnumInstances->Reset();
        while (SUCCEEDED(result = pEnumInstances->Next( WBEM_INFINITE, 1, &pNextInstance, &dwNextReturned)) &&
            dwNextReturned == 1)
        {

            // Browse the properties of the instance using the
            // IWbemClassbject functions.

            pNextInstance->Release();
            dwCount ++;
        }
        wprintf(L"There are %d users in the domain!\n", dwCount);
    }
    else
        wprintf(L"The instance enumeration operation failed on %s because of WMI error %x\n", strClassName, result);
    SysFreeString(strClassName);
}


Getting Instance Information

[This is preliminary documentation and subject to change.]

This section contains information on:

  • Getting an Instance of a Class with C++
  • Deleting an Instance of a Class with C++


Getting an Instance of a Class with C++

[This is preliminary documentation and subject to change.]

The following code sample shows how to get an instance of a class using C++.

//-----------------------------------------------------------------------------------------
void GetAnInstance(IWbemServices *pServices)
{
    // Get an instance of the Active Directory class called user.
    // There is typically a user called Administrator.

    // You must change this string to actually contain the
    //ADSI path to the
    // user object for Administrator on your domain.
    BSTR strInstancePath = SysAllocString(L"ds_user.ADSIPath=\"LDAP://CN=Administrator,CN=Users,DC=dsprovider,DC=nttest,DC=microsoft,DC=com\"");
    IWbemClassObject *pInstance = NULL;
    HRESULT result = WBEM_E_FAILED;
    if (SUCCEEDED(result = pServices->GetObject(strInstancePath, 0, NULL, &pInstance, NULL)))
    {
        // Iterate through properties of the user.
        // Note: All properties are prefixed with "ds_."
        BSTR strSamAccountName = SysAllocString(L"DS_sAMAccountName");
        BSTR strLogonCount = SysAllocString(L"DS_logonCount");

        VARIANT vSamAccountNameValue;
        VARIANT vLogonCountValue;
        VariantClear(&vSamAccountNameValue);
        VariantClear(&vLogonCountValue);
        if (SUCCEEDED(pInstance->Get(strSamAccountName, 0, &vSamAccountNameValue, NULL, NULL)) &&
            SUCCEEDED(pInstance->Get(strLogonCount, 0, &vLogonCountValue, NULL, NULL)) )
        {
            wprintf(L"The user object for user %s was successfully retrieved! ", vSamAccountNameValue.bstrVal);
            wprintf(L"It has a Logon Count of %d\n", vLogonCountValue.lVal);
        }
        else
            wprintf(L"The GetObject() operation failed to get the required properties on the user object\n");

        pInstance->Release();
    }
    else
        wprintf(L"The GetObject() operation failed on %s because of WMI error %x\n", strInstancePath, result);
    SysFreeString(strInstancePath);
}


Deleting an Instance of a Class with C++

[This is preliminary documentation and subject to change.]

The following code sample shows how to delete an instance of a class using C++.

//-----------------------------------------------------------------------------------------
void DeleteAnInstance(IWbemServices *pServices)
{
    // Delete an instance of the Active Directory class called user.
    // Before executing this, create a user called "user1."

    // Edit this string so it contains the ADSI path to the
    // user object for "user1" on your domain.
    BSTR strInstancePath = SysAllocString(L"ds_user.ADSIPath=\"LDAP://CN=user1,CN=Users,DC=dsprovider,DC=nttest,DC=microsoft,DC=com\"");

    HRESULT result = WBEM_E_FAILED;
    if (SUCCEEDED(result = pServices->DeleteInstance(strInstancePath, 0, NULL, NULL)))
        wprintf(L"Deleted the user %s successfully!\n", strInstancePath);
    else
        wprintf(L"Could not delete the user %s due to WMI error %x\n", strInstancePath, result);

    SysFreeString(strInstancePath);
}


Querying for Instances

[This is preliminary documentation and subject to change.]

This section contains information on:

  • Conducting a Class Query With C++


Conducting a Class Query with C++

[This is preliminary documentation and subject to change.]

The following code sample shows how to conduct a class query with C++.

//-----------------------------------------------------------------------------------------
void ExecuteAQuery(IWbemServices *pServices)
{
    // Find users who have logged on more than 4 times since their accounts were created.
    // The following demonstrates how to form the query.
    BSTR strQuery = SysAllocString(L"select * from ds_user where ds_logonCount>4");

    // Note: The query language is WQL.
    BSTR strQueryLanguage = SysAllocString(L"WQL");

    IEnumWbemClassObject *pEnumerator = NULL;
    HRESULT result = WBEM_E_FAILED;
    if (SUCCEEDED(result = pServices->ExecQuery(strQueryLanguage, strQuery, WBEM_FLAG_FORWARD_ONLY, NULL, &pEnumerator)))
    {
        // Iterate through the enumeration, examining each object.
        IWbemClassObject *pNextInstance = NULL;
        ULONG dwCount = 0;
        ULONG dwNextReturned = 0;
        while (SUCCEEDED(result = pEnumerator->Next( WBEM_INFINITE, 1, &pNextInstance, &dwNextReturned)) &&
            dwNextReturned == 1)
        {

            // Browse the properties of each user instance using the
            // IWbemClassbject functions.

            // Release it when done.
            pNextInstance->Release();
            dwCount ++;
        }
        wprintf(L"There are %d users who have logged in more than 4 times!\n", dwCount);

        // Release the enumerator when done.
        pEnumerator->Release();
    }
}


Executing Class and Instance Operations using C++

[This is preliminary documentation and subject to change.]

The following code is a driver program that calls the functions presented in the Executing Instance Operations section. It can be used to execute class and instance operations.

#define _WIN32_WINNT    0x0500

#include <windows.h>
#include <stdio.h>

#include <objbase.h>
#include <wbemcli.h>

// Function declarations for each of the sample code functions.
Void    GetAClass                                    (IWbemServices *pServices);
void    EnumerateSubClassesOfAClass    (IWbemServices *pServices);
void    GetAnInstance                            (IWbemServices *pServices);
void    DeleteAnInstance                    (IWbemServices *pServices);
void    CreateAnInstance                    (IWbemServices *pServices);
void    numerateInstancesOfAClass        (IWbemServices *pServices);
void    xecuteAQuery                            (IWbemServices *pServices);

//-----------------------------------------------------------------------------------------
void main()
{
    // Initialize COM. Remember, the DS Provider needs impersonation to be called.
    // Call the CoInitializeSecurity() COM function, and #define _WIN32_WINNT to
    // be greater than 0x0400 (see top of sample).
    If (SUCCEEDED(CoInitialize(NULL)) && SUCCEEDED(CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_CONNECT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, 0)))
    {
        // Create the IWbemLocator object.
        IWbemLocator *t_pLocator = NULL;
        if (SUCCEEDED(CoCreateInstance(CLSID_WbemLocator,
            0,
            CLSCTX_INPROC_SERVER,
            IID_IWbemLocator, (LPVOID *) &t_pLocator)))
        {
            // Connect to the correct namespace.
            // The DS Provider operates in the root\directory\LDAP namespace.
            IWbemServices *t_pNamespace = NULL;
            BSTR strNamespace = SysAllocString(L"root\\directory\\LDAP");
            if(SUCCEEDED(t_pLocator->ConnectServer(strNamespace, NULL, NULL, NULL, 0, NULL, NULL, &t_pNamespace)))
            {

                // Important - since the DSProvider goes accross the process…
                // Every IWbemServices interface obtained form the IWbemLocator must
                // have the COM interface function IClientSecutiry::SetBlanket() called on it
                // for the DS Provider to work.
                IClientSecurity *t_pSecurity = NULL ;
                if (SUCCEEDED(t_pNamespace->QueryInterface ( IID_IClientSecurity , (LPVOID *) & t_pSecurity )))
                {
                    t_pSecurity->SetBlanket(
                        t_pNamespace ,
                        RPC_C_AUTHN_WINNT,
                        RPC_C_AUTHZ_NONE,
                        NULL,
                        RPC_C_AUTHN_LEVEL_CONNECT ,
                        RPC_C_IMP_LEVEL_IMPERSONATE,
                        NULL,
                        EOAC_NONE
                    );
                    t_pSecurity->Release () ;
                }

                /**************************************************************
                *
                *  THE FUNCTIONS BELOW SHOW HOW TO PERFORM VARIOUS OPERATIONS.
                *  THEY ARE GROUPED ACCORDING TO THE VARIOUS DS PROVIDERS.
                *
                **************************************************************/

                /************************************************************
                * DS CLASS OPERATIONS - USING THE DS CLASS PROVIDER.
                ************************************************************/
                GetAClass(t_pNamespace);
                EnumerateSubClassesOfAClass(t_pNamespace);

                /************************************************************
                * DS INSTANCE OPERATIONS - USING THE DS INSTANCE PROVIDER.
                ************************************************************/
                GetAnInstance(t_pNamespace);
                DeleteAnInstance(t_pNamespace);
                EnumerateInstancesOfAClass(t_pNamespace);
                ExecuteAQuery(t_pNamespace);

                /************************************************************
                * INSTANCE ASSOCIATIONS - USING THE DS INSTANCE ASSOCIATIONS PROVIDER.
                ************************************************************/

                t_pNamespace->Release();
            }
            SysFreeString(strNamespace);
            t_pLocator->Release();
        }
    }
}


Specifying the LDAP ADSI Path

[This is preliminary documentation and subject to change.]

BSTR strObjPath = SysAllocString(L"ds_user.ADSIPath=\"LDAP://CN=abc\#,"
                                 L"CN=Users,DC=dsprovider,DC=nttest,"
                                 L"DC=microsoft,DC=com\"");


Registering the DS Provider

[This is preliminary documentation and subject to change.]

The DS provider DLL and classes are registered with WMI automatically during the WMI installation process. There should be no need for you to register this provider for your applications. However, if an application requires the DS Provider to be registered and it is not, you must register the DLL, then compile the Dsprov.mof file yourself using the MOF compiler, as described in Compiling the dsprov.mof File.

Registrations are the instance definitions required for the DS Provider to interact with WMI. Generally, registrations include instances of these system classes:

  • __Win32Provider
  • __InstanceProviderRegistration
  • __ClassProviderRegistration

These instance definitions do not provide Active Directory information themselves.

Note The DS provider employs the standard registration process for providers. For a complete description of this process, see Registering a Provider.

This section contains information on:

  • Registering the DLL
  • Compiling The Dsprov.mof File


Registering the DLL

[This is preliminary documentation and subject to change.]

The file Dsprov.dll is a dynamically linked library that contains the DS Provider. This file must be registered with Microsoft® Windows 2000 before you can use the DS Provider. If you are running Windows 2000, Dsprov.dll should already be registered. If for some reason it is not, perform the following procedure to register it.

The following steps describe how to register the DLL.

To register Dsprov.dll with either Windows 2000

  1. Open a command prompt window.
  2. Navigate to the WBEM installation folder (for example, %Windir%\system32\wbem\).
  3. Type regsvr32.exe Dsprov.dll.


Compiling The Dsprov.mof File

[This is preliminary documentation and subject to change.]

You can manually register the DS provider with WMI by compiling Dsprov.mof.

The following steps describe how to compile the MOF file.

To compile the Dsprov.mof MOF file with Windows 2000

  1. Open a command prompt window.
  2. Navigate to the WBEM installation folder (for example, %Windir%\system32\wbem\).
  3. Type mofcomp Dsprov.mof.

When you are done, perform instance enumeration.


DS Provider Reference

[This is preliminary documentation and subject to change.]

This section contains information on:

  • DS Provider Classes


Example VB Scripts

[This is preliminary documentation and subject to change.]

This section contains information on:

  • Generating a User Path Listing with VBScript
  • Generating a User-Group Path Listing with VBScript


Generating a User Path Listing with VBScript

[This is preliminary documentation and subject to change.]

The following script lists the ADSI path to the user objects that a given group contains.

'----------------------------------------------------------------------------

' This is a routine that prints the users in a group.
'----------------------------------------------------------------------------

Sub FindGroupMembership ( objService , theGroup )

    On Error Resume Next

    Dim objInstance
    Dim objEnumerator
    Dim groupFound
    groupFound = 0

    ' Enumerate the Group
    Set objEnumerator = objService.InstancesOf ( "ds_group" )

    If Err = 0 Then
        ' Go through the groups looking for the correct one
        For Each objInstance In objEnumerator

            Dim propertyEnumerator
            Set propertyEnumerator = objInstance.Properties_
            If propertyEnumerator("DS_sAMAccountName") = theGroup Then
                groupFound = 1
                Wscript.Echo "Group: " + propertyEnumerator.Item("DS_sAMAccountName") + " has users:"

                For x = LBound(propertyEnumerator("DS_member")) To UBound(propertyEnumerator("DS_member"))
                    Wscript.Echo propertyEnumerator("DS_member")(x)
                Next
            End If
        Next
    Else
        WScript.Echo "Err = " + Err.Number + " " + Err.Description
    End If

    If( groupFound = 0) Then
        Wscript.Echo "Group not found: " + theGroup
    End If

End Sub

'----------------------------------------------------------------------------

' Start of script.
' Create a locator and connect to the namespace where the DS Provider operates.
'----------------------------------------------------------------------------

Dim objLocator
Set objLocator = CreateObject("WbemScripting.SWbemLocator")
Dim objService
Set objService = objLocator.ConnectServer(".", "root\directory\LDAP")

'----------------------------------------------------------------------------
' Set the impersonation level.

objService.Security_.ImpersonationLevel = 3

'----------------------------------------------------------------------------
' The first argument should be the group.

Set objArgs = Wscript.Arguments
If objArgs.Count <> 0 Then
    FindGroupMembership objService , objArgs(0)
Else
    Wscript.Echo "Usage: groupContains <group>"
End If


Generating a User-Group Path Listing with VBScript

[This is preliminary documentation and subject to change.]

This script lists the ADSI path to the group objects to which a given user belongs.

'
'----------------------------------------------------------------------------
'
' This is a general routine that prints the groups a user belongs to.
'----------------------------------------------------------------------------

Sub FindUserMembership ( objService , user )

    On Error Resume Next

    Dim objInstance
    Dim objEnumerator
    Dim userFound
    userFound = 0

'----------------------------------------------------------------------------
    ' Enumerate the users
    Set objEnumerator = objService.InstancesOf ( "ds_user" )

    If Err = 0 Then

        ' Iterate through the list of all users, looking for the correct one.
        For Each objInstance In objEnumerator

            Dim propertyEnumerator
            Set propertyEnumerator = objInstance.Properties_

            If propertyEnumerator("DS_sAMAccountName") = user Then
                userFound = 1
                Wscript.Echo "User: " + propertyEnumerator.Item("DS_sAMAccountName") + " belongs to:"

                For x = LBound(propertyEnumerator("DS_memberOf")) To UBound(propertyEnumerator("DS_memberOf"))
                    Wscript.Echo propertyEnumerator("DS_memberOf")(x)
                Next
            End If

        Next

    Else
        WScript.Echo "Err = " + Err.Number + " " + Err.Description
    End If

    If( userFound = 0) Then
        Wscript.Echo "User not found: " + user
    End If

End Sub

'----------------------------------------------------------------------------
' Start of script.
' Create a locator, and connect to the namespace where the DS Provider operates.

Dim objLocator
Set objLocator = CreateObject("WbemScripting.SWbemLocator")
Dim objService
Set objService = objLocator.ConnectServer(".", "root\directory\LDAP")

'----------------------------------------------------------------------------
' Set the impersonation level.

objService.Security_.ImpersonationLevel = 3

'----------------------------------------------------------------------------
' The first argument should be the user.

Set objArgs = Wscript.Arguments

If objArgs.Count <> 0 Then
    FindUserMembership objService , objArgs(0)
Else
    Wscript.Echo "Usage: userBelongsTo <user>"
End If


DS Provider Classes

[This is preliminary documentation and subject to change.]

Every object contained in any Active Directory you connect to is represented in WMI through the DS Provider. The class, DS_LDAP_Root_Class, serves as the base class for every Active Directory class. When you enumerate this class, you are looking at copies of all of the Active Directory classes. Each class is prefixed with DS_.

The other three classes (Uint8Array, DS_LDAP_Class_Containment, and DS_LDAP_Instance_Containment) can be thought of as utility classes. They provide extra information about Active Directory classes and objects.

The DS Provider contains the following classes.

Class | Description
Uint8Array | Used to create a class to model arrays of Uint8 (Octet String, Windows NT Security Descriptor).
DS_LDAP_Root_Class | The base class of all classes provided by the DS Provider.
DS_LDAP_Class_Containment | An association class required to expose the containment between classes in the Active Directory. Each class in the Active Directory has an attribute called Poss-Superiors and System-Poss-Superiors.
DS_LDAP_Instance_Containment | Every instance of every Active Directory class has a parent and zero or more children. This association class captures this relationship.


View Provider

[This is preliminary documentation and subject to change.]

You can use the View Provider to create new classes based on instances of other classes. The source class instances for view classes can be from the same namespace or from different namespaces. Using the View Provider, you can create view classes from similar but unrelated source classes or even from identical source class instances located on different computers. View classes make it easy to bring together information from different places.

This section contains the following topics:

  • About the View Provider gives an overview of the View Provider and a discussion about views.
  • Using the View Provider shows how to register the View Provider and gives examples that show how to create views.


About the View Provider

[This is preliminary documentation and subject to change.]

Windows Management Instrumentation (WMI) providers are usually designed to provide information about a specific managed object on a single computer. You can use the View Provider to take properties from different source classes, different namespaces, or different computers and combine the properties as a single class.

The three types of view classes are:

  • Join view classes, which consist of instances of different classes connected by a common property value.
  • Union view classes, which are the union of source class instances.
  • Association view classes, which provide views of existing association classes.


Join View Classes

[This is preliminary documentation and subject to change.]

Join view classes contain properties from source class instances that are connected by a common property value. For example, Class1.prop1 = Class2.prop2. Join classes can also be based on inequality of property values. For example, Class1.prop1 <> Class2.prop2. In this case, prop1 and prop2 will not be mapped onto the same property in the view class.

Each instance in a join view class consists of parts of other class instances. Join view classes are helpful when the information you are looking for is contained in separate but related classes. For example, if you want information about a printer and information about the printer configuration, you can create a join view class that contains some of the properties of the Win32_Printer class and some of the properties of the Win32_PrinterConfiguration class. Without the View Provider, you must retrieve and merge the properties of the two separate instances to get this information.

Note Properties used to perform the join must have identical CIM types. Also, there are non-equality joins. In this case, the non-equality properties must map to different properties in the view class.


Union View Classes

[This is preliminary documentation and subject to change.]

Union view classes are created from the logical union of source class instances. Union views include all the instances of the source classes unless you limit the instances by using a WHERE clause on the source query.

Union view classes are useful when you want to see instances of similar or identical classes that are located in different namespaces or on different computers. For example, to monitor the status of the disk drives on several computers, you can create a union class that contains instances of the different disk drives you want to monitor.

You can then construct a query that checks for hard drives that are running out of space. The following example checks for hard drives that have less than 30 megabytes of space left.

SELECT * FROM UnionDrive WHERE fspace < 30000000 AND desc = "Local Fixed Disk"

The properties of union view classes can be based on properties that are not present in all of the source class instances. If the source class instances do not have the same property, the properties of union class instances have a value of NULL. For example, suppose you are performing the union of two similar classes that manage specific types of hard drives but only one class supports a property called temperature. You can create a union view class with a temperature property, but the temperature property of the union view class has a value of NULL for source instances that do not have a temperature property.


Updating Instances of View Classes

[This is preliminary documentation and subject to change.]

You can update the values of non-key properties of union view class instances. The changes you make to the view class instance will be propagated back to the source class instances that form the union view class. For example, suppose you have a union class named UnionClass formed from two source classes called class1 and class2.

If you examine the UnionClass instance with a key value of "Class2key2" you will see that the property Class2Prop = 4. If you change the value of this property to Class2Prop = 66 and save the changes, the view provider will modify the source class instance Class2 that this instance originates from. If you check the source instance in Class2 with a key value "Class2key2", you will see the value of the property Class2Prop = 66.

Update Restrictions

The following restrictions apply to changes to view class instances:

  • You cannot create new instances of view classes.
  • Only union classes support updates; join and association views create read-only view instances.


Association View Classes

[This is preliminary documentation and subject to change.]

Association view classes allow you to use ASSOCIATORS OF queries on classes that reside in different namespaces. Association view classes can use the Direct qualifier to prevent association references from being mapped to a view reference. See Creating Views with Association Classes, Creating an Association View Class, Association Classes, ASSOCIATORS OF Statement.


View Class Definition

[This is preliminary documentation and subject to change.]

View class definitions should begin with the JoinOn string qualifier, the Union Boolean qualifier, or Association qualifier to indicate which type of view class is being defined. The Union, Association, and JoinOn qualifiers are mutually exclusive. If you specify the Union qualifier with a value of TRUE, you cannot assign a value for the Association or JoinOn qualifier. Conversely, if you specify a value for the JoinOn qualifier, you cannot assign the value TRUE to the Union or Association qualifier.

After you declare which type of view you are designing, you must specify values for the ViewSources qualifier and the ViewSpaces qualifier. These two qualifiers specify which source instances and properties you want to use and where to find the namespaces to which the source classes belong.

The next step is to define the properties that will be in your view class. Each property in a view class has a PropertySources qualifier to indicate the source property from which this property will get data.


Key Properties for View Classes

[This is preliminary documentation and subject to change.]

You must specify the key properties of the source classes when defining union view classes. Each source class must have the same number of key properties matched by Cimtype. Also, the keys of view classes must be able to uniquely identify all source instances on which the view class is based. In some cases, you might need to specify system properties to ensure that instances are unique. For example, if you create a view from the union of two identical classes in two different namespaces you must include the __Namespace property as a key in the view class to differentiate any two identical source instances in different namespaces. If you use two similar classes from the same namespace to create a view, use the __Class property instead of the __Namespace property. Rename any system properties in the view so you can avoid a conflict with the system properties of the view class.


View Provider Qualifiers

[This is preliminary documentation and subject to change.]

The following table shows the qualifiers you can use to define View Provider classes.

Qualifier | Purpose
Union qualifier | Boolean value that indicates you are defining a union class.
JoinOn qualifier | String that defines how source class instances should be joined in join view classes.
ViewSources qualifier | Array of WQL queries that define the source instances and properties that are used in a specific view class. Positional correspondence of all the array qualifiers is important.
ViewSpaces qualifier | Defines the namespaces where the source instances are located.
PropertySources qualifier | Defines the source properties from which a view class property gets data.
PostJoinFilter qualifier | Uses a WQL query to filter the instances after they have been joined in a join class.
HiddenDefault qualifier | Use to define a default value for a view class property based on a source class property with a different default value.
Direct qualifier | Used with view association properties and tells the provider that the association reference is not to be mapped to a view reference.
MethodSource qualifier | Tells the provider which source method to execute for the view method.


Union Qualifier

[This is preliminary documentation and subject to change.]

When the Union qualifier is set to TRUE it indicates that you are defining a union view. Union views contain instances based on the union of source instances. For example, you might declare the following:

Union, ViewSources{"Select Handle, Name, CreationDate From Win32_Process", "Select Caption, Name, ProcessHandle From Win32_Thread"}.


JoinOn Qualifier

[This is preliminary documentation and subject to change.]

The JoinOn qualifier set to non-Null indicates that you are defining a class that will join source instances. The value of the string you assign to the JoinOn qualifier determines how the View Provider will join the source instances.

The following example shows how to use the join qualifier to join two source classes from the Performance Monitor Provider.

JoinOn("Win32Perf_RawProcess.IDProcess = Win32Perf_RawThread.IDProcess")


ViewSources Qualifier

[This is preliminary documentation and subject to change.]

All view classes must have a string array qualifier called ViewSources. The ViewSources qualifier contains the source queries that define the source instances used in the view class. The value of the ViewSources qualifier is a string array containing WQL queries. You can define source classes and restrict the source instances your view class uses with the WQL WHERE keyword to create a filtered view.

The View Provider matches the source queries in the ViewSources qualifier to the namespaces listed in the ViewSpaces qualifier in the order the queries and namespaces are listed. The number of source queries must match the number of namespaces listed in the ViewSpaces qualifier. The order in which you list the source queries determines the namespaces from which the source instances are drawn.

Note The number of source queries you can define for join view classes depends on the number of instances these queries return and how many ways these instances can be joined. The number of possible combinations of source instances for view classes grows exponentially, so keep source queries for join view classes as simple as possible.


ViewSpaces Qualifier

[This is preliminary documentation and subject to change.]

The ViewSpaces qualifier defines the names and location of the namespaces where the source instances are located. You can specify any combination of namespaces on local or remote computers.

The following example lists two namespaces on the local computer.

ViewSpaces{"\\\\.\\root\\LocalNamespace", "\\\\.\\root\\RemoteNamespace"}

The View Provider matches the source queries in the ViewSources qualifier to the namespaces listed in the ViewSpaces qualifier in the order the queries and namespaces are listed. For more information about the ViewSpaces qualifier, see remote namespace view classes.


PropertySources Qualifier

[This is preliminary documentation and subject to change.]

Every property in a view class must have a string array qualifier called PropertySources. The PropertySources qualifier contains the name of the source class property or properties from which this view class property gets data. The order of the values in this array correspond to the order of the source classes defined for the ViewSources qualifier. The following example shows how to define a property for a union view class that is the union of the Win32_LogicalDisk class from two different computers:

[PropertySources{"DeviceID", "DeviceID"},key] String Devname;

The first DeviceId property corresponds to the DeviceId property from the class in the first source query. The second DeviceId property is the DeviceId property from the class in the second source query.

When defining properties for join view classes you must define a separate view property for each of the source class properties unless the source class properties are the basis of the join view class. The following example creates properties in a join view class on similar properties from the Win32_Printer source class and the Win32_PrinterConfiguration source class:

[PropertySources{"VerticalResolution", ""}] Uint32 Vres;
[PropertySources{"", "YResolution"}] Uint32 Yres;

If the two source classes are being joined by a common property, you can only define a single view class property because the value of both source class properties is always the same. The following example shows how to join the Win32_Printer class and the Win32_PrinterConfiguration by a common property value:

[PropertySources{"DeviceId", "DeviceName "}] String Name;


PostJoinFilter Qualifier

[This is preliminary documentation and subject to change.]

You can filter the instances of a join view class by assigning a WQL query to the PostJoinFilter qualifier. The value of the WQL query is applied to the instances of the join view class. You can use this qualifier to restrict the instances of your view class to those that meet specific conditions. The following WQL query filters instances of a join class called based on instances of Win32_LogicalDisk.

PostJoinFilter("SELECT * FROM JoinDrive WHERE FreeSpace > 1000000 and Description = \"3 1/2 Inch Floppy Drive\"")

There are several restrictions to the use of this qualifier.

  • PostJoinFilter is only available to join view classes.
  • The class name and property names specified in the query refer to the properties of the view class, not the source class.
  • No exclusion of properties is permitted, only SELECT * type queries are allowed.


HiddenDefault Qualifier

[This is preliminary documentation and subject to change.]

Any non-key view class property that is not named in any of the ViewSources qualifiers or JoinOn qualifiers may have the Boolean qualifier named HiddenDefault set to TRUE. The purpose of the HiddenDefault qualifier is to mark a property that belongs to an underlying source class. The underlying source class is implied by the view and defaults to a different value than that in the source class.

For example, suppose you have a source class named Win32_ScheduledJob with a Boolean property named OnceOnly which indicates whether the job is to be carried out periodically or once only. If you create two view classes named View_PeriodicJob and View_SingleShotJob, neither requires the OnceOnly property because the behavior is specified by the class name. However, when you create a new instance of the classes, each instance must specify the properties value and set it accordingly in the underlying source class instance. You can set the properties value by default in the class definition. View properties with this qualifier are ignored in all operations, except when creating an instance. When creating an instance, the value is always set to the default value.


Direct Qualifier

[This is preliminary documentation and subject to change.]

You can use the Direct qualifier in association view classes to prevent association references from being mapped to a view reference. The following example defines the property GroupComponent as an association reference that will not be mapped in the view reference.

[Direct, key, PropertySources{"GroupComponent"}]


MethodSource Qualifier

[This is preliminary documentation and subject to change.]

You can include methods from the source classes of union views by using the MethodSource qualifier. The syntax of this qualifier is similar to the PropertySources qualifier but defines a method instead of a property. The signature of the method must match the signature of the source class exactly. The easiest way of ensuring this is to copy the method signature from the MOF file that defines the source class. The example below defines a method from the ClearEventlog method of the CIMv2 class Win32_NTEventlogFile:

[implemented, MethodSource{"ClearEventlog"}]
  uint32   VClearEventlog([in] string ArchiveFileName);

Note The MethodSource qualifier is only valid when it is used with union views. See Union Views and Methods for more details.


Remote Namespace View Classes

[This is preliminary documentation and subject to change.]

You can create view classes that connect class instances from different namespaces on different computers if the view provider is on a computer with the Microsoft® Windows® 2000 operating system and the remote system is running Microsoft® Windows NT® version 4.0, SP4 or later or Windows 2000 operating system.

Remote namespace view classes are defined by specifying the full path to a remote namespace as part of the ViewSpaces qualifier. The following example shows how you can specify a local namespace and a namespace on a remote computer:

ViewSpaces{"\\\\.\\root\\LocalNamespace", "\\\\MyComputer\\root\\RemoteNamespace"},

Note You cannot create remote namespace views if the source classes are on computers that are not running Windows 2000.


Filtered Views

[This is preliminary documentation and subject to change.]

You can restrict the source instances the view classes use by adding a WHERE clause to the ViewSources qualifier.

The following example selects only instances of the LocalDisk class where the value of the FileSystem property is "NTFS" and instances of the RemoteDisk class where the value of the FreeSpace property is greater than 45 megabytes:

ViewSources{"SELECT __Namespace, Description, DeviceID, FileSystem, FreeSpace, VolumeName FROM LocalDisk WHERE FileSystem = \"NTFS\"", "Select __Namespace, Description, DeviceID, FileSystem, FreeSpace, VolumeName FROM RemoteDisk WHERE FreeSpace > 45000000"}


Creating Views with Association Classes

[This is preliminary documentation and subject to change.]

Creating a view class based on an association class results in a view association class only if the view class has two key reference properties and the view class has the Association Boolean qualifier set to TRUE. An association class can have other properties that are not references. If you create a view class using an association class as a source class but without mapping the reference properties, the resulting view class is not an association class.

Association views must be taken as a special case because the content of the association references must use the key structure present in the viewing namespace.

For example, if the association reference takes the following form in the original namespace:

Instance of Assoc1
{
    ref1 = "\\\\SourceMachine\\SourceNamespace\\Class:KeyProperty=KeyValue";

Then the association reference takes the following form in the viewing namespace:

Instance of ViewAssoc1
{
ref1 = "\\\\ViewMachine\\ViewNamespace\\ViewClass:ViewKeyProperty1 = Value1, ViewKeyProperty2 = Value2;

The view provider will leave the reference unmapped if you specify the Direct qualifier in this association view.


Using the View Provider

[This is preliminary documentation and subject to change.]

This section describes how you can register the View Provider and create view classes. The following topics are discussed:

  • Registering the View Provider
  • Creating a Join View Class
  • Creating a Union View Class


Registering the View Provider

[This is preliminary documentation and subject to change.]

The View Provider DLL is registered automatically during the Windows Management Instrumentation (WMI) installation process. A sample MOF named Viewtest.mof is supplied with the WMI core shows the registration of the provider. To compile the MOF into any namespace that the View Provider is to be used in, use the following syntax where <WBEM install dir> represents the location of the WMI installation, for example: C:\WINNT\system32\WBEM

C:\> <WBEM install dir>\mofcomp /N:<namespace path> <WMI install dir>\viewtest.mof

The view provider is registered with WMI with the following MOF code (taken from Viewtest.mof).

instance of __Win32Provider as $DataProv
{
    Name = "MS_VIEW_INSTANCE_PROVIDER";
    ClsId = "{AA70DDF4-E11C-11D1-ABB0-00C04FD9159E}";
    ImpersonationLevel = 1;
    PerUserInitialization = "True";

};

instance of __InstanceProviderRegistration
{
    Provider = $DataProv;
    SupportsPut = True;
    SupportsGet = True;
    SupportsDelete = True;
    SupportsEnumeration = True;
    QuerySupportLevels = {"WQL:UnarySelect"};
};


Creating a Join View Class

[This is preliminary documentation and subject to change.]

You can create a join view class from the Performance Monitor Provider classes, Win32_PerfRawData_PerfProc_Process and Win32_PerfRawData_PerfProc_Thread. The following MOF code creates a join class with some of the properties of both classes joined by the ProcessID property:

#pragma namespace("\\\\.\\root\\cimv2")

instance of __Win32Provider as $DataProv
{
    Name = "MS_VIEW_INSTANCE_PROVIDER";
    ClsId = "{AA70DDF4-E11C-11D1-ABB0-00C04FD9159E}";
    ImpersonationLevel = 1;
    PerUserInitialization = "True";

};

instance of __InstanceProviderRegistration
{
    Provider = $DataProv;
    SupportsPut = True;
    SupportsGet = True;
    SupportsDelete = True;
    SupportsEnumeration = True;
    QuerySupportLevels = {"WQL:UnarySelect"};
};

[JoinOn("Win32_PerfRawData_PerfProc_Process.IDProcess = Win32_PerfRawData_PerfProc_Thread.IDProcess"),
ViewSources{"Select Name, IDProcess, PriorityBase  From Win32_PerfRawData_PerfProc_Process" , "Select Name,IDProcess, ThreadState, PriorityCurrent From Win32_PerfRawData_PerfProc_Thread"},
ViewSpaces{"\\\\.\\root\\cimv2", "\\\\.\\root\\cimv2"},
dynamic: ToInstance, provider("MS_VIEW_INSTANCE_PROVIDER")]

class JoinedProcessThread
{
    [PropertySources{"IDProcess", "IDProcess"}] Uint32 ProcessID;
    [PropertySources{"Name", ""}] String PName;
    [PropertySources{"", "Name"}, key] String TName;
    [PropertySources{"", "ThreadState"}] Uint32 State;
    [PropertySources{"PriorityBase", ""}] Uint32 BasePriority;
    [PropertySources{"", "PriorityCurrent"}] Uint32 CurrentPriority;
};


Join View Example

[This is preliminary documentation and subject to change.]

The following example demonstrates several join view classes. Copy this MOF code to a text file and compile it with the MOF compiler. You can view the resulting classes in the Root\Sample_views namespace using WMI CIM Studio or WMI Object Browser.

////////////////////////////////////////////////////////////////
//                                                            //
//  Purpose: This sample MOF file demonstrates join views     //
//  of classes from the Win32 provider, WDM provider and      //
//  Performance Counters Provider                            //
////////////////////////////////////////////////////////////////

#pragma namespace("\\\\.\\root")

instance of __namespace
{
    Name = "sample_views";
};

#pragma namespace("\\\\.\\root\\sample_views")

instance of __Win32Provider as $DataProv
{
    Name = "MS_VIEW_INSTANCE_PROVIDER";
    ClsId = "{AA70DDF4-E11C-11D1-ABB0-00C04FD9159E}";
    ImpersonationLevel = 1;
    PerUserInitialization = "True";
};

instance of __InstanceProviderRegistration
{
    Provider = $DataProv;
    SupportsPut = True;
    SupportsGet = True;
    SupportsDelete = True;
    SupportsEnumeration = True;
    QuerySupportLevels = {"WQL:UnarySelect"};
};

//===================================================================
//  JOIN CASE1
//  The following class creates a new class from many
//  related WDM classes
//  NOTE: The WDM Provider is only available on (or after)
//  Windows 98 and Windows 2000.
//===================================================================

[JoinOn("MSNdis_MediaConnectStatus.InstanceName = MSNdis_MediaInUse.InstanceName \
     and MSNdis_MediaConnectStatus.InstanceName = MSNdis_MACOptions.InstanceName \
     and MSNdis_MediaConnectStatus.InstanceName = MSNdis_CoMediaConnectStatus.InstanceName \
     and MSNdis_MediaConnectStatus.InstanceName = MSNdis_CoMediaInUse.InstanceName \
     and MSNdis_MediaConnectStatus.InstanceName = MSNdis_CoTransmitPdusOk.InstanceName \
     and MSNdis_MediaConnectStatus.InstanceName = MSNdis_CoVendorDescription.InstanceName \
     and MSNdis_MediaConnectStatus.InstanceName = MSNdis_CoVendorDriverVersion.InstanceName \
     and MSNdis_MediaConnectStatus.InstanceName = MSNdis_CoVendorId.InstanceName \
     and MSNdis_MediaConnectStatus.InstanceName = MSNdis_CurrentLookahead.InstanceName"
),
ViewSources
    {
    "Select * from MSNdis_MediaConnectStatus",
    "Select * from MSNdis_MediaInUse",
    "Select * from MSNdis_MACOptions",
    "Select * from MSNdis_CoMediaConnectStatus",
    "Select * from MSNdis_CoMediaInUse",
    "Select * from MSNdis_CoTransmitPdusOk",
    "Select * from MSNdis_CoVendorDescription",
    "Select * from MSNdis_CoVendorDriverVersion",
    "Select * from MSNdis_CoVendorId",
    "Select * from MSNdis_CurrentLookahead"
    },
ViewSpaces
    {
    "\\\\.\\root\\wmi",
    "\\\\.\\root\\wmi",
    "\\\\.\\root\\wmi",
    "\\\\.\\root\\wmi",
    "\\\\.\\root\\wmi",
    "\\\\.\\root\\wmi",
    "\\\\.\\root\\wmi",
    "\\\\.\\root\\wmi",
    "\\\\.\\root\\wmi",
    "\\\\.\\root\\wmi"
    },
dynamic, provider("MS_VIEW_INSTANCE_PROVIDER")]
class Join_WDM_Media
{
    [
    PropertySources{"InstanceName","InstanceName","InstanceName", \
            "InstanceName","InstanceName","InstanceName", \
            "InstanceName","InstanceName","InstanceName", \
            "InstanceName"},
    key
    ]
   string VName;
    [
    PropertySources{"NdisMediaConnectStatus","","","","","","","","",""}
    ]
   uint32 VMediaConnectStatus;
    [
    PropertySources{"","NdisMediaInUse","","","","","","","",""}
    ]
   uint32 VMediaInUse [];
     [
    PropertySources{"","NumberElements","","","","","","","",""}
    ]
   uint32 VMediaInUseNumberElements;
     [
    PropertySources{"","","NdisMACOptions","","","","","","",""}
    ]
   uint32 VMACOptions;
    [
    PropertySources{"","","","NdisCoMediaConnectStatus","","","","","",""}
    ]
   uint32 VCoMediaConnectStatus;
    [
    PropertySources{"","","","","NdisCoMediaInUse","","","","",""}
    ]
   uint32 VCoMediaInUse [];
     [
    PropertySources{"","","","","NumberElements","","","","",""}
    ]
   uint32 VCoMediaInUseNumberElements;
    [
    PropertySources{"","","","","","NdisCoTransmitPdusOk","","","",""}
    ]
   uint32 VCoTransmitPdusOk;
    [
    PropertySources{"","","","","","","NdisCoVendorDescription","","",""}
    ]
   string VNdisCoVendorDescription;
    [
    PropertySources{"","","","","","","Active","","",""}
    ]
   Boolean VNdisCoVendorDescriptionActive;
    [
    PropertySources{"","","","","","","","NdisCoVendorDriverVersion","",""}
    ]
   uint32 VNdisCoVendorDriverVersion;
    [
    PropertySources{"","","","","","","","Active","",""}
    ]
   Boolean VNdisCoVendorDriverVersionActive;
    [
    PropertySources{"","","","","","","","","NdisCoVendorID",""}
    ]
   uint32 VNdisCoVendorID;
    [
    PropertySources{"","","","","","","","","Active",""}
    ]
   Boolean VNdisCoVendorIdActive;
    [
    PropertySources{"","","","","","","","","","NdisCurrentLookAhead"}
    ]
   Uint32 VCurrentLookAhead;
};

//===================================================================
//  JOIN CASE2
//  The following class creates a new class from two classes relating
//  the same type of information provided by two different providers.
//  NOTE: The HiPerf Provider is only available on Windows 2000
//  and later operating systems.
//===================================================================
[JoinOn("Win32_PerfRawData_PerfProc_Process.IDProcess = Win32_Process.ProcessId"),
ViewSources
    {
    "Select * from Win32_PerfRawData_PerfProc_Process",
    "Select * from Win32_Process"
    },
ViewSpaces
    {
    "\\\\.\\root\\cimv2",
    "\\\\.\\root\\cimv2"
    },
dynamic, provider("MS_VIEW_INSTANCE_PROVIDER")]
class Join_Process
{
    [key,
    PropertySources{"Name",""}]
    string Name;

    [PropertySources{"PercentProcessorTime",""}]
    uint64 PercentProcessorTime;

    [PropertySources{"PercentUserTime",""}]
    uint64 PercentUserTime;

    [PropertySources{"PercentPrivilegedTime",""}]
    uint64 PercentPrivilegedTime;

    [PropertySources{"VirtualBytesPeak",""}]
    uint64 VirtualBytesPeak;

    [PropertySources{"VirtualBytes",""}]
    uint64 VirtualBytes;

    [PropertySources{"PageFaultsPersec",""}]
    uint32 PageFaultsPersec;

    [PropertySources{"PageFileBytesPeak",""}]
    uint64 PageFileBytesPeak;

    [PropertySources{"PageFileBytes",""}]
    uint64 PageFileBytes;

    [PropertySources{"PrivateBytes",""}]
    uint64 PrivateBytes;

    [PropertySources{"ThreadCount",""}]
    uint32 ThreadCount;

    [PropertySources{"PriorityBase",""}]
    uint32 PriorityBase;

    [PropertySources{"ElapsedTime",""}]
    uint64 ElapsedTime;

    [key,
    PropertySources{"IDProcess","ProcessId"}]
    uint32 IDProcess;

    [PropertySources{"CreatingProcessID",""}]
    uint32 CreatingProcessID;

    [PropertySources{"HandleCount",""}]
    uint32 HandleCount;

    [PropertySources{"IOReadOperationsPersec",""}]
    uint64 IOReadOperationsPersec;

    [PropertySources{"IOWriteOperationsPersec",""}]
    uint64 IOWriteOperationsPersec;

    [PropertySources{"IODataOperationsPersec",""}]
    uint64 IODataOperationsPersec;

    [PropertySources{"IOOtherOperationsPersec",""}]
    uint64 IOOtherOperationsPersec;

    [PropertySources{"IOReadBytesPersec",""}]
    uint64 IOReadBytesPersec;

    [PropertySources{"IOWriteBytesPersec",""}]
    uint64 IOWriteBytesPersec;

    [PropertySources{"IODataBytesPersec",""}]
    uint64 IODataBytesPersec;

    [PropertySources{"IOOtherBytesPersec",""}]
    uint64 IOOtherBytesPersec;

    [PropertySources{"","ExecutablePath"}]
    string ExecutablePath;

    [PropertySources{"","ExecutionState"}]
    uint16 ExecutionState;

    [PropertySources{"","MaximumWorkingSetSize"}]
    uint32 MaximumWorkingSetSize;

    [PropertySources{"","MinimumWorkingSetSize"}]
    uint32 MinimumWorkingSetSize;

    [PropertySources{"","PeakWorkingSetSize"}]
    uint32 PeakWorkingSetSize;

    [PropertySources{"","QuotaNonPagedPoolUsage"}]
    uint32 QuotaNonPagedPoolUsage;

    [PropertySources{"","QuotaPagedPoolUsage"}]
    uint32 QuotaPagedPoolUsage;

    [PropertySources{"","QuotaPeakNonPagedPoolUsage"}]
    uint32 QuotaPeakNonPagedPoolUsage;

    [PropertySources{"","QuotaPeakPagedPoolUsage"}]
    uint32 QuotaPeakPagedPoolUsage;

    [PropertySources{"","WindowsVersion"}]
    string WindowsVersion;

    [PropertySources{"","SessionId"}]
    uint32 SessionId;
};

//===================================================================
//  JOIN CASE3
//  The following class creates a new class by combining process
//  information with the file information associated to the process
//  executable file.
//  NOTE: This class uses the EnumerateClasses qualifier as
//  enumerating files is far more expensive than enumerating
//  processes. Other interesting points are that the select statement
//  for the datafile names properties of interest only and the query
//  for processes asks only for those processes which have a file
//  path. Since getting all properties for a datafile is expensive
//  the Win32 provider will optimize where possible. It is a good idea //  to scope queries as much as possible to allow providers to
//  optimize where possible.
//===================================================================
[JoinOn("CIM_DataFile.Name = Win32_Process.ExecutablePath"),
EnumerateClasses{"Win32_Process"},
ViewSources
    {
    "Select Name, Compressed, Readable, Writeable, FileSize from CIM_DataFile",
    "Select * from Win32_Process where ExecutablePath <> NULL"
    },
ViewSpaces
    {
    "\\\\.\\root\\cimv2",
    "\\\\.\\root\\cimv2"
    },
dynamic, provider("MS_VIEW_INSTANCE_PROVIDER")]
class Join_ProcessWithFileInfo
{
    [PropertySources{"Compressed",""}]
    boolean FileCompressed;

    [PropertySources{"Readable",""}]
    boolean FileReadable;

    [PropertySources{"FileSize",""}]
    uint64 FileSize;

    [PropertySources{"Writeable",""}]
    boolean FileWriteable;

    [key,
    PropertySources{"Name","ExecutablePath"}]
    string FileName;

    [key,
    PropertySources{"","Handle"}]
    string ProcessHandle;

    [PropertySources{"","Priority"}]
    uint32 ProcessPriority;

    [PropertySources{"","MaximumWorkingSetSize"}]
    uint32 ProcessMaximumWorkingSetSize;

    [PropertySources{"","MinimumWorkingSetSize"}]
    uint32 ProcessMinimumWorkingSetSize;

    [PropertySources{"","PageFaults"}]
    uint32 ProcessPageFaults;

    [PropertySources{"","PageFileUsage"}]
    uint32 ProcessPageFileUsage;

    [PropertySources{"","PeakPageFileUsage"}]
    uint32 ProcessPeakPageFileUsage;

    [PropertySources{"","PeakWorkingSetSize"}]
    uint32 ProcessPeakWorkingSetSize;

    [PropertySources{"","QuotaNonPagedPoolUsage"}]
    uint32 ProcessQuotaNonPagedPoolUsage;

    [PropertySources{"","QuotaPagedPoolUsage"}]
    uint32 ProcessQuotaPagedPoolUsage;

    [PropertySources{"","QuotaPeakNonPagedPoolUsage"}]
    uint32 ProcessQuotaPeakNonPagedPoolUsage;

    [PropertySources{"","QuotaPeakPagedPoolUsage"}]
    uint32 ProcessQuotaPeakPagedPoolUsage;

    [PropertySources{"","WindowsVersion"}]
    string ProcessWindowsVersion;

    [PropertySources{"","ThreadCount"}]
    uint32 ProcessThreadCount;

    [PropertySources{"","HandleCount"}]
    uint32 ProcessHandleCount;

    [PropertySources{"","ParentProcessId"}]
    uint32 ProcessParentProcessId;

    [PropertySources{"","SessionId"}]
    uint32 ProcessSessionId;

    [PropertySources{"","PrivatePageCount"}]
    uint64 ProcessPrivatePageCount;

    [PropertySources{"","PeakVirtualSize"}]
    uint64 ProcessPeakVirtualSize;

    [PropertySources{"","VirtualSize"}]
    uint64 ProcessVirtualSize;

    [PropertySources{"","ReadOperationCount"}]
    uint64 ProcessReadOperationCount;

    [PropertySources{"","WriteOperationCount"}]
    uint64 ProcessWriteOperationCount;

    [PropertySources{"","OtherOperationCount"}]
    uint64 ProcessOtherOperationCount;

    [PropertySources{"","ReadTransferCount"}]
    uint64 ProcessReadTransferCount;

    [PropertySources{"","WriteTransferCount"}]
    uint64 ProcessWriteTransferCount;

    [PropertySources{"","OtherTransferCount"}]
    uint64 ProcessOtherTransferCount;

    [PropertySources{"","ExecutionState"}]
    uint16 ProcessExecutionState;

    [PropertySources{"","WorkingSetSize"}]
    uint64 ProcessWorkingSetSize;
};

//===================================================================
//  JOIN CASE4
//  The following classes create a new class by combining
//  connection information with the logical disk information.
//  NOTE: This class uses the PostJoinFilter qualifier.
//  The PostJoinFilter allows the results to be filtered by comparing
//  properties in the view class which allows properties in different
//  source classes to be validated together.
//===================================================================
[JoinOn("Win32_LogicalDisk.DeviceID = Win32_NetworkConnection.LocalName"),
PostJoinFilter("Select * from Join_DiskConnectionAlert where "
                "((DiskFreeSpace < 500000000) AND (ConnectionState = \"Connected\")) OR  "
                "ConnectionState <> \"Connected\""),
ViewSources
    {
    "Select * from Win32_LogicalDisk",
    "Select * from Win32_NetworkConnection where LocalName <> NULL"
    },
ViewSpaces
    {
    "\\\\.\\root\\cimv2",
    "\\\\.\\root\\cimv2"
    },
dynamic, provider("MS_VIEW_INSTANCE_PROVIDER")]
class Join_DiskConnectionAlert
{
    [key, PropertySources{"DeviceID","LocalName"}]
    string Name;

    [PropertySources{"Compressed",""}]
    boolean DiskCompressed;

    [PropertySources{"Description",""}]
    string DiskDescription;

    [PropertySources{"DriveType",""}]
    uint32 DiskDriveType;

    [PropertySources{"FileSystem",""}]
    string DiskFileSystem;

    [PropertySources{"FreeSpace",""}]
    uint64 DiskFreeSpace;

    [PropertySources{"MaximumComponentLength",""}]
    uint32 DiskMaximumComponentLength;

    [PropertySources{"MediaType",""}]
    uint32 DiskMediaType;

    [PropertySources{"ProviderName",""}]
    string DiskProviderName;

    [PropertySources{"Size",""}]
    uint64 DiskSize;

    [PropertySources{"SupportsFileBasedCompression",""}]
    boolean DiskSupportsFileBasedCompression;

    [PropertySources{"VolumeName",""}]
    string DiskVolumeName;

    [PropertySources{"VolumeSerialNumber",""}]
    string DiskVolumeSerialNumber;

    [key, PropertySources{"","Name"}]
    string Moniker;

    [PropertySources{"","Comment"}]
    string ConnectionComment;

    [PropertySources{"","ConnectionState"}]
    string ConnectionState;

    [PropertySources{"","ConnectionType"}]
    string ConnectionType;

    [PropertySources{"","DisplayType"}]
    string ConnectionDisplayType;

    [PropertySources{"","Persistent"}]
    boolean IsConnectionPersistent;

    [PropertySources{"","ProviderName"}]
    string ConnectionProviderName;

    [PropertySources{"","RemoteName"}]
    string ConnectionRemoteName;

    [PropertySources{"","RemotePath"}]
    string ConnectionRemotePath;

    [PropertySources{"","ResourceType"}]
    string ConnectionResourceType;

    [PropertySources{"","Status"}]
    string ConnectionStatus;

    [PropertySources{"","UserName"}]
    string ConnectionUserName;
};

[JoinOn("Win32_LogicalDisk.DeviceID = Win32_NetworkConnection.LocalName"),
PostJoinFilter("Select * from Join_DiskConnectionOK where "
                "(DiskFreeSpace >= 500000000) AND (ConnectionState = \"Connected\")"),
ViewSources
    {
    "Select * from Win32_LogicalDisk",
    "Select * from Win32_NetworkConnection where LocalName <> NULL"
    },
ViewSpaces
    {
    "\\\\.\\root\\cimv2",
    "\\\\.\\root\\cimv2"
    },
dynamic, provider("MS_VIEW_INSTANCE_PROVIDER")]
class Join_DiskConnectionOK
{
    [key, PropertySources{"DeviceID","LocalName"}]
    string Name;

    [PropertySources{"Compressed",""}]
    boolean DiskCompressed;

    [PropertySources{"Description",""}]
    string DiskDescription;

    [PropertySources{"DriveType",""}]
    uint32 DiskDriveType;

    [PropertySources{"FileSystem",""}]
    string DiskFileSystem;

    [PropertySources{"FreeSpace",""}]
    uint64 DiskFreeSpace;

    [PropertySources{"MaximumComponentLength",""}]
    uint32 DiskMaximumComponentLength;

    [PropertySources{"MediaType",""}]
    uint32 DiskMediaType;

    [PropertySources{"ProviderName",""}]
    string DiskProviderName;

    [PropertySources{"Size",""}]
    uint64 DiskSize;

    [PropertySources{"SupportsFileBasedCompression",""}]
    boolean DiskSupportsFileBasedCompression;

    [PropertySources{"VolumeName",""}]
    string DiskVolumeName;

    [PropertySources{"VolumeSerialNumber",""}]
    string DiskVolumeSerialNumber;

    [key, PropertySources{"","Name"}]
    string Moniker;

    [PropertySources{"","Comment"}]
    string ConnectionComment;

    [PropertySources{"","ConnectionState"}]
    string ConnectionState;

    [PropertySources{"","ConnectionType"}]
    string ConnectionType;

    [PropertySources{"","DisplayType"}]
    string ConnectionDisplayType;

    [PropertySources{"","Persistent"}]
    boolean IsConnectionPersistent;

    [PropertySources{"","ProviderName"}]
    string ConnectionProviderName;

    [PropertySources{"","RemoteName"}]
    string ConnectionRemoteName;

    [PropertySources{"","RemotePath"}]
    string ConnectionRemotePath;

    [PropertySources{"","ResourceType"}]
    string ConnectionResourceType;

    [PropertySources{"","Status"}]
    string ConnectionStatus;

    [PropertySources{"","UserName"}]
    string ConnectionUserName;
};


Creating a Union View Class

[This is preliminary documentation and subject to change.]

The following code example:

  • Registers the View Provider in the Root\Default namespace.
  • Creates test namespaces called LocalNameSpace and RemoteNameSpace.
  • Defines and creates instances of two classes in the two test namespaces.
  • Defines a union view class for these two classes and stores it in the Root\Default namespace.
#pragma namespace("\\\\.\\root")

instance of __Namespace
{
    Name = "RemoteNameSpace" ;
} ;

instance of __Namespace
{
    Name = "LocalNameSpace" ;
} ;

#pragma namespace("\\\\.\\root\\default")

instance of __Win32Provider as $DataProv
{
    Name = "MS_VIEW_INSTANCE_PROVIDER";
    ClsId = "{AA70DDF4-E11C-11D1-ABB0-00C04FD9159E}";
    ImpersonationLevel = 1;
    PerUserInitialization = "True";

};

instance of __InstanceProviderRegistration
{
    Provider = $DataProv;
    SupportsPut = True;
    SupportsGet = True;
    SupportsDelete = True;
    SupportsEnumeration = True;
    QuerySupportLevels = {"WQL:UnarySelect"};
};

#pragma namespace("\\\\.\\root\\LocalNameSpace")

Class LocalDisk
{
    String Description;
    [key] String DeviceID;
    String FileSystem;
    uint64 FreeSpace;
    String VolumeName;
};

Instance of LocalDisk
{
    Description = "3 1/2 Inch Floppy Drive";
    DeviceID = "A:";
    FileSystem = "FAT";
    FreeSpace = 1246720;
    VolumeName = "PKBACK# 002";
};

instance of LocalDisk
{
    Description = "Local Fixed Disk";
    DeviceID = "C:";
    FileSystem = "FAT";
    FreeSpace = 582778880;
    VolumeName = "MyComputer";
};

#pragma namespace("\\\\.\\root\\RemoteNameSpace")

Class RemoteDisk
{
    String Description;
    [key] String DeviceID;
    String FileSystem;
    uint64 FreeSpace;
    String VolumeName;
};

Instance of RemoteDisk
{
    Description = "3 1/2 Inch Floppy Drive";
    DeviceID = "A:";
    FileSystem = "FAT";
    FreeSpace = 60928;
    VolumeName = "MyComputer2";
};

instance of RemoteDisk
{
    Description = "Local Fixed Disk";
    DeviceID = "C:";
    FileSystem = "NTFS";
    FreeSpace = 29294592;
    VolumeName = "A_MyComputer";
};

#pragma namespace("\\\\.\\root\\default")

[Union, ViewSources{"Select Description, DeviceID, __Namespace, FileSystem, FreeSpace, VolumeName From LocalDisk", "Select Description, DeviceID, __Namespace, FileSystem, FreeSpace, VolumeName From LocalDisk"},
ViewSpaces{"\\\\.\\root\\LocalNamespace", "\\\\.\\root\\RemoteNamespace"}, dynamic: ToInstance, provider("MS_VIEW_INSTANCE_PROVIDER")]
class UnionOfDrives

{
    [PropertySources{"Description", "Description"}] string des;
    [PropertySources{"DeviceID", "DeviceID"}, key] String did;
    [PropertySources{"__Namespace", "__Namespace"}, key] String KEYID;
    [PropertySources{"FileSystem", "FileSystem"}] String fsystem ;
    [PropertySources{"FreeSpace", "FreeSpace"}] uint64 fspace;
    [PropertySources{"VolumeName", "VolumeName"}] String vname;
};


Union View Example

[This is preliminary documentation and subject to change.]

The following example demonstrates several union view classes. Copy this MOF code to a text file and compile it with the MOF compiler. You can view the resulting classes in the root\sample_views namespace using WMI CIM Studio or WMI Object Browser.

////////////////////////////////////////////////////////////////
//                                                            //
//  Purpose: This sample MOF file demonstrates union views    //
//           and methods                                      //
//                                                            //
////////////////////////////////////////////////////////////////

#pragma namespace("\\\\.\\root")

instance of __namespace
{
    Name = "sample_views";
};

#pragma namespace("\\\\.\\root\\sample_views")

//**************************************************************//
//                                                              //
//  The following three instances register the view provider    //
//  in the current namespace                                    //
//                                                              //
//**************************************************************//

instance of __Win32Provider as $DataProv
{
    Name = "MS_VIEW_INSTANCE_PROVIDER";
    ClsId = "{AA70DDF4-E11C-11D1-ABB0-00C04FD9159E}";
    ImpersonationLevel = 1;
    PerUserInitialization = "True";
};

instance of __InstanceProviderRegistration
{
    Provider = $DataProv;
    SupportsPut = True;
    SupportsGet = True;
    SupportsDelete = True;
    SupportsEnumeration = True;
    QuerySupportLevels = {"WQL:UnarySelect"};
};

instance of __MethodProviderRegistration
{
    Provider = $DataProv;
};

//*******************************************************************
//
//  The following classes demonstrate unions of classes defined
//  in multiple namespaces
//
//  In these cases, a source system property is added as a key to
//  maintain uniqueness.
//
//*******************************************************************

//===================================================================
//  UNION CASE1
//  In this case, the namespaces are on different machines
//  (supported on Windows 2000 only).
//====================================================================

[union,
ViewSources {"Select * from Win32_OperatingSystem"},
    ViewSpaces {"\\\\.\\root\\cimv2::\\\\MACHINE1\\root\\cimv2"},
    dynamic, provider("MS_VIEW_INSTANCE_PROVIDER")
    ]
class Union_OS
{
    [key, PropertySources{"Name"}]
    string Name;

    [key, PropertySources{"__Server"}]
    string Server;

    [PropertySources{"Version"}]
    string Version;

    [PropertySources{"BuildNumber"}]
    string BuildNumber;
};

//===================================================================
//  UNION CASE2
//  In this case, the namespaces are on the same machine
//  (supported on all platforms).
//===================================================================

[union,
ViewSources {"Select * from __Win32Provider"},
    ViewSpaces {"\\\\.\\root\\cimv2::\\\\.\\root\\wmi::\\\\.\\root\\snmp\\localhost::\\\\.\\root\\directory\\ldap"},
    dynamic, provider("MS_VIEW_INSTANCE_PROVIDER")
    ]
class Union_ProvidersOnThisMachine
{
    [key, PropertySources{"Name"}]
    string Name;

    [key, PropertySources{"__Namespace"}]
    string Location;

    [PropertySources{"CLSID"}]
    string ClassIdentifier;

    [PropertySources{"PerUserInitialization"}]
    boolean PerUserInitialization;
};

//*******************************************************************
//
//  The following classes demonstrate unions of similar classes.
//  The source classes must have the same key structure.
//
//*******************************************************************

//===================================================================
//  UNION CASE3
//  In this case, the namespaces are on the same machine
//  (supported on all platforms).
//  This class lists several types of drives supported by
//  the Win32 Provider.
//===================================================================

[
    union,
    ViewSources {
                "Select * from Win32_DiskDrive",
                "Select * from Win32_CDRomDrive",
                "Select * from Win32_FloppyDrive"
                },
    ViewSpaces {
                "\\\\.\\root\\cimv2",
                "\\\\.\\root\\cimv2",
                "\\\\.\\root\\cimv2"
                },
    dynamic, provider("MS_VIEW_INSTANCE_PROVIDER")
]
class Union_PhysicalDrives
{
    [key, PropertySources{"DeviceId", "DeviceId", "DeviceId"}]
    string DeviceIdentifier;

    [PropertySources{"MediaType", "MediaType", "Caption"}]
    string Type;

    [PropertySources{"Partitions", "", ""}]
    uint32 NumberOfPartitions;

    [PropertySources{"", "MediaLoaded", ""}]
    boolean DiscLoaded;

    [PropertySources{"Caption", "Name", "Name"}]
    string Name;

};

//===================================================================
//  UNION CASE4
//  In this case, remote namespaces are used.
//  This class lists several types of drives supported by
//  the Win32 Provider on the local machine and
//  a machine named Machine1
//===================================================================

[
    union,
    ViewSources {
                "Select * from Win32_DiskDrive",
                "Select * from Win32_CDRomDrive",
                "Select * from Win32_FloppyDrive"
                },
    ViewSpaces {
                "\\\\.\\root\\cimv2::\\\\Machine1\\root\\cimv2",
                "\\\\.\\root\\cimv2::\\\\Machine1\\root\\cimv2",
                "\\\\.\\root\\cimv2::\\\\Machine1\\root\\cimv2"
                },
    dynamic, provider("MS_VIEW_INSTANCE_PROVIDER")
]
class Union_PhysicalDrivesOnMyMachines
{
    [key, PropertySources{"DeviceId", "DeviceId", "DeviceId"}]
    string DeviceIdentifier;

    [PropertySources{"MediaType", "MediaType", "Caption"}]
    string Type;

    [PropertySources{"Partitions", "", ""}]
    uint32 NumberOfPartitions;

    [PropertySources{"", "MediaLoaded", ""}]
    boolean DiscLoaded;

    [PropertySources{"Caption", "Name", "Name"}]
    string Name;

};


Union Views and Methods

[This is preliminary documentation and subject to change.]

You can include methods along with properties in union views. Methods are defined with the MethodSource qualifier and are only supported with union views.

The following code example:

  • Creates a namespace called WMI.
  • Registers the View Provider in the Root\WMI namespace as an instance and method provider.
  • Defines a union view class that contains a property and two methods from the Win32_NTEventlogFile class from another namespace.
////////////////////////////////////////////////////////////////
//                                                            //
//  Purpose: This sample MOF file demonstrates a union view   //
//           with methods from the class Win32_NTEventlogFile //
//           in the \Root\cimv2 namespace.                    //
////////////////////////////////////////////////////////////////

#pragma namespace("\\\\.\\root")

instance of __Namespace
{
    Name = "Test" ;
} ;

#pragma namespace("\\\\.\\root\\Test")

instance of __Win32Provider as $DataProv
{
    Name = "MS_VIEW_INSTANCE_PROVIDER";
    ClsId = "{AA70DDF4-E11C-11D1-ABB0-00C04FD9159E}";
    ImpersonationLevel = 1;
    PerUserInitialization = "True";

};

instance of __InstanceProviderRegistration
{
    Provider = $DataProv;
    SupportsPut = True;
    SupportsGet = True;
    SupportsDelete = True;
    SupportsEnumeration = True;
    QuerySupportLevels = {"WQL:UnarySelect"};
};

instance of __MethodProviderRegistration
{
    Provider = $DataProv;
};

[Union,
ViewSources {"Select * From Win32_NTEventlogFile"},
    ViewSpaces ("\\\\.\\root\\cimv2"),
    dynamic, provider("MS_VIEW_INSTANCE_PROVIDER")
]
class View_NTEventlogFile
{
[
key, PropertySources{"Name"}
]    string    VName;
    //Methods
[implemented, MethodSource{"ClearEventlog"}]
    uint32    VClearEventlog([in] string ArchiveFileName);

[implemented, MethodSource{"BackupEventlog"}]
    uint32    VBackupEventlog([in] string ArchiveFileName);
};

Union Views and Methods Example Number 2

//===================================================================
//  Union / method example 2
//  Methods are only supported on union views.
//  Furthermore, the signature of the method has to match that
//  of the source exactly. The easiest way of ensuring this is
//  to copy the method signature from the MOF file
//  and pasting it into the view class.
//===================================================================

#pragma namespace("\\\\.\\root")

instance of __Namespace
{
    Name = "Test" ;
} ;

#pragma namespace("\\\\.\\root\\Test")

instance of __Win32Provider as $DataProv
{
    Name = "MS_VIEW_INSTANCE_PROVIDER";
    ClsId = "{AA70DDF4-E11C-11D1-ABB0-00C04FD9159E}";
    ImpersonationLevel = 1;
    PerUserInitialization = "True";

};

instance of __InstanceProviderRegistration
{
    Provider = $DataProv;
    SupportsPut = True;
    SupportsGet = True;
    SupportsDelete = True;
    SupportsEnumeration = True;
    QuerySupportLevels = {"WQL:UnarySelect"};
};

instance of __MethodProviderRegistration
{
    Provider = $DataProv;
};

[
Union,
ViewSources {"Select * From Win32_OperatingSystem"},
ViewSpaces {"\\\\.\\root\\cimv2"},
dynamic, provider("MS_VIEW_INSTANCE_PROVIDER")
]
class Union_OSWithMethods
{
    [key, PropertySources{"Name"}]
    string Name;

    [key, PropertySources{"__Server"}]
    string Server;

    [PropertySources{"Version"}]
    string Version;

    [PropertySources{"BuildNumber"}]
    string BuildNumber;

//Methods
    [implemented,
    MethodSource{"Reboot"}
    ]
    uint32 Reboot();

    [implemented, Privileges{"SeShutdownPrivilege"},
    MethodSource{"Shutdown"}
    ]
    uint32 Shutdown();

    [implemented: ToSubClass,
    Privileges{"SeShutdownPrivilege"}: ToSubClass,
    MappingStrings
    {"Win32API|System Shutdown Functions|ExitWindowsEx"}: ToSubClass,
    MethodSource{"Win32Shutdown"}
    ]
    uint32 Win32Shutdown(
    [in, MappingStrings{"Win32API|System Shutdown Functions|ExitWindowsEx"}: ToSubClass,
    BitMap{"0x00000000", "0x00000001", "0x00000002", "0x00000004", "0x00000008"}: ToSubClass] sint32 Flags,
    [in, MappingStrings{"Win32API|System Shutdown Functions|ExitWindowsEx"}: ToSubClass] sint32 Reserved = 0);

};


Creating an Association View Class

[This is preliminary documentation and subject to change.]

The following examples demonstrate how to create association view classes. The first section of this MOF file registers the view provider as an instance provider in a new namespace that is created.

///////////////////////////////////////////////////////////////////
//                                                               //
//  Purpose: This sample MOF file demonstrates association views //
//  of Win32_SystemOperatingSystem, Win32_OperatingSystem and    //
//  Win32_ComputerSystem                                         //
///////////////////////////////////////////////////////////////////

#pragma namespace("\\\\.\\root")

instance of __namespace
{
    Name = "sample_views";
};

#pragma namespace("\\\\.\\root\\sample_views")

instance of __Win32Provider as $DataProv
{
    Name = "MS_VIEW_INSTANCE_PROVIDER";
    ClsId = "{AA70DDF4-E11C-11D1-ABB0-00C04FD9159E}";
    ImpersonationLevel = 1;
    PerUserInitialization = "True";
};

instance of __InstanceProviderRegistration
{
    Provider = $DataProv;
    SupportsPut = True;
    SupportsGet = True;
    SupportsDelete = True;
    SupportsEnumeration = True;
    QuerySupportLevels = {"WQL:UnarySelect"};
};

//*******************************************************************
//
//  The following classes demonstrate views of associations
//
//*******************************************************************

//  ASSOCIATION CASE1
//  The following class is a view of the CIMv2 class
//  Win32_SystemOperatingSystem association. It is practically
//  useless as both end points are in other namespaces and
//  Associators/References queries cannot be used across namespaces.
//
//  This view uses the direct qualifier to identify a reference
//  property that is not to be mapped to a view reference.
//===================================================================
[
Association,
ViewSources {"Select * From Win32_SystemOperatingSystem"},
ViewSpaces {"\\\\.\\root\\cimv2"},
dynamic, provider("MS_VIEW_INSTANCE_PROVIDER")
]
class Association_SystemOperatingSystem
{
    [Direct, key, PropertySources{"GroupComponent"}]
    Win32_ComputerSystem ref Computer;

    [Direct, key, PropertySources{"PartComponent"}]
    Win32_OperatingSystem ref OperatingSystem;
};

//  ASSOCIATION CASE2
//  The following class is a view of the CIMv2 class
//  Win32_SystemOperatingSystem association. This version is a
//  little more useful. In this case, Win32_OperatingSystem is
//  mapped into the sample namespace and Win32_ComputerSystem is not.
//  However, this view association allows the view operating system to
//  be associated to the Win32_ComputerSystem. And performing an
//  Associators of the view operating system
//  instance will return the Win32_ComputerSystem.
//
//  Again, this view uses the Direct qualifier to identify a reference
//  property that is not to be mapped to a view reference.
//
//  NOTE: First the view operating system is shown, then the view association.
//===================================================================
[union,
ViewSources {"Select * from Win32_OperatingSystem"},
    ViewSpaces {"\\\\.\\root\\cimv2"},
    dynamic, provider("MS_VIEW_INSTANCE_PROVIDER")
]
class Union_OS_For_AssociationExample
{
    [key, PropertySources{"Name"}]
    string Name;

    [PropertySources{"Version"}]
    string Version;

    [PropertySources{"BuildNumber"}]
    string BuildNumber;
};

[
Association,
ViewSources {"Select * From Win32_SystemOperatingSystem"},
ViewSpaces {"\\\\.\\root\\cimv2"},
dynamic, provider("MS_VIEW_INSTANCE_PROVIDER")
]
class Association_SystemViewOperatingSystem
{
    [Direct, key, PropertySources{"GroupComponent"}]
    Win32_ComputerSystem ref Computer;

    [key, PropertySources{"PartComponent"}]
    Union_OS_For_AssociationExample ref OperatingSystem;
};

//  ASSOCIATION CASE3
//  The following class is a view of the CIMv2 class
//  Win32_SystemOperatingSystem association. In this case,
//  Win32_OperatingSystem and Win32_ComputerSystem
//  are mapped into the sample namespace. However, this view
//  association allows the view operating system to be associated
//  to the view computer system.
//  Performing an ASSOCIATORS OF the view operating system instance
//  will return the view computer system. Furthermore, performing an
//  ASSOCIATORS OF the view computer system instance will return the
//  view operating system.
//
//  This view makes no use of the Direct qualifier.
//
//  NOTE: First the view computer system is shown, then
//  the view association.
//===================================================================
[
Union,
ViewSources {"Select * From Win32_ComputerSystem"},
ViewSpaces {"\\\\.\\root\\cimv2"},
dynamic, provider("MS_VIEW_INSTANCE_PROVIDER")
]
class Union_ComputerSystem_For_AssociationExample
{
    [key,PropertySources{"Name"}]
    string Name;

    [PropertySources{"Domain"}]
    string Domain;

    [PropertySources{"Manufacturer"}]
    string Manufacturer;

    [PropertySources{"Model"}]
    string Model;

    [PropertySources{"NumberOfProcessors"}]
    uint32 NumberOfProcessors;
};

[
Association,
ViewSources {"Select * From Win32_SystemOperatingSystem"},
ViewSpaces {"\\\\.\\root\\cimv2"},
dynamic, provider("MS_VIEW_INSTANCE_PROVIDER")
]
class Association_ViewSystemViewOperatingSystem
{
    [key, PropertySources{"GroupComponent"}]
    Union_ComputerSystem_For_AssociationExample ref Computer;

    [key, PropertySources{"PartComponent"}]

    Union_OS_For_AssociationExample ref OperatingSystem;
};


Provider Framework

The provider framework is a set of classes that can be used to create a Windows Management Instrumentation (WMI) instance and/or method provider. The resulting provider is dynamic, supplying its instances on demand rather than storing them in the Common Information Model (CIM) repository. Providers created with the provider framework are modeled as pull providers.

Using the framework classes and the methods that they expose can cut development time significantly because they eliminate the need to become proficient with the Component Object Model (COM). All of the communication with COM is handled by the provider framework. The provider framework is a layer between the providers and the CIM Object Manager as shown in the following diagram:

Developers can create a provider with the framework either by manually writing code or taking advantage of an application wizard called the Provider Code Generator. The Provider Code Generator is included with the WMI CIM Studio application. The Provider Code Generator produces several files that can be compiled and built after a small amount of customization. The end result is an operational instance and method provider for one or more classes. The Provider Code Generator supplies stub implementations of all required functions and methods in American National Standards Institute (ANSI)-based C++ and handles provider registration. Classes defined by the Provider Code Generator to expose these implementations derive from classes defined by the provider framework. The provider framework defines several classes to bridge the gap between the framework provider and WMI.

Creating a framework provider with the Provider Code Generator is fast and easy. After selecting a class or classes to support, the Provider Code Generator requests the name and location for the output files and the name for the provider. With that information, the Provider Code Generator produces several output files that can be compiled and built to produce a working provider.

For a complete working example of a framework provider, see the CReindeerProv class in the WMI SDK \Samples\Vc\FrameworkProv folder.


Provider Code Generator

The Provider Code Generator is a wizard that is available in the Windows Management Instrumentation (WMI) Common Information Model (CIM) Studio application included with the WMI SDK. The Provider Code Generator uses the functions of the provider framework to produce a customizable instance provider that can be fully functional with minimum effort on the developer's part. The provider framework frees developers from having to be knowledgeable about Component Object Model (COM) and allows them to focus on the features that are specific to their instance providers.

The Provider Code Generator produces several files. There are C++ source and header files for each class supported by the new provider, a definition file, a Managed Object Format (MOF) file that is used for registration, a makefile for building the provider, and a file that contains the entry points for the provider's DLL. These files make calls to the provider framework to handle registration, initialization, loading, and unloading.

  20. To create an instance provider with the Provider Code Generator, start by selecting one or more non-system classes in the left pane and click the appropriate button on the WMI CIM Studio toolbar. A welcoming screen appears. The Provider Code Generator produces code based on the selected classes. Click Next, and the following screen appears:

  20. The class or classes that were selected appear in the area on the left side of the screen. On the top of the right side of the screen are text entry boxes for the base file name, C++ class name, and description. The base file name is the name used for the source and header files that contain the instance provider's implementation of IWbemServices for the class. Each class has its own set of source and header files. The C++ class name is the name of the class that exposes the IWbemServices implementation.
  21. The Provider Code Generator assigns a default base file name and C++ class name based on the chosen class. The base file name is the same as the class name and the C++ class name is a "C" followed by the class name. For example, if Win32_Share is selected, the base file name is Win32_Share and the C++ class name is CWin32_Share.
  22. The description field is optional and can be used to specify information about the class. There is no default value for the description field.
  23. The bottom of the right side of the screen lists properties. Each property has a corresponding check box that indicates whether the property is included with the new class. All of the local non-system properties for the class must be included. If the superclass defines properties that can be overridden, the check box labeled Override Inherited Properties can be selected. Once selected, all of the inherited properties are displayed. Selecting the check box next to an inherited property indicates to the Provider Code Generator that the property should be overridden in the class.
  24. Click the Next button on the bottom of the screen to continue. A second screen appears for specifying information about the new instance provider. There are text entry fields for the provider's name, a description, and a directory path. The Provider Code Generator automatically assigns the name NewProv for new providers; it can be changed to a name that is more meaningful.
  26. Like the class description, the provider description is optional and can be left blank.
  27. The directory path specifies the location for the files that are generated by the Provider Code Generator. The default path is the directory that contains the installation of the WMI SDK, typically "C:\Program Files\WBEM". If the output files should be saved in an alternate location, replace this default path.
  28. Click the Finish button when you have entered all of the necessary information. If one of the selected classes is currently handled by another provider, a warning message is displayed. The message presents the option of replacing the provider that is currently attached to this class with the new provider that's being generated. Clicking Yes replaces the provider qualifier on this class to point to the newly generated provider. Clicking No leaves the provider qualifier on the class as is, which means the class will continue to be provided by the previous provider, but the new provider files will still be generated


Provider Code Generator Files

The Provider Code Generator produces several types of files: C++ source files, header files, a DEF file, a Managed Object Format (MOF) file, and a makefile. If you need to modify these files, see the comments contained within each file. The following table specifies the naming convention for each of these files and describes their contents.

Provider Code Generator file | Description
Maindll.cpp | Contains code for the provider's DLL entry point and for initialization, registration, and shutdown. No modification is required unless you are writing multithreaded code. If so, you will want to uncomment the appropriate source lines generated in DllRegisterServer.
<provider name>.def | Standard definition file. No modification required.
<provider name>.mak | Makefile for compiling and building the provider. The LIB and INCLUDE environment variables are set to the appropriate provider framework directories when the Windows Management Instrumentation (WMI) SDK is installed..
<provider name>.mof | Contains the instances required to register the provider with WMI. Requires modification if the provider should be registered in a namespace other than the current one or the provider does not support one of the standard features.
<base file name>.cpp | Contains the provider's class implementation. Requires modification to customize the framework provider and support its specific features.
<base file name>.h | Contains the provider's class definition. Requires modification if the class supports any private data or member functions.


Provider Code Generator Maindll File

The Maindll.cpp file contains definitions of the globally unique identifier (GUID) and the class identifier (CLSID) for the framework provider DLL and implementations of the following standard functions.

Function | Description
DllGetClassObject | Called to create a new instance of the framework class CWbemGlueFactory.
DllCanUnloadNow | Called periodically to determine whether the provider DLL can be unloaded.
DllRegisterServer | Called to register the provider DLL as a COM server in the system registry.
DllUnregisterServer | Called to remove registry entries for the provider DLL.

The Maindll.cpp file will most likely not need to be changed. The framework provider may require additional registration or validation in the DllCanUnloadNow function.


Provider Code Generator Source and Header Files

For each class supported by the framework provider, the Provider Code Generator generates one source (.cpp) file and an associated header (.h) file. The header file defines the class that the framework provider supports; a class that derives from the framework provider class. The framework provider class supplies default implementations of many of the synchronous IWbemServices methods and a set of helper functions. The framework provider's class definition is set up to support a standard constructor and destructor and the following methods:

  • DeleteInstance
  • EnumerateInstances
  • ExecMethod
  • ExecQuery
  • GetObject
  • PutInstance

The source file contains implementations of the methods defined in the header file. This file contains "TO DO" labels with comments to identify where to place customization code. Also included for each method is a standard comment block that lists the name of the method, a brief description, a description of the input parameters, the valid return values, and comments.

The developer usually implements the GetObject and EnumerateInstances methods, because they will not work as written. The other methods are optional and may be deleted if unused. If the developer is writing a method-only provider for a static method, these two methods can be deleted as well.


Provider Code Generator MOF File

The Managed Object Format (MOF) file that is produced by the Provider Code Generator does not need to be changed, although it can be. The MOF file contains definitions of the three instances required for registration: __Win32Provider, __InstanceProviderRegistration, and __MethodProviderRegistration. Each of these instances have properties that are set to default values. Only the Name and Clsid properties of the __Win32Provider class are included in the MOF file. All of the other properties values are inherited.

The properties of the __InstanceProviderRegistration class specify whether various features are supported. The Provider Code Generator sets these properties as follows, specifying support for all possible instance provider operations:

instance of __InstanceProviderRegistration
{
    Provider = $P;
    SupportsGet = TRUE;
    SupportsPut = TRUE;
    SupportsDelete = TRUE;
    SupportsEnumeration = TRUE;
    QuerySupportLevels = {"WQL:UnarySelect"};
};

The WQL:UnarySelect value for the QuerySupportLevels property indicates that the provider supports query processing with the WQL SELECT statement only. WMI translates WQL statements such as ASSOCIATORS OF and REFERENCES OF into SELECT statements.

If the framework provider will not be supporting a particular feature, the MOF file should be modified. For example, if the provider does not support deleting instances, it should set SupportsDelete to FALSE. If WMI handles queries for the provider, QuerySupportLevels should be set to NULL. If you are not supporting the feature, delete it from the .mof, .h and .cpp files.


Compiling a Framework Provider

A framework provider created by the Provider Code Generator can be compiled using the .mak file that is automatically produced.

When building providers to work with the framework, see the .mak file in the FrameworkProv folder in the VC samples folder of the WMI SDK. In addition:

  • You must link with Msvcrt.lib (or Msvcrtd.lib for Debug builds). Ensure this by setting the /MD compiler switch. Failure to do this will result in either undefined symbols at link time, or stack and heap corruption at run time. In other words, you must never link with Libc.lib or Libcmt.lib.
  • For debug builds, compile as a multithreaded .dll debug configuration, and link with Framedyd.lib.
  • For release builds, compile as a multithreaded .dll configuration, and link with Framedyn.lib. Because release and debug memory allocators are different, never use Framedyd.lib in a release build or Framedyn.lib in a debug build.

Failure to link with Msvcrt.lib and Framedyd.lib (or Msvcrtd.lib and Framedyd.lib) will result in either undefined symbols at link time, or stack corruption at run time.

To build a manually created provider

  1. Create a new project of type win32 Dynamic-Link Library and add all .cpp and .h files created by the wizard to the project. (if you used the Provider wizard to generate framework code).
  2. Set the INCLUDE environment variable (or project setting) to the include directory of the Windows Management Instrumentation Software Development Kit (WMI SDK).
  3. Set the LIB environment variable (or project setting) to the lib directory of the WMI SDK.
  4. Include the FWCommon.h header file first in each added source file. The Provider Code Generator automatically places it first in the files that it generates.
  5. Link with Msvcrt.lib and Framedyn.lib. Failure to do this will result in either undefined symbols at link time, or stack corruption at run time.
  6. Build your project.

You may see the following warnings, which were moved from Level 3 to Level FWCommon.h:

  • C4275: Non DLL-interface classkey 'identifier' used as base for DLL-interface classkey 'identifier'
  • C4800: forcing bool variable to one or zero, possible performance loss
  • C4786: 'identifier' : identifier was truncated to 'number' characters in the debug information
  • C4251: 'identifier' : class 'type' needs to have dll-interface to export class 'type2'

Because these warnings have been suppressed in FWCommon.h by moving them to warning Level 4 will only be seen if the framework provider is compiled at warning Level 4.


Debugging a Framework Provider

You will find it much easier to debug a framework provider if you use the debug version of Framedyn.dll. The debug version is called Framedyd.dll and is installed with the WMI SDK. Since they differ in name, both the retail and the debug versions of the DLL can be loaded simultaneously.

There are a number of useful tidbits to know when debugging a framework provider.

When your provider is loaded, it is usually loaded as an in-process COM server by WinMgmt (see Out of Process Framework Providers). This means that the process you want to debug is WinMgmt.exe, and not the client application.

Under Windows NT, there are two ways to use the debugger against WinMgmt. You can either start the service and attach, or you can actually start WinMgmt under the debugger.

Under Windows 95/98, WinMgmt runs as a hidden process, but you can still attach to it, or start it under the debugger.

If you start WinMgmt under the debugger, make sure you add your provider under Project/Settings/Debug/Additional DLLs, otherwise you won't be able to set breakpoints in your code.

On Windows NT, if you start WinMgmt under the debugger, realize that you are running in a different security context than most customers will be using. Normally WinMgmt runs as Local System. Starting it under the debugger means that it is running under the context of the currently logged in user. Running as the currently logged in user also can cause differences when trying to attach remotely.

If you run WinMgmt as an executable file on NT, and it crashes (or you terminate it in the debugger), the WinMgmt service will not automatically start when you connect unless it has already terminated. You must let WinMgmt terminate normally or use the WinMgmt /RegServer command. There are two ways to have it terminate normally. If you have started WinMgmt with the /EXE switch, a window will appear for WinMgmt that has a Close option. You can also use the WinMgmt /Kill switch to shut it down.

Running WinMgmt within the debugger without specifying the /EXE switch will run in the same context as running it with the /EXE switch. You just won't get the window.

When WinMgmt is run as an executable, it temporarily disables the feature that allows the service to be automatically started. This avoids the problem of having two WinMgmts running at the same time. When the WinMgmt executable is shut down normally, it re-enables this feature. However, if you terminate WinMgmt in the debugger (or if WinMgmt crashes), this feature will not get re-enabled. This is not normally a problem when debugging, but is something to be aware of. You can re-enable this feature by either starting WinMgmt then shutting it down normally, or by using WinMgmt /RegServer.

When setting break points in your code, you might want to set them at all entry points. For example, if the client application makes a query call such as "SELECT * FROM Foo", WinMgmt may decide to call your EnumerateInstances function instead of your query function. This can lead to some serious head scratching when you see that instances are being sent back, but your breakpoint never gets hit.

The provider framework creates a log file in the wbem\logs directory named Framework.log. The detail of the logging is controlled by the registry key HKLM\software\Microsoft\wbem\cimom\logging. Valid values are 0 (no logging), 1 (error logging, default), and 2 (verbose). On Win2000, this can also be controlled through the MMC application. Turning logging to verbose and restarting WinMgmt will give much more detailed logging. Note that when the log file size hits the max size (HKLM\software\Microsoft\wbem\cimom\Log File Max Size), the log file is renamed from Framework.Log to Framework.Lo_.

If your provider is misregistered, it may not get called at all. Below are the steps that are taken to call your provider. Turn on logging (described above) and check the framework.log file to see if the framework is even being called. If it is, the problem is in steps 5-7, otherwise the problem is in steps 2-4.

  1. The client calls some function (such as ExecQuery) against a class.
  2. WinMgmt examines the class definition, checking to see if there is a 'Dynamic' qualifier, and a 'Provider' qualifier. For 'method only' classes, the 'Dynamic' qualifier is not needed. These values are set in the MOF file used to create the class. For more information, see the Reindeer class in the FrameworkProv sample that ships with the WMI SDK.
  3. WinMgmt takes the value of the 'Provider' qualifier, and looks in the __Win32Provider class for a provider with that name. Note that there is a __Win32Provider class in every namespace, but WinMgmt only looks in the namespace that the client is attached to. WinMgmt checks the properties on the __Win32Provider instance to see if the provider supports the requested operation. This instance is created in the MOF file used to create the class. See the __Win32Provider, __InstanceProviderRegistration, and __MethodProviderRegistration classes in the FrameworkProv sample for more information.
  4. Using the CLSID from the __Win32Provider instance, WinMgmt makes a COM call to the provider. COM determines what in-process server (dll) to load by looking at HKCR\clsid\<clsid>\InProcServer\(default) key. This is normally created by doing a RegSvr32 against your provider. Note that this DLL should NOT be on a network share, as WinMgmt normally runs as Local System and won't have access to network resources.
  5. The framework checks the security of the client. A client must have an impersonation level of either Impersonate or Delegate.
  6. The framework scans the list of classes known to it to locate the requested class. A provider adds itself to the list by declaring a static instance of itself where it specifies its class name and namespace. See the declaration of MyReindeerProvSet in the FrameworkProv sample. A common mistake here is to have the incorrect namespace specified in the static constructor for your class. Turn on logging (described above) and look for where your class is logged into the framework to see what namespace is being used.
  7. The framework then calls into the provider.

    If you are receiving heap corruptions and/or gp faults as soon as your provider is loaded, then most likely you have done one of two things.

    1. You are compiling your provider debug, but linking to the retail version of the framework (or vice versa).
    2. You are not linking to MSVCRT(D).dll.

Be aware that under certain circumstances, your provider can be called on multiple threads at the same time. So if you are stepping through a routine and suddenly find yourself somewhere else, it may be that you have switched to another thread.

Also be aware that GP faults are converted into C++ exceptions by the framework. If you are tracing through your code and suddenly jump into the framework, you may have caused an exception. In debug builds of the framework, these will give a STRUCTURED_EXCEPTION assert message. WBEM_E_PROVIDER_FAILURE is returned to the client application.

If you are running a client on computer A, and connecting to computer B, you would set up the debugger for the provider on computer B. The WinMgmt on computer A is not involved in any way in this session.


Error Handling for Framework Providers

Framework providers that call a provider framework method should return the error or status code that the method returns unless the provider can supply more detailed information. For example, if a call to CWbemProviderGlue::GetAllInstances returns WBEM_E_OUT_OF_MEMORY, the framework provider should return WBEM_E_OUT_OF_MEMORY.

Typically, when checking for errors, framework providers should use the SUCCEEDED and FAILED macros, rather than testing for specific error codes. Providers should test for specific error codes only if they can remedy the situation in some way. For example, if a provider is able to free memory, it is worth writing code to check for WBEM_E_OUT_OF_MEMORY.


Thrown Framework Errors

As a general rule, the framework only throws on catastrophic errors, for example, out of memory errors or general protection faults. Well designed providers should handle the possibility of thrown exceptions. Consider the following code:

CInstance *pInstance = NULL;

// Note that we don't check the return from CreateNewInstance.  If
// it's going to fail, it will throw.
pInstance.Attach(CreateNewInstance(pMethodContext));

// This code calls the CHString class.  The CHString class could
// throw an exception on out of memory
CHString sString (L"\\");
sString += szReallyLongString;

pInstance->SetCHString(L"Key", sString);

hr = Commit(pInstance);

return hr;

If the sString were to throw an exception, it would be trapped by the framework, which would return WBEM_E_OUT_OF_MEMORY to the client. If that happened, the pInstance returned from CreateNewInstance would never get released. There are several ways of dealing with this. Here is one:

CInstance *pInstance = NULL;

// Note that we don't check the return from CreateNewInstance.  If
// it's going to fail, it will throw.
pInstance = CreateNewInstance(pMethodContext);

try
{
// This code calls the CHString class.  The CHString class could
// throw an exception on out of memory
CHString sString (L"\\");
sString += szReallyLongString;

pInstance->SetCHString(L"Key", sString);

hr = pInstance->Commit();
}
catch (. . .)
{
    pInstance->Release();
      throw;
}

pInstance->Release();

return hr;

In this case, if sString throws an error, it is caught in the following catch block, which releases the newly created instance. The catch block then throws to the framework, which returns WBEM_E_OUT_OF_MEMORY to the client application. Note that we have changed from using Provider::Commit (which DOES free the instance pointer) to CInstance::Commit (which doesn't).

Generally speaking, you should plan on dealing with the possibility that almost anything will throw. Even if the code you are calling doesn't contain an actual throw statement, it could still get a general protection fault. Or it could call a routine which calls a routine which just got changed to use a CHString. So anytime you open, new, allocate or otherwise create something, you should make sure that it will be closed, deleted, or freed on an exception.

The framework currently throws three different types of exceptions:

  1. class CHeap_Exception, defined in provexce.h and thrown when a memory allocation or memory free fails.
  2. class CStructured_Exception, defined in provexce.h and thrown when a general protection fault of some type occurs.
  3. class CFramework_Exception, (defined in fwcommon.h and thrown when unrecoverable errors occur inside the framework.


Using Smart Pointers to Handle Thrown Exceptions

Here is another method for handling a thrown exception:

_COM_SMARTPTR_TYPEDEF(CInstance, __uuidof(CInstance));

CInstancePtr pInstance;

// Note that we don't check the return from CreateNewInstance.  If
// it's going to fail, it will throw.
pInstance = CreateNewInstance(pMethodContext);

// This code calls the CHString class.  The CHString class could
// throw an exception on out of memory
CHString sString (L"\\");
sString += szReallyLongString;

pInstance->SetCHString(L"Key", sString);

hr = pInstance->Commit();

return hr;

This illustrates the use of smart pointers. For more about this, see the documentation for the _com_ptr_t class in MSDN. Smart pointers take advantage of the fact that when an exception is thrown, the destructors for all C++ classes get called as the routine is exited. So, in the code above, if the CHString throws, the destructor for the CInstancePtr class is called, which releases the pointer. Likewise, the destructor is called when the routine exits, which is why there is no release at the end of the routine.

_com_ptr_t is one of a number of different smart pointer classes available. They all have their strengths and weaknesses. Choose the one that best matches your needs.


Upgrading Framework Providers

[This is preliminary documentation and subject to change.]

Backward compatibility is not supported when upgrading from WMI versions 1.1 or 1.2 to WMI version 1.5 or higher. Some of the changes will have no effect upon legacy code. Other changes will require changes in existing code. This document is provided to help you make a smooth and successful upgrade.

The following topics cover the changes that have been made to the framework provider:

  • CHString changes
  • TSTR and WSTR changes
  • Exception handling changes
  • Impersonation changes
  • GetObject changes
  • Deprecated function changes
  • WBEMTime and WBEMTimeSpan changes
  • Calling convention changes
  • Creating a Subclass

CHString Changes

CHString is now based upon Unicode rather than ANSI strings. This creates some incompatibilities with ANSI systems, most of which you will discover when you recompile your code. When passing a CHString to a function that requires an ANSI string parameter, you need to explicitly convert to an ANSI string. CHString has no LPCSTR cast. A related incompatibility arises when you use any function of the printf or scanf families, or CHString format. This incompatibility will not be apparent when you recompile your code. Consider the following code:

CHString str = "example1";
printf("%s\m", str);

Though the preceding code compiles without error or warning, if you are running on an ANSI system it does not generate the correct output (it generates a one-character string). Now consider the following code which fixes this problem:

CHString str = "example1";
#ifdef _UNICODE
  printf("%s\n", (LPCWSTR) str);
#else
  printf("%S\n", (LPCWSTR) str);
#endif

By compiling printf with a format string ("%S" or "%s") that is appropriate to your system you will get the expected output.

See CHString for some of the implications of this change.

TSTR and WSTR Changes

Many methods now take WSTR parameters instead of TSTR or CHString parameters.

These incompatibilities become apparent when you recompile your code. The following code passes a string constant to the function:

PInstance->SetCharSplat ("example1", "EXAMPLE2");

Because "example1" is an ANSI string and a WSTR string is required by the function, you must change the call so that "example1" is passed as a WSTR string, as shown in the following code:

PInstance->SetCharSplat (L"example1", "EXAMPLE2");

Consider the following code which also is incompatible with the new function prototype:

LPCTSTR str = "example1";
PInstance->SetCharSplat (str, "EXAMPLE2");

This will work when compiling for UNICODE, but will fail to compile when compiling for ANSI.

Exception Handling Changes

Exception handling is now enabled for the framework. Several classes now throw exceptions.

Generally speaking, the framework only throws errors on catastrophic errors, for example, out of memory or general protection faults.

You now need to make sure that if you have created instances you also dispose of those instances when an exception is thrown. Failure to do so will result in memory leaks. For a more detailed discussion, see Thrown Framework Errors.

Impersonation Changes

The framework now impersonates the connected user before making a call to the provider.

When a provider is called, it may run as an administrator with full rights or as a user with limited rights. When a service is requested (for example, deleting a file), you must ensure:

  • The present client has rights to that service
  • The request was performed successfully
  • Failures due to insufficient rights are caught and handled correctly.

Impersonation also raises the question of what to do if you are enumerating instances and you are able to populate some properties but not others. In general, if you can get enough information to populate the key properties you should return the instance along with WBEM_S_PARTIAL_RESULTS.

Note that when using GetObject, returning WBEM_E_ACCESS_DENIED indicates to the client that the requested object exists. For security reasons you may not want the client to have this information.

For details on impersonation, see Security and Authentication. See also A Few Thoughts on Framework Provider Security.

GetObject Changes

Previously, GetObject was a macro in Windows.h resolving to GetObjectW or GetObjectA, depending on the UNICODE context. The framework has its own GetObject method which cannot be written as a macro. Therefore, in Fwcommon.h, the definition of GetObject has been removed (#undef GetObject). If you need the actual Win32 GetObject method, you must call GetObjectA or GetObjectW directly.

Deprecated Function Changes

A number of methods have been deprecated. One version of CWbemProviderGlue::GetEmptyInstance, all versions of CWbemProviderGlue::FillInstance and several methods in the WBEMTime class have been deprecated. See Wbemtime.h for specifics. To find these methods, either check the comments in the appropriate header, or recompile and run your program using the Debug version of FrameDyd. When a deprecated function is called you will receive an ASSERT.

WBEMTime and WBEMTimeSpan Changes

Both the WBEMTime class and the WBEMTimeSpan class have changed. These changes are not expected to affect existing code.If you are performing date or time arithmetic, the changes made to these methods may affect your code. For details, see Provider Framework Utility Classes. If you are not performing date or time arithmetic, these changes do not affect your code.

Calling Convention Changes

Several methods that previously did not have a calling convention are now specified as WINAPI. Recompiling your code will fix any discrepancies.


Framework Tutorial

[This is preliminary documentation and subject to change.]

In the following example, we will use Microsoft Visual Studio 6.0 to create a new framework provider. We will gradually add code to the project until we have a fully functional framework provider.

This limited provider supports creating and enumerating instances, modifying properties, and executing simple methods. It does not support queries, deleting instances, or executing methods through synchronous or asynchronous calls to CWbemProviderGlue::GetInstancesByQuery. For code examples of these other methods, see the FrameworkProv sample that ships with the WMI SDK.

For more information on implementing queries, see How to Write an ExecQuery Routine (and Why You Should).


Defining the Sample Framework Provider Class

The easiest way to add a new framework provider class to your system is with the MOF compiler. Here's what you need to know at this point:

  • Your sample framework provider will be both a dynamic instance provider and a method provider.
  • You'll compile it into the Root\Default namespace.
  • The provider's name will be ReindeerProv.dll.


To Create the Framework Provider Class

  1. Create an empty folder named ReindeerProv in some convenient location.
  2. Open Microsoft® Visual Studio® and select the File/New menu item. Select the Files tab from the New dialog box and then select Text File.
  3. Set the File Name to ReindeerClass.mof and the Location to the newly created ReindeerProv folder. Click OK.
  4. Use the namespace pragma to direct compilation into the Root\Default namespace by adding these lines to the start of the new file:
    // ReindeerClass.mof

#pragma namespace ("\\\\.\\Root\\Default")
  5. Define the Reindeer class, whose instances and methods will be provided by the dynamic provider ReindeerProv.dll.
    1. Define the properties of the Reindeer class by adding these boldfaced lines to the end of the file:
      // ReindeerClass.mof

#pragma namespace ("\\\\.\\Root\\Default")

[Dynamic, Provider ("ReindeerProv")]
class Reindeer
{
    [read, key]
    String Name;

    [read, write]
    uint32 Weight;

    [read, write]
    boolean RedNose;
};

    Instances of the Reindeer class will be provided on demand by ReindeerProv.dll. Each Reindeer instance has a unique name, a modifiable weight, and, possibly, a red nose.

    2. Now declare a method to calculate the total weight of all reindeer:
      [Dynamic, Provider ("ReindeerProv")]
class Reindeer
{
    [read, key]
    String Name;

    [read, write]
    uint32 Weight;

    [read, write]
    boolean RedNose;

    [Implemented, static, Description(
    "The CalcWeight method computes the total weight of all reindeer. "
    "It returns the total weight, or 0xffffffff on error.")]
    uint32 CalcWeight();
};

    Save your text file. The resulting MOF file is ready to compile.

  6. Run the mofcomp MOF compiler to compile the new MOF file.

    From the command line, navigate to the ReindeerProv folder and type:

    mofcomp reindeerclass.mof

    You should see these lines appear on your display:

    Parsing MOF file: reindeerclass.mof
MOF file has been successfully parsed
Storing data in the repository...
Done!
  7. Verify that the Reindeer class has been added to the CIM repository:
    1. Open WMI Cim Studio.
    2. In the Connect to namespace dialog box, change to the Root\Default namespace and click OK.
    3. Click OK again to complete the login.

      After a moment, you will see the Reindeer class listed at the bottom of the left-hand Class Explorer pane.

    4. Select this class.

In the right-hand Class Viewer pane, the Reindeer class properties, Name, RedNose, and Weight, are listed under the Properties tab, and its method, CalcWeight, is listed under the Methods tab.


To Create the Framework Provider Source Files

Now that the Reindeer class is in the CIM repository, you can use the Provider Code Generator in WMI Cim Studio to create the framework provider source files for this class.

To Create the New Provider Source Files

  1. First, check the checkbox to the left of the Reindeer class in the Class Explorer pane.
  2. Double-click the Provider Code Generator icon in the Wizards toolbar above the Class Viewer pane. This opens the Provider Code Generator Wizard.
  3. Click the Next button. Accept all the defaults in the Specify names and properties dialog. For more information on this dialog, see the Provider Code Generator documentation. Click the Next button again.
  4. In the Save provider dialog, change the provider name to ReindeerProv, and the directory for generated files to the ReindeerProv folder.
  5. Click the Finish button. You will see a warning dialog that reads, "The dynamic provider ReindeerProv provides the class Reindeer. Do you want to replace it with the new dynamic provider ReindeerProv?" Click Yes. A short time later, you will see the message "Generation of files complete."

    This adds the following files to the ReindeerProv folder:

    MAINDLL.CPP
    Reindeer.CPP
    Reindeer.H
    ReindeerProv.DEF
    ReindeerProv.MAK
    ReindeerProv.MOF

To Create the New Provider Project

You can convert the makefile ReindeerProv.MAK into a Visual Studio project by following these steps:

  1. From Visual Studio, select the File/Open Workspace menu item. Navigate to the ReindeerProv folder. List files of type Makefiles (.mak) and select the ReindeerProv.MAK file. Click Open.
  2. You will see the warning "This makefile was not generated by Developer Studio". Click Yes to continue.
  3. The Win32 platform is already selected. Click OK.
  4. Change the name of the new project file to Reindeer and click Save.
  5. From the FileView tab, right-click on the Reindeer files project heading and select Add Files to Project from the popup menu. In the Insert Files into Project dialog box, list files of type All Files (*.*) and select these files:

    MAINDLL.CPP
    Reindeer.CPP
    Reindeer.H
    ReindeerProv.DEF
    ReindeerProv.MOF

    Click OK to add these files to the project.

  6. Connect the makefile to the Visual Studio active configuration switch by following these steps:
    1. Open the ReindeerProv.MAK file and look for these lines:
      !MESSAGE You can specify a configuration when running NMAKE
!MESSAGE by defining the macro CFG on the command line. For example:
!MESSAGE
!MESSAGE NMAKE /f "Reindeer.mak" CFG="Reindeer - Win32 Debug"

    The active configuration is switched by a command line argument.

Command line argument | Action
Reindeer - Win32 Debug | Selects the Debug build.
Reindeer - Win32 Release | Selects the Release build.

  2. Copy the suggested command line into the clipboard.
    NMAKE /f "Reindeer.mak" CFG="Reindeer - Win32 Debug"
  3. From the FileView tab, right-click on the Reindeer files project heading and select Settings from the popup menu.
  4. Click on the General tab and select the Win32 Debug configuration from the Settings For list box.
  5. Replace the Build Command Line with the one you pasted into the clipboard, and click OK.

    Save and close the ReindeerProv.MAK file.

  7. Select the Tools/Options menu item and click on the Directories tab. Select Include files from the Show directories for list box. Add the path to the WMI SDK Include folder, if it isn't already there. Click OK.
  8. Select Library files from the Show directories for list box. Add the path to the WMI SDK lib folder, if it isn't already there.
  9. Build the project and verify it creates a Debug folder that includes the new dynamic provider ReindeerProv.dll. If not, be sure your active configuration is set to Debug by selecting the Build/Set Active Configuration menu item, selecting ReindeerProv - Win32 Debug, and clicking OK.


Examining the Sample Framework Provider Source Files

The ReindeerProv.MOF file, generated by the Provider Code Generator, contains all the source code you need to register the Reindeer instance and method providers. This file is listed below:

// ReindeerProv.MOF
//
// Generated by Microsoft WBEM Code Generation Engine
//
// TO DO: If this class is intended to be created in a namespace
//        other than the default (root\default), you should add
//        the #pragma namespace command here.  If these classes
//        are going into your own namespace, consider creating
//        the namespace here as well.  See CIMWIN32.MOF for an
//        example of how to create a namespace.  Also, consider
//        combining this mof with the mof the defines the class
//        that this provider provides.
//
//=============================================================

//*************************************************************
//***   Registers Framework Provider                        ***
//*************************************************************
instance of __Win32Provider as $P
{
    Name = "ReindeerProv";
    ClsId = "{d39e92a0-d119-47d7-bd5f-bab7769f4876}";
};

instance of __InstanceProviderRegistration
{
    Provider = $P;
    SupportsGet = TRUE;
    SupportsPut = TRUE;
    SupportsDelete = TRUE;
    SupportsEnumeration = TRUE;
    QuerySupportLevels = {"WQL:UnarySelect"};
};

instance of __MethodProviderRegistration
{
    Provider = $P;
};

This mof source code serves several purposes.

  1. It creates an instance of __Win32Provider to register the provider.
    instance of  Win32Provider as $P
{
    Name = "Reindeer";
    ClsId = "{006efdb2-2b29-11d3-8c17-0000f875872b}";
};

    In plain English, this reads, "The WMI dynamic provider ReindeerProv.dll is identified by the COM ClassID given in curlique brackets. Call this identity by the alias $P."

    This amounts to a promise that the provider will support the IWbemProviderInit interface.

  2. It declares the provider to be an instance provider.
    instance of InstanceProviderRegistration
{
    Provider = $P;
    SupportsGet = TRUE;
    SupportsPut = TRUE;
    SupportsDelete = TRUE;
    SupportsEnumeration = TRUE;
    QuerySupportLevels = {"WQL:UnarySelect"};
};

    The Provider property is given as $P, the alias for ReindeerProv.dll. The parameters to __InstanceProviderRegistration say that this provider supports data retrieval, modification, and deletion, as well as enumeration and basic SELECT queries. This amounts to a promise to support the following interfaces:

    IWbemServices::GetObjectAsync
    IWbemServices::PutInstanceAsync
    IWbemServices::DeleteInstanceAsync
    IWbemServices::CreateInstanceEnumAsync
    IWbemServices::ExecQueryAsync

  3. It declares the provider to be a method provider.
    instance of __MethodProviderRegistration
{
    Provider = $P;
};

    The Provider property is given as $P, the alias for ReindeerProv.dll. There are no other parameters to __MethodProviderRegistration. There is instead an inherit promise that this provider will support the method(s) of the Reindeer class.


Modifying the ReindeerProv.MOF File

Our simple provider does not support queries or deleting instances. Change the following boldfaced lines in ReindeerProv.MOF to remove support for these methods:

instance of InstanceProviderRegistration
{
    Provider = $P;
    SupportsGet = TRUE;
    SupportsPut = TRUE;
    SupportsDelete = FALSE;
    SupportsEnumeration = TRUE;
    QuerySupportLevels = NULL;
};


Merging the Two MOF Files

Follow the suggestions in the comment section of the ReindeerProv.MOF file and merge it with the ReindeerClass.mof file. Cut and paste these boldfaced lines from the ReindeerClass.mof file into the ReindeerProv.MOF file.

// ReindeerProv.MOF
//
// Generated by Microsoft WBEM Code Generation Engine
//
// TO DO: If this class is intended to be created in a namespace
//        other than the default (root\default), you should add
//        the #pragma namespace command here.  If these classes
//        are going into your own namespace, consider creating
//        the namespace here as well.  See CIMWIN32.MOF for an
//        example of how to create a namespace.  Also, consider
//        combining this mof with the mof the defines the class
//        that this provider provides.
//
//=============================================================

#pragma namespace ("\\\\.\\Root\\Default")

//*************************************************************
//***   Registers Framework Provider                        ***
//*************************************************************
instance of __Win32Provider as $P
{
    Name = "ReindeerProv";
    ClsId = "{d39e92a0-d119-47d7-bd5f-bab7769f4876}";
};

instance of __InstanceProviderRegistration
{
    Provider = $P;
    SupportsGet = TRUE;
    SupportsPut = TRUE;
    SupportsDelete = TRUE;
    SupportsEnumeration = TRUE;
    QuerySupportLevels = {"WQL:UnarySelect"};
};

instance of __MethodProviderRegistration
{
    Provider = $P;
};

[Dynamic, Provider ("ReindeerProv")]
class Reindeer
{
    [read, key]
    String Name;

    [read, write]
    uint32 Weight;

    [read, write]
    boolean RedNose;

    [Implemented, static, Description(
    "The CalcWeight method computes the total weight of all reindeer. "
    "It returns the total weight, or 0xffffffff on error.")]
    uint32 CalcWeight();
};
  2. Close the ReindeerClass.mof file and delete it from the project folder.
  3. Run the mofcomp MOF compiler to compile the ReindeerProv.MOF file.

    From the command line, navigate to the ReindeerProv folder and type:

    mofcomp reindeerprov.mof

    You should see these lines appear on your display:

    Parsing MOF file: reindeerprov.mof
MOF file has been successfully parsed
Storing data in the repository...
Done!


Implementing the Sample Framework Provider

The in-process server skeleton for the sample dynamic framework provider is defined in the source file MAINDLL.CPP. The source code in this file implements these required DLL functions:

  • DllGetClassObject
  • DllCanUnloadNow
  • DllRegisterServer
  • DllUnregisterServer

DllMain


Improving the Framework Provider DLL Support

To improve the DLL support for the framework provider, you can make the following changes in MAINDLL.CPP:

  1. Scroll down to the function DllRegisterServer and find these lines:
        // TO DO: Using 'Both' is preferable.  The framework is designed and written to support
    // free threaded code.  If you will be writing free-threaded code, uncomment these
    // three lines.

//    if(Is4OrMore())
//        pModel = "Both";
//    else
        pModel = "Apartment";

    Since our example will be free-threaded, go ahead and uncomment the lines

        if(Is4OrMore())
        pModel = "Both";
    else
        pModel = "Apartment";
  2. Scroll down to the function DllMain and find these lines:
            case DLL_PROCESS_ATTACH:

    // TO DO: Consider adding DisableThreadLibraryCalls().

    Go ahead and add the call to DisableThreadLibraryCalls:

            case DLL_PROCESS_ATTACH:

    // TO DO: Consider adding DisableThreadLibraryCalls().
    DisableThreadLibraryCalls(hInstDLL);

    This optimization disables the DLL_THREAD_ATTACH and DLL_THREAD_DETACH notification calls. Since our provider does nothing in either case, this reduces the number of times the provider DLL initialization code is paged into memory.


Specifying the Namespace

You must specify the namespace to be served by the framework provider.

To Specify the Framework Provider Namespace

  1. Open the file Reindeer.CPP and scroll down to these lines:
    // TO DO: Replace "NameSpace" with the appropriate namespace for your
// provider instance.  For instance:  "root\\default or "root\\cimv2".
//===================================================================
CReindeer MyReindeerSet (PROVIDER_NAME_REINDEER, L"NameSpace") ;
  2. Replace the "NameSpace" argument with "root\\default", as suggested by the comment:
    CReindeer MyReindeerSet (PROVIDER_NAME_REINDEER, L"root\\default");


Creating Instances with the Framework Provider

The sample framework provider must supply Reindeer instances to WMI on demand. WMI requests these instances by calling the CReindeer::EnumerateInstances method. The Provider Code Generator creates a skeleton for this method in the Reindeer.CPP source file. The default implementation returns no instances to WMI, and reports a successful completion.

To Implement the EnumerateInstances Method

While a normal provider would get its information by reading the registry, making Win32 API calls or the like, for our simple provider you will define a data structure that represents one Reindeer instance. You can then make an array of these structures, one for each existing Reindeer instance that you wish to supply to WMI. Follow these steps to implement EnumerateInstances this way:

  1. Add these boldfaced lines to the end of Reindeer.H, just after the definition of the CReindeer class, but before the #endif statement:
            HRESULT EnumerationCallback(CInstance *pReindeer, MethodContext *pMethodContext, VOID *pTotWeight);

} ;

// struct to hold instance information
struct Deers
{
    WCHAR* m_name;     // name of Reindeer
    DWORD m_weight;    // weight of reindeer
    bool m_redNose;    // does he have a red nose?
    bool m_deleted;    // has he been deleted?

    enum {NDeers = 9};
};

#endif
  2. Add these boldfaced lines to the beginning of Reindeer.CPP, just after the property names, but before the constructor:
    const static WCHAR* pWeight = L"Weight" ;

Deers ohDeers[Deers::NDeers] =
{
    // Name   Weight  Red Nose  Deleted flag
    {L"Dasher",  200,  false,  false},
    {L"Dancer",  150,  false,  false},
    {L"Prancer", 162,  false,  false},
    {L"Vixen",   125,  false,  false},
    {L"Comet",   212,  false,  false},
    {L"Cupid",   196,  false,  false},
    {L"Donder",  255,  false,  false},
    {L"Blitzen", 145,  false,  false},
    {L"Rudolf",  123,  true,   false}
};

/*************************************************
 *
 *  FUNCTION    :   CReindeer::CReindeer

    There are nine Reindeer, but only Rudolf has a red nose. The m_deleted flag lets you delete Reindeer later under program control. Initially, all Reindeer are present and accounted for.

  3. Replace the body of the EnumerateInstances method with these boldfaced lines:
    HRESULT CReindeer::EnumerateInstances ( MethodContext* pMethodContext, long lFlags )
{
    HRESULT hRes = WBEM_S_NO_ERROR;

    // create an instance for each reindeer
    for (int i = 0; (i < Deers::NDeers) && (SUCCEEDED(hRes)); i++)
    {
        // we don't want to return deleted deer
        if (!ohDeers[i].m_deleted)
        {
            // Note that CreateNewInstance will never return NULL.
            CInstance *pInstance = CreateNewInstance(pMethodContext);

            pInstance->SetCHString(
                pName, CHString(ohDeers[i].m_name));
            if (SUCCEEDED(LoadPropertyValues(
                              pInstance, i, BIT_ALL_PROPERTIES)))
            {
                hRes = pInstance->Commit();
            }
            pInstance->Release();
        }
    }
    return hRes ;
}

    In plain English, this reads, "As long as there are Reindeer to be returned, create a Reindeer instance and initialize its properties, then return this instance to WMI."

    The Reindeer instance is created by passing the method context to the Provider::CreateNewInstance method. You don't have to worry about what's in the context.

    CInstance *pInstance = CreateNewInstance(pMethodContext);

    The CInstance::SetCHString method sets the key Name property of the new Reindeer instance to the Deers.m_name of the current item in the ohDeers array.

    pInstance->SetCHString(pName, CHString(ohDeers[i].m_name));

    The remaining properties are initialized by calling LoadPropertyValues with the pointer to the new Reindeer instance, the current index into the ohDeers array, and a mask that indicates the properties to be set. LoadPropertyValues is a member function of the CReindeer class, and has intimate knowledge of the ohDeers array. You will implement this function shortly below.

    LoadPropertyValues(pInstance, i, BIT_ALL_PROPERTIES)

    Finally, the new initialized Reindeer instance is returned to WMI via the CInstance::Commit method.

    hRes = pInstance->Commit();

To Implement the LoadPropertyValues Method

LoadPropertyValues is a member function of the CReindeer class, and is not generated by the Provider Code Generator. LoadPropertyValues is designed to initialize the properties of a new Reindeer instance, and has an intimate knowledge of the ohDeers array. There are two methods in the CReindeer class that need to set Reindeer properties:

EnumerateInstances
GetObject

To implement the LoadPropertyValues method, follow these steps:

  1. Add these boldfaced lines to the beginning of Reindeer.CPP, just after the #include statements:
    #include "Reindeer.h"

#define BIT_REDNOSE 0x00000001
#define BIT_WEIGHT  0x00000002
#define BIT_ALL_PROPERTIES 0xffffffff

    These lines define the masks used by LoadPropertyValues to select individual properties. To select all properties, except for the key Name property, use the BIT_ALL_PROPERTIES mask.

  2. Add these boldfaced lines to the end of Reindeer.CPP.
    // CReindeer::LoadPropertyValues
// pInstance -- points to a CInstance object
// dwIndex   -- index into the ohDeers array
// dwRequiredProperties -- bitmask of properties to set

HRESULT CReindeer::LoadPropertyValues(
    CInstance *pInstance, DWORD dwIndex, DWORD dwRequiredProperties)
{
   if (dwRequiredProperties & BIT_WEIGHT)
       pInstance->SetDWORD(pWeight,  ohDeers[dwIndex].m_weight);

   if (dwRequiredProperties & BIT_REDNOSE)
       pInstance->Setbool(pRedNose,  ohDeers[dwIndex].m_redNose);

   return WBEM_S_NO_ERROR;
}

    In plain English, this reads, "Set the given property or properties from the corresponding data for the given Reindeer in the ohDeers array."

  3. Declare the LoadPropertyValues method as a member function of the CReindeer class by adding this boldfaced line to the CReindeer class declaration in Reindeer.H, just after ExecMethod:
            // Other Functions
        virtual HRESULT ExecMethod( const CInstance& Instance,
                        const BSTR bstrMethodName,
                        CInstance *pInParams,
                        CInstance *pOutParams,
                        long lFlags = 0L );

        // TO DO: Declare any additional functions and accessor
        // functions for private data used by this class
        //===========================================================
        HRESULT LoadPropertyValues( CInstance *pInstance, DWORD dwIndex, DWORD dwRequiredProperties);


To Test the EnumerateInstances Method

To test your implementation of EnumerateInstances, follow these steps:

  1. Build the project and verify that it builds without errors.
  2. From the command line, navigate to the Debug folder (for a debug build) or the Release folder (for a release build) and type:
    regsvr32 reindeerprov.dll

    You should see an alert box with the message "DllRegisterServer in reindeerprov.dll succeeded." Click OK. Your provider is now registered with COM.

Note You must do this whenever you change the path to the DLL.

  3. Open WMI Cim Studio.
  4. In the Connect to namespace dialog box, change to the Root\Default namespace and click OK. Press OK again to complete the login.
  5. After a moment, you will see the Reindeer class listed at the bottom of the left-hand Class Explorer pane. Select this class.
  6. Click the Instances button in the toolbar at the top of the Class Viewer pane. You should see the Reindeer instances displayed, with columns for the Name, Weight, and RedNose properties.

If you would like to make changes in the CReindeer source files and see them reflected in the CIM Studio Class Viewer pane, you must first flush the various WMI system caches:

  7. Rebuild your framework provider.
  8. Close CIM Studio.
  9. From the command line, type:
    net stop winmgmt
  10. Repeat steps 3 through 6 above.

To Implement the GetObject Method

To implement GetObject, you need only to search the items of the ohDeers array until you find one that matches the key Name property of the instance argument. You then move the properties of the item into the instance argument and return the instance to WMI.

To implement GetObject, replace the body of the GetObject method with these boldfaced lines:

HRESULT CReindeer::GetObject ( CInstance* pInstance, long lFlags )
{
    HRESULT hr = WBEM_E_NOT_FOUND;

    // name is the key, we retrieve the name
    CHString name;
    pInstance->GetCHString(pName, name);

    // search the array for a Reindeer with the name we're given
    // (make sure he hasn't been deleted!)
    for (int i = 0; i < Deers::NDeers; i++)
    {
        if (0 == name.CompareNoCase(CHString(ohDeers[i].m_name)) && !ohDeers[i].m_deleted)
        {
            // we found the one they're look for - fill in the data

            hr = LoadPropertyValues(pInstance, i, BIT_ALL_PROPERTIES);
            break;
        }
    }

    return hr ;
}

In plain English, this reads, "First, get the Name property from the instance argument. If there is a Reindeer whose name matches the Name property of the given instance, use it to update the Weight and RedNose properties of the instance argument." If no matching Reindeer is found, GetObject returns WBEM_E_NOT_FOUND.

To Test the GetObject Method

To test your implementation of GetObject, follow these steps:

  1. Build the project and verify that it builds without errors.
  2. From the command line, navigate to the Debug folder (for a debug build) or the Release folder (for a release build) and type:
    regsvr32 reindeerprov.dll

    You should see an alert box with the message "DllRegisterServer in reindeerprov.dll succeeded." Click OK. Your provider is now registered with COM.

    Note You must do this whenever you change the path to the DLL.

  3. Open WMI Cim Studio.
  4. In the Connect to namespace dialog box, change to the Root\Default namespace and click OK. Press OK again to complete the login.
  5. After a moment, you will see the Reindeer class listed at the bottom of the left-hand Class Explorer pane. Select this class.
  6. Click the Instances button in the toolbar at the top of the Class Viewer paneError! Cannot read or display file.. You should see the Reindeer instances displayed, with columns for the Name, Weight, and RedNose properties.
  7. Right click the "Blitzen" Reindeer and click on the Go To Object button. You will see the Properties view for the Blitzen instance.

    If you would like to make changes in the CReindeer source files and see them reflected in the CIM Studio Class Viewer pane, you must first flush the various WMI system caches:

  8. Rebuild your framework provider.
  9. Close CIM Studio.
  10. From the command line, type:
    net stop winmgmt
  11. Repeat steps 3 through 7 above.


Modifying Instances with the Framework Provider

The sample framework provider allows WMI to modify the properties of instances of the Reindeer class. When a client does a PutInstance against the Reindeer class, the CReindeer::PutInstance method is called to actually perform the work. The Provider Code Generator creates a skeleton for this method in the Reindeer.CPP source file. The default implementation returns WBEM_E_PROVIDER_NOT_CAPABLE to WMI. For more information on the lFlags parameter, see Provider::PutInstance.

To Implement the PutInstance Method

To implement PutInstance, you need only to move the properties of the instance argument into the corresponding item of the ohDeers array that matches the key Name property of this instance.

Replace the body of the PutInstance method with these boldfaced lines:

HRESULT CReindeer::PutInstance ( const CInstance &Instance, long lFlags)
{
    HRESULT hresult = WBEM_E_INVALID_PARAMETER;

    // we do not create reindeer here.
    if (lFlags & WBEM_FLAG_CREATE_ONLY)
        hresult = WBEM_E_UNSUPPORTED_PARAMETER;
    else
    {
        // get the key value so we can tell
        // which reindeer we're operating on
        CHString name;
        Instance.GetCHString(pName, name);
        for (int i = 0; i < Deers::NDeers; i++)
        {
            if (0 == name.CompareNoCase(CHString(ohDeers[i].m_name)) && !ohDeers[i].m_deleted)
            {
                // we found one, we can change the red nose
                // and/or the weight properties
                DWORD weight;
                bool  redNoze;

                if (Instance.GetDWORD(pWeight,  weight))
                    ohDeers[i].m_weight = weight;

                if (Instance.Getbool(pRedNose, redNoze))
                    ohDeers[i].m_redNose = redNoze;

                hresult = WBEM_S_NO_ERROR;
                break;
            }
        }

        if (FAILED(hresult))
        {
            // If they said they wanted to update, but it wasn't there
            if (lFlags & WBEM_FLAG_UPDATE_ONLY)
            {
                hresult = WBEM_E_NOT_FOUND;
            }
        }
    }

    return hresult;
}

In plain English, this reads, "If there is a Reindeer whose name matches the Name property of the given instance, update its Weight and RedNose properties from that instance."

There are a few errors that can occur:

  • WMI calls PutInstance to create a new instance. New instances cannot be created here. In this case, PutInstance returns WBEM_E_UNSUPPORTED_PARAMETER.
  • There is no present Reindeer matching the key value. In this case, PutInstance returns WBEM_E_NOT_FOUND.

To Test the PutInstance Method

To test your implementation of PutInstance, follow these steps:

  1. Build the project and verify that it builds without errors.
  2. From the command line, navigate to the Debug folder (for a debug build) or the Release folder (for a release build) and type:
    regsvr32 reindeerprov.dll

    You should see an alert box with the message "DllRegisterServer in reindeerprov.dll succeeded." Click OK. Your provider is now registered with COM.

    Note You must do this whenever you change the path to the DLL.

  3. Open WMI Cim Studio.
  4. In the Connect to namespace dialog box, change to the Root\Default namespace and click OK.
  5. Press OK again to complete the login.
  6. After a moment, you will see the Reindeer class listed at the bottom of the left-hand Class Explorer pane. Select this class.
  7. Click the Instances button in the toolbar at the top of the Class Viewer pane. You should see the Reindeer instances displayed, with columns for the Name, Weight, and RedNose properties.
  8. Right click the "Blitzen" Reindeer and click on the Go To Object button. You will see the Properties view for the Blitzen instance.
  9. Change the RedNose property to true by clicking on the Value field and selecting true from the drop-down list. Click on the Save button in the toolbar located at the top of the Class Explorer pane.
  10. Click the Instances button in the toolbar at the top of the Class Viewer pane. Scroll right to the RedNose column. Both Blitzen and Rudolf now have red noses.

    If you would like to make changes in the CReindeer source files and see them reflected in the CIM Studio Class Viewer pane, you must first flush the various WMI system caches:

  11. Rebuild your framework provider.
  12. Close CIM Studio.
  13. From the command line, type:
    net stop winmgmt
  14. Repeat steps 3 through 10 above.


Invoking Methods with the Framework Provider

The sample framework provider allows WMI to invoke the methods of a method provider, such as the CalcWeight method of the Reindeer class. When a client calls Provider::ExecMethod to invoke a method of the Reindeer class, passing it the name of the method to invoke, the CReindeer::ExecMethod method is called to actually do the work. Only static methods can be invoked this way.

Before invoking a method, the framework fills a CInstance instance with input arguments. The input parameters are typically defined in the MOF definition for the class owning the method. For example, a method which adds two input parameters might be defined this way:

[Implemented, Description(
    "The Addem method returns the sum of two arguments.")]
    uint32 Addem([In] uint32 LeftNum, [In] uint32 RightNum);

The Addem method would use CInstance::GetDWORD to retrieve the arguments LeftNum and RightNum by name.

After invoking a method, the results of the execution are returned in another CInstance instance, also supplied by the framework. For example, the Addem method would use CInstance::SetDWORD to return the sum of its two arguments. The return value is always named "ReturnValue".

The framework passes pointers to both the input and output CInstance instances to ExecMethod.

The Provider Code Generator creates a skeleton for ExecMethod in the Reindeer.CPP source file. The default implementation returns WBEM_E_PROVIDER_NOT_CAPABLE to WMI. For more information on the lFlags parameter, see Provider::ExecMethod.

To Implement ExecMethod

To implement ExecMethod, you need to see if the given name of the method to invoke is one that you support. If so, you retrieve the input arguments, execute the method, and return the result.

In the following example, the CReindeer::CalcWeight method is implemented. To implement CalcWeight, replace the body of the ExecMethod method with these boldfaced lines:

HRESULT CReindeer::ExecMethod ( const CInstance& Instance,
                        const BSTR bstrMethodName,
                        CInstance *pInParams,
                        CInstance *pOutParams,
                        long lFlags)
{
    HRESULT hresult = WBEM_E_PROVIDER_NOT_CAPABLE;

    if (_wcsicmp(bstrMethodName, L"CalcWeight") == 0)
    {
        hresult = WBEM_S_NO_ERROR;
        DWORD dwTotWeight = 0;

        for (int i = 0; i < Deers::NDeers; i++)
        {
            if (!ohDeers[i].m_deleted)
            {
                dwTotWeight += ohDeers[i].m_weight;
            }
        }
        // Set the out parameter, and we're done
        pOutParams->SetDWORD(L"ReturnValue", dwTotWeight);
    }

    return hresult;
}

In plain English, this reads, "If the CalcWeight method is invoked, return the combined weight of all Reindeer."

For more information on implementing ExecMethod, see Issues When Writing an ExecMethod Routine.

To Test ExecMethod

To test your implementation of ExecMethod, follow these steps:

  1. Build the project and verify that it builds without errors.
  2. From the command line, navigate to the Debug folder (for a debug build) or the Release folder (for a release build) and type:
    regsvr32 reindeerprov.dll

    You should see an alert box with the message "DllRegisterServer in reindeerprov.dll succeeded." Click OK. Your provider is now registered with COM.

    Note You must do this whenever you change the path to the DLL.

  3. Open WMI Cim Studio.
  4. In the Connect to namespace dialog box, change to the Root\Default namespace and click OK.
  5. Press OK again to complete the login.
  6. After a moment, you will see the Reindeer class listed at the bottom of the left-hand Class Explorer pane. Select this class.
  7. Click the Methods tab. A list box opens listing all Reindeer methods.
  8. Right click the CalcWeight method and click on Execute Method. The Method Parameters dialog opens, allowing you to enter input arguments. CalcWeight has no input arguments.
  9. Click the Execute button. The edit box to the right of the ReturnValue label changes to 1568, the total weight of the reindeer.

    If you would like to make changes in the CReindeer source files and see them reflected in the CIM Studio Class Viewer pane, you must first flush the various WMI system caches:

  10. Rebuild your framework provider.
  11. Close CIM Studio.
  12. From the command line, type:
    net stop winmgmt
  13. Repeat steps 3 through 9 above.


Provider Framework Advanced Topics

Framework provider writers face a variety of choices for optimal implementation. Some of these issues are addressed in the following topics.

  • How to Write an ExecQuery Routine (and Why You Should)
  • How to Support a Client Canceling a Request
  • Issues When Writing an ExecMethod Routine
  • How to Approach the Creation of an Association Class
  • Default Parameters in Framework Functions
  • What is a Status Object?
  • A Few Thoughts on Framework Provider Security
  • Out of Process Framework Providers
  • Multithreading Issues
  • Returning Zero Instances vs. Error – A Philosophical Debate
  • What is a MethodContext Anyway?
  • WBEMTime, WBEMTimeSpan, and FAT versus NTFS Time
  • How To Support Per-Property Gets
  • How To Make Calls Back to WinMgmt to Get Data
  • Creating a Subclass_hmm_Creating_a_Subclass


How to Write an ExecQuery Routine (and Why You Should)

Framework provider performance can benefit greatly by implementing the ExecQuery. The following topics detail the pros and cons of writing an ExecQuery function:

  • Why You DON'T Need to Write a Query Routine
  • Why You DO Need to Write a Query Routine
  • Writing a Query Routine

Why You DON'T Need to Write a Query Routine

The first thing you have to understand about ExecQuery routines is that you don't have to write one. If you don't write support for queries, your EnumerateInstances routine will be called instead, and the instances and properties will be post-filtered by WinMgmt so that only the appropriate data is sent back to the client.

Why You DO Need to Write a Query Routine

In real life, it doesn't take very long for problems to begin cropping up using simple enumerations instead of queries. For example, the Win32_LogicalDisk class reports the drive letter and volume label (among other properties) for all the drive letters on the system. Suppose you want to be able to produce a pulldown list of drive letters, so you do a query of the form "SELECT DeviceID FROM Win32_LogicalDisk". This query takes MUCH longer than you expect. That's because Win32_LogicalDisk doesn't support queries (yet), so enumeration is called and WinMgmt post-filters the results. Enumerations populate all properties, one of which is VolumeLabel. To read the volume name, you actually have to read the disk. For floppy drives and network drives, this takes much too long. To improve performance, Win32_LogicalDisk needs to consider the properties that are being requested.

For a second example, consider CIM_DataFile, which represents all files on all logical drives, including floppies and network drives. As you can imagine, an enumeration of this class can return a LOT of instances. For reasonable performance, the implementation of this class needs to look at the WHERE clause to see if it can shorten the workload. If the query is of the form "SELECT * FROM CIM_DataFile WHERE Drive='A:'", a great deal of work can be avoided. To improve performance CIM_DataFile needs to consider the instances that are requested.

While providers that return very few instances with easily obtainable properties may be able to avoid writing a query routine, most providers would benefit from writing one. Fortunately, they are very easy to write.


How To Write a Query Routine

Let's start with the case where we want to examine what properties are required. Perhaps the best way to start is to create a LoadPropertyValues routine. This routine will contain the actual calls to CInstance->SetXXX, instead of having them duplicated in both the GetObject and EnumerateInstances, and then for a third time in the ExecQuery routine.

A good example of what this routine should look like is shown in the FrameworkProv sample, which ships with the WMI SDK. Take a look at the LoadPropertyValues routine in that code. In particular, look at how the dwRequiredProperties parameter is used. Then look at EnumerateInstances routine where the LoadPropertyValues routine is called. Since it will be populating all properties, it passes BIT_ALL_PROPERTIES (which is set to 0xffffffff).

Now look at the ExecQuery routine. It builds up a DWORD using the CFrameworkQuery::IsPropertyRequired method. Then look at the code that follows. This is basically the same loop that is in EnumerateInstances, except that instead of passing BIT_ALL_PROPERTIES, it passes dwRequiredProperties.

Other functions that deal with which properties are being requested are CFrameworkQuery::GetRequiredProperties, CFrameworkQuery::AllPropertiesAreRequired, and CFrameworkQuery::KeysOnly.

Now let's look at how to process the WHERE clause. Again, let's look at the FrameworkProv sample. The comments in the query section describe WHERE clause processing theory pretty well, so here we're going to focus on the implementation.

The only function currently in the framework to do WHERE clause processing is GetValuesForProp. This routine takes a property name, and an array. If the array length is non-zero on return, then all you need to do is return one instance for each element in the array, and you have satisfied the query.

While you can look at the Reindeer provider, let's consider how this would work in a more realistic class. For example, in the CIM_DataFile class, the key property is Name. The name property contains the full path of the file, for example, "C:\winnt\system32\wbem\winmgmt.exe". If you call

GetValuesForProp(L"Name", saNames),

then it is very easy to send back the instances requested by the query.

If the GetValuesForProp against the Name property returns an empty array, then CIM_DataFile makes additional calls to GetValuesForProp using Drive and a few other properties. If you really can't find anything to optimize on, then you must fall back to enumeration.

Consider the somewhat contrived query

"SELECT * FROM CIM_DataFile WHERE (Name = 'C:\autoexec.bat" AND Drive = 'C:') OR Drive = 'A:'".

How many values will GetValuesForProp(L"Name") return? How about GetValuesForProp(L"Drive")?

If you return one instance for each element of the returned array, you have satisfied the query. Given that constraint, Name returns zero values, and Drive returns two. The reason Name returns zero elements is the "OR drive = 'a:'" clause of the query.

In Summary While you don't have to write query routines, you can use them to improve performance. Use functions like IsPropertyRequired to see what properties are required, and GetValuesForProp to see what Instances are required.


How To Handle Associator and Reference Queries

WMI does not send Associator or References queries through to framework providers. By using the schema, WMI is able to determine which classes are related to the class in question, and it generates appropriate WQL queries to retrieve the results.

For example, if you run an Associators query against an instance of CIM_Controller, WMI would examine the schema and find all association classes that had CIM_Controller, or any of the parent classes of CIM_Controller, as an endpoint. For example, the CIM_ControlledBy class has a property named Antecedent that is a CIM_Controller ref. So WMI might generate a query of the form "SELECT * FROM CIM_ControlledBy WHERE Antecedent = "FloppyController1"".

It isn't actually necessary to do anything to support Associator and References queries beyond what you would do to support regular WQL queries. For more information on supporting regular WQL queries, see How To Write an ExecQuery Routine (and Why You Should)".

To ensure that your providers give good performance in response to Associator and Reference type queries:

  • Make sure you support queries in your association class, especially queries where the reference properties are used in a WHERE clause. See the CFrameWorkQuery::GetValuesForProp method for more information.
  • In your association class, when you are checking to see if the endpoints exist, make sure you use the CWbemProviderGlue::GetInstanceKeysByPath or CWbemProviderGlue::GetInstancePropertiesByPath functions, to allow the endpoints to skip populating expensive or unneeded properties (see the discussion about GetObject in How To Approach the Creation of an Association Class.
  • Make sure classes that are endpoints of associations support per property gets. See How To Support PerProperty Gets for more information.


How to Support a Client Canceling a Request

The only way in a framework provider to detect that a client has canceled a request is to check the return code from Commit (either Provider::Commit or CInstance::Commit). If it is WBEM_E_CALL_CANCELLED, the client has canceled the request.

When a request is cancelled, you should stop sending back instances. In fact, any time FAILED(Commit) is true, you should stop sending back instances. While WinMgmt will discard all unneeded instances, it is an unnecessary waste of system resources to continue.


Issues When Writing an ExecMethod Routine

A class can support methods without having to support EnumerateInstances or GetObject. In fact, the Win32_BaseService class does this very thing.

Here is the function prototype for ExecMethod. Let's talk about what is in each of these parameters, and how you might use them.

HRESULT Provider::ExecMethod ( const CInstance& Instance,
    const BSTR bstrMethodName,
    CInstance *pInParams,
    CInstance *pOutParams,
    long lFlags)

In order to understand the first parameter, you must first understand that there are two types of methods, static and instance. The difference between them is that instance methods apply to one specific instance of a class, while static instances apply to the class in general.

An example of an instance method would be a method that changes the key value of an instance. An example of a static method would be one that counts how many instances a class is going to return. Examples of both static and instance methods can be found in the FrameworkProv sample that ships with the WMI SDK.

If the method is being run against a specific instance, the Instance parameter will be populated with the key properties (and ONLY the key properties) of the instance they are running against. These values can be read with the normal CInstance::GetXXX functions. Look in the FrameworkProv sample code to see how the Undelete method is handled by the ExecMethod routine.

If a method is being run against a class, the Instance parameter will be the class object.

It is possible for you to define any number of methods in a single class. All methods for a class will call the Provider::ExecMethod entry point. The second parameter to ExecMethod is the name of the method the client is invoking.

To explain the pInParams parameter, we need to look at a specific MOF file. Consider the following method:

[Implemented, Description("Some generic method.")]
void DoSomething([In] string Param1, [In] uint32 Param2 ) ;

In order to retrieve these parameters, you would use commands such as

pInParams->GetCHString(L"Param1", sParam1);
pInParams->GetDWORD(L"Param2", dwParam2);

Before we talk about the pOutParams parameter, we need to discuss some terminology. When we talk about "return" values for methods, there are really two things we might be talking about. Consider the following method:

[Implemented, static, Description("Some other generic routine")]
uint32 AddThese([out] uint32 ParamA, [out] uint32 ParamB) ;

You see that the AddThese method returns a uint32. This should not be confused with the HRESULT that is returned from the Provider::ExecMethod call. The HRESULT should be used to indicate WMI type errors: WBEM_E_OUT_OF_MEMORY, WBEM_E_NOT_FOUND, etc. The return from the method (the uint32 in the AddThese function), should return the result from the function.

Use the pOutParams parameter to set the values of ParamA and ParamB using normal CInstance::SetXXX functions. In addition to the [out] properties specified between the parenthesis in the method declaration, there is one additional property named "ReturnValue". This is where the method's return value should be stored.

A method may have input parameters, output parameters, both input and output parameters, or no input or output parameters. A method may return a value, or it may be of type void.

The lFlags parameters is seldom used or modified. In most providers, you can safely ignore it.


How to Approach the Creation of an Association Class

Before we talk about how to write an association class, let's talk a bit about why you should create an association class. Consider these two classes: Win32_DiskDrive, and Win32_DiskPartition. Using a classic database approach, you might just make the Disk Drive Number (the key for the Win32_DiskDrive class), part of the key for Win32_DiskPartition. Then if you needed to show all the partitions on a specific disk drive, then you could just match the instances up based on the Disk Drive Number.

There are several problems with this approach.

First, this means that if someone besides you (the writer of these two classes) wants to be able to show partitions on a drive, then they need to know how the two classes relate. They might have to guess which properties to use to relate the two.

Second, what if you want to find all the information that is known about this disk drive. What partitions does it have? What drive letters are mapped to it? What IRQ's does it use? Just because when you wrote these two classes and you knew that these two were related, doesn't mean that someone who is looking at a list of hundreds of classes will be able to guess which ones are related. Read How To Handle Associator and Reference Queries to see how to actually do this.

Now, let's look at the mechanics of actually creating an association class. Generally association classes have two properties. These properties are of type CIM_Reference (a subtype of string). Here's an example:

[dynamic: ToInstance,
provider("CIMWin32"): ToInstance,
Locale(1033): ToInstance]
class Win32_DiskDriveToDiskPartition : CIM_MediaPresent
{
        [read: ToSubClass, Override("Antecedent"): ToSubClass, key]
Win32_DiskDrive ref Antecedent = NULL;
        [read: ToSubClass, Override("Dependent"): ToSubClass, key]
Win32_DiskPartition ref Dependent = NULL;
};

And here are some sample instances:

instance of Win32_DiskDriveToDiskPartition
{
       Antecedent = "\\\\.\\Root\\CimV2:Win32_DiskDrive.DeviceID=\"\\\\\\\\.\\\\PHYSICALDRIVE0\"";
       Dependent = "\\\\.\\Root\\CimV2:Win32_DiskPartition.DeviceID=\"Disk #0, Partition #0\"";
};

instance of Win32_DiskDriveToDiskPartition
{
       Antecedent = "\\\\.\\Root\\CimV2:Win32_DiskDrive.DeviceID=\"\\\\\\\\.\\\\PHYSICALDRIVE0\"";
       Dependent = "\\\\.\\Root\\CimV2:Win32_DiskPartition.DeviceID=\"Disk #0, Partition #1\"";
};

As you can see, the Antecedent and Dependent properties are simply strings. These strings contain the object path (described elsewhere) of the two related instances. From these two instances, we see that PhysicalDrive0 has two partitions.

With all this in mind, how do we go about creating an association class? One of the easiest ways (not necessarily the most efficient, but easy) is to do something like the code below (note that this is NOT the actual code from the Win32_DiskDriveToPartition class. It has been significantly changed for brevity and clarity).

HRESULT hr = WBEM_S_NO_ERROR;

// Perform queries
//================

TRefPointerCollection<CInstance> DiskDrives;
TRefPointerCollection<CInstance> Partitions;

CHString sQuery1(L"SELECT __PATH, KeyName FROM Win32_DiskDrive"));
CHString sQuery2(L"SELECT __PATH, DeviceID FROM Win32_DiskPartition"));

// grab all of both items that could be endpoints
if (SUCCEEDED(hr = CWbemProviderGlue::GetInstancesByQuery(sQuery1,
&DiskDrives, pMethodContext, L"Root\\Cimv2"))
&&
SUCCEEDED(hr = CWbemProviderGlue::GetInstancesByQuery(sQuery2,
&Partitions,
pMethodContext, L"Root\\Cimv2")))
{

This will populate DiskDrives with all the instances of Win32_DiskDrive, and Partitions with all the instances of Win32_DiskPartition. All that remains is to stitch them together:

CInstancePtr *pDisk, *pPart;

REFPTRCOLLECTION_POSITION posDisk;
REFPTRCOLLECTION_POSITION posPart;
CHString sDiskPath, sPartitionPath;

if ( DiskDrives.BeginEnum( posDisk ) )
{
    while (pDisk = DiskDrives.GetNext(posDisk) && SUCCEEDED(hr))
    {
        if (Partitions.BeginEnum(posPart))
        {
while (pPart = Partitions.GetNext(posPart) &&
      SUCCEEDED(hr))
{
if (IsRelated (pDisk, pPart)
{
pInstance = CreateNewInstance(pMethodContext);

pDisk->GetCHString(L"__PATH", sKey1);
pPart->GetCHString(L"__PATH", sKey2);

pInstance->SetCHString(L"Antecedent", sDiskPath);
pInstance->SetCHString(L"Dependent", sPartitionPath);

hr = Commit(pInstance);
}
}

Partitions.EndEnum();
}
}

DiskDrives.EndEnum();

}    // IF BeginEnum

return hr;

And the IsRelated function might look something like this:

BOOL IsRelated(CInstance *pDisk, CInstance *pPart)
{
    BOOL bRelated = FALSE;

    If (pDisk->GetDWORD(L"Index", dwIndex) &&
    pPart->GetDWORD(L"DiskIndex", dwDiskIndex))
{
bRelated = (dwIndex == dwDiskIndex);
}

return bRelated;
}

It's really easy, although this may not be the most efficient way to do this. To increase the efficiency, you might want to copy the code that enumerates the instances of Win32_DiskDrive into this routine. Or, for the really adventurous, you could create a C++ subclass of the C++ class in which you enumerate the Win32_DiskDrives. Then you could just override the LoadPropertyValues routine to create the association.

The GetObject code isn't much more complicated. You might ask why a GetObject routine is even required for an association class. The answer is that GetObject is the easiest way to check to see if two instances are related. A perfect example of this would be a Win32_GroupUser class (list all the user accounts in a specific group account). If you want to check membership in a group, you could do it with a simple GetObject.

  1. Make sure the two endpoints exist. This can be done by using CWbemProviderGlue::GetInstanceKeysByPath or CWbemProviderGlue::GetInstancePropertiesByPath For more information, see Using Per-Property Gets in Framework Providers.
  2. Make sure the two endpoints are the classes you claim them to be. What if they passed a perfectly valid object path to your DiskPartition class, but it was a pointer to a mouse?.
  3. Use the IsRelated method to verify that the endpoints are related.

Finally, what about ExecQuery? If you're not sure whether you need to write ExecQuery, read How To Write an ExecQuery Routine (and Why You Should). ExecQuery works the same way for association classes that it does for regular classes.

Consider the Win32_GroupUser class mentioned above. If the client makes the query "SELECT * FROM Win32_GroupUser WHERE Antecedent="Win32_Group.Name=\"Domain Admins\"", ExecQuery can satisy this query relatively easily. In general, queries are much faster than falling back on a complete enumeration.


Default Parameters in Framework Functions

There are a number of functions in the framework that support optional parameters. However, you will get best results if you ignore the defaults and specify all of the parameters to the following functions:

Provider::Provider

CWbemProviderGlue::GetAllDerivedInstances

CWbemProviderGlue::GetInstanceByPath

CWbemProviderGlue::GetInstancesByQuery

CWbemProviderGlue::GetEmptyInstance

CWbemProviderGlue::IsDerivedFrom

Note The prototype of the Provider constructor is

Provider::Provider(
LPCWSTR a_pszName,
LPCWSTR a_pszNameSpace = NULL
);

For functions that take a MethodContext as a parameter, such as EnumerateInstances and ExecQuery, you can use the MethodContext you were passed. You can also get a MethodContext from a CInstance by calling the CInstance:: GetMethodContext method.


What is a Status Object?

You can use instances of classes derived from __ExtendedStatus to report status and error conditions to calling functions. If the HRESULT you are going to be return from your provider is a failure code, that is, any value larger than 0x80000000, you can return a status object of your own.This status object will be propagated by WinMgmt back to the client. You can create your own class that derives from __ExtendedStatus to include whatever properties you want. For an example of this, see the FrameworkProv sample that ships with the WMI SDK. Search for the string pErrorInstance. Also look for the ReindeerError class defined in the FrameworkProv.MOF file.

One of the problems programmers have had historically is what to return as an error. In most cases, all you can return is a 32 bit integer. It's hard to describe much with that. Even when the system allows for a more detailed error message, how do you produce an error message that is detailed enough to allow a technician to solve the problem without overwhelming the data entry clerk, who is likely to be the first person to see it?

Let's say that in order to shut down some process, you need to read information from your configuration file. However, when you go to read your configuration file, you find it has been deleted. What can you say with a 32 bit integer? Something like, "Error: 2 File Not Found". This could be really confusing for the user, who doesn't know what the file in question is.

Now let's look at how you might use an status object to solve this problem. You could create a class derived from __ExtendedStatus with a single property, that is, an embedded object. You could have the outermost object populate the description with a general error message, and use the embedded object to drill down to a more detailed description. You could have layers of errors describing not only what happened, but how you got there. For example:

Failed to shut down Service.

Failed to locate service name

Failed to open configuration file C:\Winnt\System\foo.ini. LastError=2

This idea is very powerful, and also very easy to implement.


A Few Thoughts on Framework Provider Security

When a framework provider is first called, the thread it is running on is impersonating the client that called it. Keep in mind that that client may be an administrator with full rights, or a user with very limited rights.

Impersonation raises the question of what to do if you are enumerating instances, and you have the authority to populate some properties, but not others. The general rule of thumb is, if you can get enough information to populate the key properties, return the instance with the return code WBEM_S_PARTIAL_RESULTS.

Be careful when writing your GetObject routine. Returning WBEM_E_ACCESS_DENIED may tell a caller that an object exists, even though they have no rights to see it.

If you need to, you can use functions such as Window NT's OpenThreadToken, RevertToSelf and ImpersonateLoggedOnUser functions to run in WinMgmt's context (usually Local System). Be aware that under certain circumstances OpenThreadToken might fail. This usually means that you are already running under WinMgmt's context, as may happen when eventing is being used.

If you make calls back into WinMgmt using an IWbemServices pointer, WinMgmt may change the user context on you back to Local System. Be prepared to set it back the way you want it. CWbemProviderGlue functions (other than calls used with the pointer returned from CWbemProviderGlue::GetNamespaceConnection) handle this for you, but if you make direct calls back into WinMgmt (see Out of Process Framework Providers), you will need to handle this yourself.

Clients that want to call framework providers must connect with either Impersonate or Delegate impersonation levels.

If you are going to be calling the Windows NT function AdjustTokenPrivileges, be aware of a limitation in COM. The client who is making the call must not only have the right, he must have it ENABLED before he makes the call to a provider on the same machine.

For more information on provider security issues, see Security and Authentication. See also the discussion on running WinMgmt as an executable file in How To Debug a Provider.


Out of Process Framework Providers

In general, the framework supports out-of-process providers. However, calls back to WinMgmt using functions such as CWbemProviderGlue::GetInstancesByQuery will not be successful. In fact, calling any CWbemProviderGlue function that takes a MethodContext as a parameter (with the exception of SetStatusObject), will fail when run out-of-process.

To work around this, you need to call CWbemProviderGlue::GetNamespaceConnection and make your IWbemServices calls directly. Make sure you set the security on the IWbemServices pointer returned from the GetNamespaceConnection call, as well as on any enumerators that are returned.

For more information on provider security issues, see Security and Authentication.


Multithreading Issues

It is beyond the scope of this document to try to define the difference between the various threading models. If possible, you should plan on using the 'Both' model. Note that the Provider Code Generator generates code that assumes the 'Apartment' model (the most restrictive). This means that if two clients try to call your provider at the same time, the second will have to wait until the first one is complete.

To change the code to support the less restrictive 'Both' model, follow these steps:

  1. Scroll down to the function DllRegisterServer and in the MAINDLL.CPP file and find these lines:
    //    if(Is4OrMore())
//        pModel = "Both";
//    else
        pModel = "Apartment";
  2. Uncomment the first three lines. The resulting lines appear below:
  3. if(Is4OrMore())
  4. pModel = "Both";
  5. else
  6. pModel = "Apartment";
  9. If you make these changes, WinMgmt can (and frequently will) call you on several threads with several different requests at the same time.

Signs of a class that may have problems running multithreaded:

  • Use of static variables that are changed outside the Provider::Provider derived constructor.
  • Creating and using member variables in your Provider::Provider derived class that are changed outside the constructor.

For classes that will be sharing data across threads, be aware that the Provider class derives from CThreadBase. CThreadBase has several functions that may be useful.


Zero Instances Versus Error - A Philosophical Debate

Windows Management Instrumentation

›Zero Instances Versus Error – A Philosophical Debate

Let's say that you have written a class to report job instances. The enumeration is done by talking to a job service. If the client calls the enumeration function, and you find that the job service is not running, do you return an error? Or just return zero instances?

This question has raised quite a debate. If you return zero instances, you may be 'hiding' the fact that there is a problem. However, if you return an error, then clients that run associator queries or deep enumerations that hit your class will return an error. If enough classes do this, no one will ever be able to run an Associator query without hitting an error.

An ideal compromise would be to return some sort of WBEM_S_INFO_OBJECT, indicating that something interesting happened. The calling function can examine the status object to see what happened. However, COM won't allow the status object to be returned unless you send back a failure code.

For more information on status objects, see What is a Status Object?


What is a MethodContext Anyway?

This question really boarders on being a WinMgmt issue instead of a framework issue. However, per-property gets and PutInstance both use a MethodContext, so some comments are probably in order. A MethodContext is mostly a wrapper for an IWbemContext object.

When a client makes an IWbemServices call, one of the parameters is an IWbemContext object. In many (hopefully most) cases, the client will specify a NULL here. The context object allows the client to pass provider-specific information through to the provider. The problem with using the context object is that it means a program has to have special knowledge to be able to talk to your provider. That rather defeats the purpose of using WinMgmt to present a common interface to management capabilities.

While we hope that clients will always specify NULL here, WinMgmt ALWAYS passes a context object down to the provider. If the provider ever makes a call back into WinMgmt, it MUST pass this context object back in. This allows WinMgmt to perform deadlock prevention.

There are two well-known uses for context objects that providers can use. One is __GET_EXTENSIONS, and the other is __PUT_EXTENSIONS. For more information, see How To Use Per-Property Gets.

If you plan on reading properties from the method context object, you should do so before making any calls back into WinMgmt. Under certain circumstances, the call back into WinMgmt could remove or change the context properties you are looking for.


WBEMTime, WBEMTimeSpan, and FAT versus NTFS Time

Time always presents a problem for management applications. Times are stored in so many formats that trying to deal with them all can be a complex issue. When you include the fact that management is frequently done across time zones (which most of those time structures don't account for), and throw in daylight savings time for good measure, the complexity increases.

DMTF creates yet another time format. This means that you may need to convert your existing time format fields to this new format. This is where the utility classes WBEMTime and WBEMTimeSpan come in.

These classes have constructors that take several of the common date/time formats, and converts them to DMTF strings, and vice versa. They also have functions to help you convert from Greenwich time to local time, and to perform date arithmetic.

One interesting problem that can occur with time formats is when reading date/times from files stored on a FAT partition. Unlike NTFS which stores its times in Greenwich time, FAT stores them as local time. So, if you were writing a class that reported the time for a file like Kernel32.dll on a Windows 95 machine, you have something of a problem.

Looked at in File Explorer, all the kernel32.dll files for Windows 95 should have the same time, right? But how do they do that? After all, the FindFirstFile function returns times in Greenwich time. And when the File Explorer goes to convert these from Greenwich time to local time in Seattle, it has to add a different number than when it goes to convert them to local time in Rome.

So, what do you report for these files? You can report the local times for these files:

Seattle:  19960824111100.000000-480
Rome:     19960824111100.000000+060

Or the Greenwich time reported by the FindFirstFile:

Seattle:  19960824103100.000000-000
Rome:     19960824112100.000000+000

However, both of these cases make it look like these files have different times, when in fact, it is the same file. The problem here is that FAT just doesn't understand about UTC offsets. Fortunately, the DMTF format allows for "fields which are not significant" to be set to an asterisk. So, these times are reported as:

Seattle:  19960824111100.000000+***
Rome:     19960824111100.000000+***


How To Support Per-Property Gets

There are a number of cases when a client will need to be able to determine whether an object exists, but doesn't really need to retrieve any of the properties of the class.

A perfect example of this can be seen in running an associators query against the Win32_CDRomDrive class. The first thing WinMgmt does is call GetObject against the this class to make sure the instance we are running against really exists. Unfortunately, there are several really expensive properties in this class. This makes the associators query take a really long time. And to add insult to injury, WinMgmt just throws those expensive properties away unused.

If only there were a way to ask for just the properties you need. Unfortunately, queries aren't a very good fit here. After all, it isn't required for a provider to support queries. If WinMgmt were to make a query call, and the class didn't support queries, the class might fall back on enumeration. That could make for a truly slow performance.

WinMgmt has defined a way to specify that both CreateInstanceEnum and GetObject should only return certain properties. For more information, read about the __GET_EXTENSIONS flag in Per-Property Operations. Note that providers are not required to support this extension. However, there can be clear performance wins to providers that do.

If the framework detects that a client is using the __GET_EXTENSIONS against an enumeration, it converts the context object parameters into a SELECT statement, and calls Provider::ExecQuery.

To use __GET_EXTENSIONS with Provider::GetObject, use the overloaded GetObject prototype that has a third parameter which is a query object. This query object is the same type of object that is passed to ExecQuery. If you are using a LoadPropertyValues routine (see How To Write an ExecQuery Routine (and Why You Should)), you can use the same logic in GetObject to populate a DWORD that you used in ExecQuery.

In fact, since the framework always calls this new prototype first (and then tries the old one if that didn't work), you can always use this new prototype, even if you aren't going to use this new parameter.


How To Make Calls Back to WinMgmt to Get Data.

It frequently happens that in order to satisfy a clients request, a provider will need to call back into WinMgmt to retrieve data. A perfect example of this can be seen in the sample code in How To Approach the Creation of an Association Class. The framework provides a number of functions for this purpose.

To get groups of instances:

    CWbemProviderGlue::GetAllInstances
    CWbemProviderGlue::GetAllInstancesAsynch
    CWbemProviderGlue::GetAllDerivedInstances
    CWbemProviderGlue::GetAllDerivedInstancesAsynch
    CWbemProviderGlue::GetInstancesByQuery
    CWbemProviderGlue::GetInstancesByQueryAsynch

Note that GetAllInstances and GetAllDerivedInstances are just wrappers to GetInstancesByQuery, and GetAllInstancesAsynch and GetAllDerivedInstancesAsynch are wrappers to GetInstancesByQueryAsynch.

To retrieve a specific instance:

    CWbemProviderGlue::GetInstanceByPath
    CWbemProviderGlue::GetInstanceKeysByPath (uses per-property gets)
    CWbemProviderGlue::GetInstancePropertiesByPath (uses per-property gets)

Misc:

    CWbemProviderGlue::GetEmptyInstance
    CWbemProviderGlue::IsDerivedFrom

Also, many of the classes in the framework are wrappers for WinMgmt objects. In these cases, there are ways to access the actual object:

    CFrameworkQuery::GetQuery
    CInstance::GetClassObjectInterface
    MethodContext::GetIWBEMContext

And if all else fails, there is a way to get an IWbemServices pointer to make your own calls directly:

    CWbemProviderGlue::GetNamespaceConnection

See also the comments about providers making calls to WinMgmt in What is a MethodContext Anyway?" and A Few Thoughts on Framework Provider Security.


Creating a Subclass

There are several things you need to know if you will be creating a subclass of a class that is already instrumented.

  1. Child classes cannot change the key structure. Specifically, a child class cannot have more, or fewer, or different keys than the parent class.
  2. Child classes cannot return any instances that the parent does not return. However it can (and frequently does) return fewer instances than the parent. It may, in fact, return zero instances.
  3. Child classes can have additional properties, and can override all non-key properties of the parent.
  4. If a child class is going to override a property from the parent, it must use the OVERRIDE qualifier (see Standard Qualifiers). There is a very important reason for this. If a child is going to override a property of a class, and a query is sent to the parent that uses that property in a WHERE clause, the parent may not return the instance, since it can see that the property won't match the WHERE clause. It can't know that the child was going to override that value so that the instance would have satisfied the query. And if a parent doesn't return an instance, the child can't (see number 2 above). If you use the OVERRIDE qualifier, WinMgmt will know to modify the query sent to the parent to exclude any properties that may be overridden by the children.
  5. When an enumeration of the child class is done, WinMgmt will take the path from each instance returned by the child class, and use it to do a GetObject against the parent class. It will then combine the instance from the parent with the instance from the child, with the child properties overriding the parent properties.
  6. When a deep enumeration (or query) of the parent is done, all child classes are also enumerated (or receive a similar query to what was sent to the parent). Because of the need to combine child instances with parent instances, WinMgmt frequently can not send instances back to the client until the enumerations of all the child classes are complete.
  7. A child class only needs to populate properties that it will be overriding, or that are declared in the child class (plus the key). Since WinMgmt will be combining the properties from the parent class, it is usually more performant for a child to not populate more properties that it must.
  8. It is illegal for two sibling classes to return the same instance, that is, to have key properties with the same value.


WMI Development Environment

To add Windows Management Instrumentation (WMI) functionality to your application, you can use WMI development tools, languages, and applications. The following sections give detailed information about the WMI development environment.

Section | Description
Applications Guide | Information on the following WMI applications: WMI Object Browser, WMI CIM Studio, WMI Event Registration Tool, and WMI Event Viewer.
ActiveX Controls | Suite of Microsoft® ActiveX® controls that uses the native WMI APIs to perform logically-related functions.
Managed Object Format (MOF) Language | Defining static or dynamic classes and class instances using the MOF compiler.
WMI Query Language | Subset of ANSI SQL with minor semantic changes to support WMI.
Programmatic Access | Programmatic creation and manipulation of classes, instances, properties, and methods.
Using DCOM Security from WMI | Authentication and impersonation security settings.
Utility Classes | Classes to assist the C++ programmer.
Association Support | Limitations on association support within WMI.
Log Files | Files that contain trace information and error messages, useful for resolving problems with WMI, a provider, or your client application.

For specific background information on WMI, see WMI Application Programming and WMI Provider Programming. For all WMI reference material, see WMI Reference.


Applications Guide

The Windows Management Instrumentation (WMI) SDK includes the following Windows Management Instrumentation (WMI) applications:

  • WMI Object Browser

    WMI Object Browser can be used to view objects in a Common Information Model (CIM) repository. You can also edit property values, edit object and property qualifiers, and run selected methods.

  • WMI CIM Studio

    WMI CIM Studio can be used to view classes in a CIM repository. You can also edit classes, properties, qualifiers, and instances; run selected methods; generate and compile Managed Object Format (MOF) files; and generate framework provider code.

  • WMI Event Registration Tool

    WMI Event Registration Tool is a graphical interface used to configure permanent event consumers. Using the tool, users can create or view instances of event consumers, filters, bindings, and timer system classes.

  • WMI Event Viewer

    WMI Event Viewer displays events for all instances of registered consumers. You can also start WMI Event Registration Tool from WMI Event Viewer.

This document provides a brief description of these applications and how to use them. For general application information, including logon instructions, see Using WMI Applications.


Using WMI Applications

This section contains the following topics:

  • System Requirements for WMI Applications
  • WMI Application Logon
  • Custom Views in CIM Studio and Object Browser


System Requirements for WMI Applications

To use WMI applications, your system must include the following hardware and software:

  • Microsoft® Windows NT® version 4.0, SP5 or later or Microsoft® Windows® 2000.
  • Microsoft® Internet Explorer version 5.0 or later. You can download the latest version of Internet Explorer from http://www.microsoft.com/ie.
  • Screen resolution of at least 800 X 600.


WMI Application Logon

When you start any WMI application, you will be presented with the Connect to namespace dialog box. The default namespace is that of the local computer (\root\CIMV2). To connect to another namespace on the local computer or on another computer on the network, either enter the path name or click Browse For Namespace ( [image]).

After you connect to a namespace, you must complete a logon dialog box. This dialog box may also appear at other times while you are using the WMI applications (when you connect to a namespace on a remote computer, for example). This dialog box is the same for all WMI applications, except that the name of the application that you are logging on to is displayed as the title of the dialog box.

To change either the impersonation level, the authentication level, or authority, click Options and expand the logon dialog box. You can choose new impersonation and authentication levels from the associated lists.

When you log on to a local namespace, the Login as current user check box is selected, and the Username, Password, and Authority boxes are unavailable. When you log on to a remote namespace, Username, Password, and Authority are available.

You can log on to your local computer as the current user. You can log on to a remote computer as either the current user or a different user. In either case, you must be an authorized WMI user.

The Authority box is used to specify NTLM or Kerberos authentication.

  • If the text you enter in Authority begins with the string "kerberos:", Kerberos authentication will be used and the text in Authority should contain a Kerberos principal name. For example, Kerberos:<principal name>.
  • If the text you enter in Authority contains any other value, or begins with the string "NTLMDOMAIN:", NTLM authentication will be used and text in Authority should contain a NTLM domain name. For example, NTLMDOMAIN:<domain name>.
  • If you leave this box empty when connecting to a remote system, the operating system will negotiate with DCOM to determine whether NTLM or Kerberos authentication will be used

To complete a WMI logon dialog box

  1. If you are logging in as the current user on the local computer, click OK.
  2. If you are logging in on a remote computer do one of the following.
    1. If you have the proper permissions on the remote computer, you may login as the current user by clicking OK.
    2. If you do not have the proper permissions on the remote computer or you want to login as a different user, click to clear Login as current user and enter your information in Username and Password. The user name can be in the form domain\user. Click OK.

By default, all members of the local users group on Windows NT/Windows 2000 systems have read-only access to all namespaces. To change the default access permissions from Windows NT, use the WMI Control application (Wbemcntl.exe). To change the default access permissions from Windows 2000, use the Microsoft® Management Console.


Custom Views in CIM Studio and Object Browser

Custom views provide non-generic views of objects contained in the WMI database. The WMI CIM Studio and WMI Object Browser applications may use these custom views to display application-specific views of WMI objects. For example, a custom view of a disk drive might show the amount of free space in a bar chart, and so on. For more information, see the following topics:

  • Creating Custom View OCXs
  • Considerations for Building Your Own WMI Client Application


Creating Custom View OCXs

Any number of views can be defined for each class stored in the WMI database. To add a custom view to the WMI database, it is necessary to create a new instance of the ClassView class. The WMI CIM Studio and Object Browser applications determine what custom views are available for a given class by querying for all instances of ClassView such that the ClassName property is equal to the current class being displayed.

The following is an example of a MOF file that can be compiled to define a custom view for the Win32_LogicalDisk class. In this MOF file, the id property takes the form of Classname.Viewname, so that custom views can be uniquely identified and easily recognized. For more information, see Building the Win32_LogicalDisk Sample.

#pragma namespace("\\\\.\\root\\cimv2")

class ClassView
{
            [key] string id;
            string title;
            string ClassName;
            string classid;
            string codebase;
            string version;
};
instance of ClassView
{
            id = "Win32_LogicalDisk.View1";
            title = "Custom View of Win32_LogicalDisk";
            ClassName = "Win32_LogicalDisk";
            classid = "{D5FF1886-0191-11D2-853D-00C04FD7BB08}";
            codebase = "";
            version = "1.0";
};


Building the Win32_LogicalDisk Sample

The application can be built from the command prompt using NMAKE, or it can be built using Microsoft® Visual C++®.

To build the application from the command prompt

Use the NMAKE command in the following manner:

NMAKE /f "Makefile"

To build the application using Visual C++

  1. From the File menu, choose Open Workspace.
  2. Select the Win32LogicalDisk.dsp sample file found in the WMI SDK directory under \Samples\Vc\Customviews.
  3. Build the application which will create the Win32LogicalDisk.ocx file.

To register the Win32LogicalDisk.ocx file

  1. Use the command line regsvr32 to register the resulting Win32LogicalDisk.ocx file as shown below:
    regsvr32 Win32LogicalDisk.ocx

To see the Win32LogicalDisk sample in CIM Studio

  1. Start the WMI CIM Studio application.
  2. Use the MOF Compiler Wizard to compile the CustomView.mof file included with the sample.
  3. Select the Win32_LogicalDisk class in the class tree.
  4. In the Object Viewer (right pane), click Instances to display all instances of Win32_LogicalDisk on your local machine.
  5. Double-click one of the instances to go to the single object view for that instance. At this point, the custom view available for instances of this class is recognized.
  6. Click the Views button and click Views.... A dialog box displays a list of the available views for this object. One of them is the "Custom View of Win32_LogicalDisk", which is implemented by our sample ocx. Selecting this option and clicking OK displays the custom view showing (in this example) the total versus free disk space on the current disk object.


Considerations for Building Your Own WMI Client Application

  • If you want your client to run on Windows NT and non-DCOM versions of Windows 95, manually load Ole32.dll and see if the function CoInitializeSecurity() exists. This function won't exist on Windows 95 installations that don't have DCOM installed separately. If it doesn't exist, the asynchronous routines in this sample won't work because of mismatched security level problems. The synchronous techniques will still work.
  • If you don't care about non-DCOM versions of Windows 95, you can define _WIN32_DCOM so that CoInitializeSecurity() is available for implicit linking. Don't use _WIN32_WINNT to get this prototype since it won't compile under the Windows 95/98 operating systems.
  • In any case, the CoInitializeSecurity() call (in InitInstance()) is required to work around a security problem when WMI tries to call a Sink object but won't identify itself. The CoInitializeSecurity() call turns off the authentication requirement.
  • WMI interfaces are defined in Wbemcli.h and Wbemprov.h, both found in the \Wmi\Include directory. You may #include both these files by including just Wbemidl.h located in the same directory.
  • WMI interface CLSIDs are defined in Wbemuuid.lib. If you get unresolved externals in interfaces and CLSIDs, this is what is missing.
  • You'll need to link with Oleaut32.lib and Ole32.lib to get the needed COM support.
  • In the Link|Output settings, specify 'wWinMainCRTStartup' as the entry point. This is per the Unicode programming instructions.
  • If you're using the makefiles, don't forget to set the VC variables. In Visual C++ version 6.0, it is Vcvars32.bat.


WMI Object Browser

WMI Object Browser is an application designed for use by system managers. Using this application, you can display the object tree for a Common Information Model (CIM) repository, view object details (properties, methods, qualifiers, and associations), edit some object information, and run selected methods. For more information, see the following topics:

  • Starting WMI Object Browser
  • WMI Object Browser User Interface
  • WMI Object Browser Functions


Starting WMI Object Browser

To start WMI Object Browser

  1. On the Start menu, point to Programs, and then click WMI SDK.
  2. Click WMI Object Browser.
  3. In the Connect to namespace dialog box, enter a namespace and click OK. For more information about logging in to a namespace, see WMI Application Logon.

    After logging in, if you have previously accessed the selected namespace in WMI Object Browser, the object tree appears. If this is the first time you are accessing the namespace, you must select an initial object tree root.

  4. At the first access of the namespace, use the Select Initial Tree Root dialog box to browse classes and their instances and then choose an instance as the root of the object tree. This dialog box initially lists only the classes in the current namespace that can have instances.
  5. In the Select Initial Tree Root dialog box, select Show all classes to see all classes in the current namespace, or Show Associations to display association classes. Classes that cannot have instances (abstract classes) appear in bold type.
  6. For each class to browse, click the class name in the Available Classes list and then click Add>>.

    Each class added appears in the Browse for objects in box. (For quicker selection, you can start typing the class name in the Available Classes box to move directly to the class location in the list.) You can remove selected classes from the search by clicking the class name in the Browse for objects in box, and then clicking Remove.

  7. When you are done choosing classes, click OK.
  8. Click the instance to be the root and click OK.

    The object tree appears in WMI Object Browser with the selected instance as the root. Note that WMI Object Browser uses the selected root as the default root whenever you subsequently access the namespace. You can change this by using the Make Initial Tree Root function.

Note An instance of the Win32_ComputerSystem class is the default root for the Root\Cimv2 namespace.


WMI Object Browser User Interface

WMI Object Browser contains an Object Explorer and an Object Viewer. In general, you select objects in the Object Explorer, and their details appear in the Object Viewer. A sample WMI Object Browser screen is shown below.


Object Explorer

The left pane in the WMI Object Browser is the Object Explorer, which shows the object tree contained in the current namespace. By default, the Root\CIMV2 namespace on the local computer appears. You can select a different local namespace or a namespace on a remote computer.

The Object Explorer shows a hierarchy of the instances that are found in a certain namespace following association links. Since this tree really represents a graph, any instance in the namespace can be selected as the root of the tree. The root can be changed temporarily in a session (through re-rooting the tree) or permanently (through schema) so that the selected root persists among WMI Object Browser sessions.

The tree always starts with an instance in the selected namespace. When that instance is expanded, each node in the next level represents a different type of association that this instance participates in (or a different role in the same association). These nodes are labeled in the form <association.role>, where "association" is the association class, and "role" is the role that the associated object plays in this association class. Expanding the tree one additional level, the nodes represent either the actual instance that is associated to the original object (if there is only one instance of a particular class) or a group of all instances of a particular class that are associated to the original object. In the latter case, expansion of one more level shows the actual instances of that class that are associated to the original object. For any node that represents an instance, the same type of expansion applies again.

The tree shows regular objects and grouping nodes. Grouping nodes are not objects themselves but are a way to organize objects. The symbols next to the names indicate the type of object or node.

Symbol | Description
 | Regular object.
 | Node that groups objects by type (class).
 | Node that groups objects by association type (class) and role. All objects beneath this type of node are associated with the parent object through the same association type and role.

Some of these symbols are also used in the Object Viewer.

Hovering over an object in the tree displays the object's path. The object path identifies the object in the namespace. You can also change the root of the object tree. For instructions, see Rerooting an Object Tree.

The Object Explorer also includes the following buttons.

Button | Description
 | Browse for Namespace allows you to browse and select namespaces on the local computer or a remote computer. For information, see Browsing for a Namespace.
 | Browse for Instance allows you to browse classes for a specific instance and reroot the Object Explorer tree from that instance. For information, see Using Browse for Instance to Reroot the Object Tree.


Object Viewer

The right pane in WMI Object Browser is the Object Viewer, which displays details about a selected object. Using the tabs, you can display the properties, methods, and associations for an object. For additional information on each of these views, see WMI Object Browser Functions.

Selecting a regular object in the Object Explorer automatically updates the Object Viewer to show details about that object. Selecting a grouping node updates the Object Viewer to show an instances table for that node. This table represents all instances that are contained under the selected node. For example, for an association.role grouping node, the table will show all instances associated to the original object in the tree through this association type and in this role.

The top of the Object Viewer displays a title of the current view. For a single object, the title is the object path of the instance currently displayed. For a multiple-object table, the title describes the group of objects currently displayed.

The Object Viewer uses an additional symbol to identify association objects ( [image]) on the Associations tab.

The Object Viewer includes the following buttons.

Button | Description
 |  | Back/Forward displays previously-viewed tabs.
 |  | Save commits changed information to Windows Management.
 |  | Views switches to filtered or custom views of object data. See Filtering Views of Object Properties and Displaying Custom Views of Object Data.
 |  | Help for Class displays help information about the selected object class.
 |  | Help opens the WMI online documentation.


WMI Object Browser Functions

Using WMI Object Browser, you can do the following:

  • Display the object tree contained in a specified CIM repository.
  • Reroot the object tree.
  • Display properties, methods, and associations for a selected object.
  • Display custom views of object data.
  • Display instances of grouped objects.
  • Display property and object qualifiers.
  • Execute methods on a selected object.
  • Edit property values and object and property qualifiers.

Note If an error occurs while you are editing object properties or qualifiers (for example, if you enter a property type and value that are incompatible), a message box appears with a brief description of the problem. In some cases, Windows Management or the provider involved supply an error object with additional detailed information about the problem that occurred. Click Advanced to view the error object's properties. The property display contains more details about the problem that occurred.

Error objects are instances of the __ExtendedStatus class (or derivatives of this class).


Displaying an Object Tree

By default, WMI Object Browser sets the namespace to root\CIMV2, which is the default namespace on the local computer. You can view the object tree for any namespace in your system or on a network by specifying the namespace path in one of the following ways:

  • Specifying the namespace in the Objects in Box
  • Selecting the namespace from the history list
  • Browsing for a Namespace
  • Using the Go to Namespace function

Note While WMI Object Browser runs with any repository, a repository that has no associations shows only a single object, the root selected by the user. This type of repository can be viewed more effectively in WMI CIM Studio.


Specifying the Namespace in the Objects in Box

The format for specifying a namespace in the Objects in box is as follows:

[\\computer\]root\namespace

For example, specifying \\EDKDOCS5\root\CIMV2 displays the object tree for the CIMV2 namespace on the computer, EDKDOCS5. If no computer is specified, the default is the local computer. You can also specify a chain of namespaces, separating each with a backslash.

\\computer\root\namespace\namespace\namespace

The Objects in box also keeps a list of previously used namespaces. Click the arrow to choose a namespace from this history list.


Selecting the Namespace from the History List

The Objects in box keeps a list of previously selected namespaces. Click the arrow to select a namespace from this history list.


Browsing for a Namespace

To browse for a namespace

  1. Click Browse for Namespace.
  2. In the Browse for Namespace dialog box, Machine Name shows the local computer by default. To select a namespace on another computer, enter that computer name, proceeded by '\\', in the Machine Name box, and click Connect.

    —or—

    Click Network Neighborhood, select the remote computer from the list that appears, and then click OK.

    The first time a user connects the WMI Active X controls to a namespace, the WMI Login dialog box is presented. Upon successful logon, the connection is cached for future use. If the Browse for Namespace dialog box is used to re-open a namespace, any currently available connections will be re-used by default. To use a new set of credentials to connect to a namespace (such as a new username/password), clear the Use existing connection if possible check box. This results in the existing connection being closed and the WMI Login dialog box being presented when the namespace is selected. Completing this dialog box makes a connection to the requested computer and returns to the Browse for Namespace dialog box with an initialized tree of the existing namespace on that computer.

  3. In the Starting Namespace box, enter the complete path (starting at root) of the namespace to browse. Note that the last namespace in the path must be one you have access to. It is important that you know what namespaces you have access to, since you cannot discover them by browsing parent namespaces for which you do not have access.

    For example, given the set of namespaces root, root\private, and root\private\you, your access to root and root\private\you but not to root\private would prevent you from browsing downward from Root to root\private\you. You would have to enter root\private\you directly in Starting Namespace.

  4. Click the plus sign (+) next to any namespace to display the namespaces under it. If you do not have access to the namespace, it will not open to reveal the namespaces under it.
  5. Click the namespace to use and then click OK.

    This returns you to WMI Object Browser, where you will see the object tree for the selected namespace. If a default root node is defined for this namespace, the object tree will use that for the initial root object. If not, the instance search tool will be displayed to let the user select a root. See Using Browse for Instance to Reroot the Object Tree.,


Using the Go to Namespace Function

The object tree can contain objects from other namespaces. If an object is from another namespace, the object's full path (including the computer name if it resides on a different computer) appears in the tree. You can display the tree for that object's namespace by using the Go to Namespace function.

To use the Go to Namespace function

Right-click the object whose namespace you want to display and click Go to Namespace. The object tree for the namespace appears rooted at the selected object.


Rerooting an Object Tree

In WMI Object Browser, when you connect to a namespace for the first time, you must set the initial tree root. The selected root is then used as the default whenever you subsequently access the namespace. You can reroot the object tree during an WMI Object Browser session, and you can also select a new initial root.

The default root that the Object Explorer uses for any given namespace is stored in the CIM repository in the schema. For every namespace accessed by WMI Object Browser, the NamespaceConfiguration class is defined, and an instance of it defines the current default root of the object tree.

Any regular object can be made the root of the object tree by using one of the following methods:

  • Using Make Initial Tree Root
  • Using Make Root to Reroot the Object Tree
  • Using Browse for Instance to Reroot the Object Tree


Using Make Initial Tree Root

To change the default initial object tree root

Right-click the object to be made the initial root and click Make Initial Tree Root. Because only regular objects can be made the root of the tree, Make Initial Tree Root is not available if grouping nodes are selected.

The new default object tree root takes effect the next time you connect to the namespace.


Using Make Root to Reroot the Object Tree

To change the root of the object tree

Right-click the object to be the new root and click Make Root. Because only regular objects can be made the root of the tree, Make Root is not available if grouping nodes are selected.

The following screens show how the tree display changes when different roots are selected.

Root = Win32_OperatingSystem Root = Win32_CDRomDrive


Using Browse for Instance to Reroot the Object Tree

You can reroot the object tree from a specific instance by using the Browse for Instance function. The Browse for Instance function allows you to display all objects in the selected classes. You can then select the object to be the new root of the object tree.

To browse for an instance

  1. In the Object Explorer, click Browse for Instance.
  2. In the Browse for Instance dialog box, select Show all classes to see all classes in the current namespace.

    By default, this dialog box shows the list of classes that can have instances. Classes that cannot have instances (abstract classes) appear in bold type.

  3. Select the Show Associations check box to display association classes.
  4. For each class to browse, click the class name in the Available Classes list and then click Add ->.

    Each class selected appears in the Browse for objects in box. (For quicker selection, you can start typing the class name in the Available Classes box to move directly to that class location in the list.)

    You can remove selected classes from the search by clicking the class name in the Browse for objects box and then clicking <- Remove.

  5. Click OK.
  6. In the Browse for Instance results, click the object to be the root of the object tree and then click OK to return to WMI Object Browser.

    The object tree appears with the selected object as the new root.


Displaying Properties of Regular Objects

To display properties of regular objects

Select the object in the Object Explorer and click the Properties tab in the Object Viewer.

The Properties tab displays the properties for a selected regular object. Symbols in the Properties tab provide the following information about the object's class.

Symbol | Description
 | Indicates a key property.
 | Indicates a system property. System property names are preceded by a double underscore (for example, __SERVER). Note that you cannot change or delete system properties. Properties cannot begin with a double underscore because the double-underscore is a sequence that is reserved for system use. Non-system properties are either defined by the user or inherited from parent classes. For more information, see WMI System Properties.
 | Indicates a local property.
 | Indicates an inherited property.
 | Indicates that the property is writeable.

A small triangle in the column head indicates which column is being used to sort the information and the sort direction (up or down). You can change how the information is sorted by clicking a column head.

The following example shows the properties of the Win32_CDRomDrive object.

See Also

Displaying Properties of Association Objects


Filtering Views of Object Properties

The default view of object data shows all properties — system, local, and inherited. You can filter this view to hide system and or inherited properties.

To filter views of object data

  1. Click the object to view and click the Properties tab.
  2. Click Views and then click Property Filters.
  3. Select or clear the filters for the desired view:
    • Show system properties
    • Show inherited properties

    Clearing these filters hides the properties in the Properties tab display.

  4. Click OK.


Displaying Custom Views of Object Data

By default, the Properties tab shows the generic view of an object's data. Developers can create custom views of data and associate those views with specific objects. If a custom view is available for an object, the Custom Views option is available. For more information about creating a custom view, see Custom Views in CIM Studio and Object Browser.

To display a custom view

  1. Click the Views button and click Views….
  2. In the Views window, select a view from the list and then click OK.
  3. To return to the generic view, click the Views button, click Views…, and select Generic View from the list. Then, click OK.

The following custom view shows the amount of free space available on a system's disk drives. The WMI SDK samples directory <drive>:\<WMI-SDK-directory>\Samples\VC\CustomViews contains files and instructions for creating this sample view.


Editing Object Properties

You can edit the Value field of properties that are not read-only.

To edit a property value

  1. Display the Properties tab for the object to change.

    For instructions, see Displaying Properties of Regular Objects or Displaying Properties of Association Objects.

  2. Click the property value to change.
  3. If an arrow appears when you select the value, click the arrow and then choose a value from the list that appears.

    If no arrow appears, enter the new value in the field. When you start typing, the text turns blue and the Save button becomes available; this indicates that the value has not been committed yet.

    If the property type is an array, clicking Array in the Value field opens a dialog box, in which you can enter each value in the array.

  4. When you have finished entering values, click OK to return to the Properties tab.

    If the property type is an object, the Value field contains either <empty> (which represents NULL) or an Object button. To change this field, do one of the following:

    • Click Object to open the Embedded Object dialog box.

      You can edit properties and qualifiers from this box the same way as on the Object Viewer Properties tab. Click OK to return to the Object Viewer.

    • Right-click Object and click Set to <empty>.
    • Right-click the <empty> value and click Create Value.

      This opens the Embedded Object dialog box. Enter the name of the class to which the object belongs. The Properties tab for that class appears. You can edit properties and qualifiers the same way as on the Object Viewer Properties tab. Click OK to return to the Object Viewer.

  5. When you have finished editing, click Save.

    After the changes are saved, the text turns black.

Note Some property values are read-only and cannot be edited.


Displaying Instances

When you select a grouping node in the Object Explorer, the Object Viewer displays an instance table showing all objects in the namespace that belong to the selected group and the common properties of those objects.

From the instance table, you can also display the details for any individual instance. Right-click the instance and then click Go to Object or double-click the row corresponding to the instance to view. This displays the object Properties tab. To return to the instance table, you must reselect the grouping node.

The following screen shows the instance table for the Win32_SerialPort object group.


Displaying Object Methods

To display object methods

Select an object in the Object Explorer and then click the Methods tab in the Object Viewer.

The Methods tab shows all methods that can be applied to the selected object. You can display and execute object methods in the WMI Object Browser, but you can only edit method information in WMI CIM Studio.

To view the parameters defined for a method, right-click on the method row and click Execute Method. To view qualifiers for the method, right-click the method row and select Method Qualifiers.


Executing Object Methods

Methods can be executed on an object if they are implemented and not disabled (this is indicated by qualifiers on the method). If any of these conditions is not met for a certain method, the Execute Method context menu command is unavailable.

To execute a method

  1. Display the Methods tab for the object to work with.

    For more information, see Displaying Object Methods.

  2. Right-click the method and select Execute Method.

    The Method Parameters window shows the parameters used when executing the selected method. The Parameters column shows the parameters defined for this method and their default values.

  3. Before executing the method, set the values for these parameters by editing their values in this table.

    The direction of the parameters is indicated by the symbol in the first column.
    Symbol Description
    Indicates an input property.
    Indicates an output property.
    Indicates an input/output property.

  4. Click Execute. When the method is done executing, you can see the resulting parameter values, including the return value.


Displaying Object Associations

To display object associations

  1. Select an object in the Object Explorer and then click the Associations tab in the Object Viewer.
  2. The Associations tab graphically displays the objects associated with the current object.

The following screen shows all objects associated with the computer system EDKDOCS1, which is the root of the object tree in the example.

On the Associations tab:

  • The left-most symbol always represents the current object, EDKDOCS1 in the preceding screen shot.
  • Each branch from the current object represents an association of that object to another object.
  • The symbol in the middle ( [image]) represents the association object.
  • The right-most symbols represent the objects associated with the current object.

On the Associations tab, you can also:

  • Hover over the association object symbol to display the association type.
  • Hover over the connecting lines on each side of the association object symbol to display the roles of the related objects.
  • Jump to another regular object by double-clicking its symbol.

    For example, double-clicking the symbol next to Win32Service.Name="Messenger" in the preceding screen sample changes the display.

    Selecting another object on the Associations tab updates all displays in the Object Viewer. In this example, the Properties and Methods tabs now display information about the Messenger object.

  • Jump to an association object by double-clicking its symbol.

    In the preceding screen shot, the association object next to Win32Service.Name="LanmanWorkstation" is of the type Win32ServiceToService. Selecting this symbol changes the display.

    This also updates the Properties and Methods tabs to show information for the newly-selected association object.

  • Jump to the Properties tab of an object by right-clicking the object's symbol or name and clicking Properties.
  • Reroot the Associations graph by right-clicking an object symbol and clicking Make Root.
  • Open another namespace.

    Association graphs can contain objects from namespaces other than the current namespace. Right-click the object and select Go to Namespace to display the tree for the object's namespace.


Displaying Properties of Association Objects

To display the properties of an association object

On the Associations tab, double-click the symbol for the association object to display. Then, click the Properties tab. The property details for the selected association object appear.

You can also right-click an object in the Object Explorer and then select Association. The Object Viewer displays the details of the association object that links the selected object to the object above it.

See Also

Displaying Properties of Regular Objects


Editing Properties of Association Objects

You can edit the property values of association objects in the same way as regular objects. For instructions, see Editing Object Properties.


Displaying Object Qualifiers

To display object qualifiers

  1. Click an object in the Object Explorer and click the Properties tab in the Object Viewer.
  2. Right-click anywhere in the grid of the Object Viewer and select Object qualifiers.


Displaying Property Qualifiers

Property qualifiers can only be displayed for non-system properties.

To display property qualifiers

  1. Select an object in the Object Explorer and then click the Properties tab in the Object Viewer.
  2. Double-click the property whose qualifiers you want to display.

    —or—

    Right-click the property whose qualifiers you want to display. Select Property qualifiers.

    If the object has no property qualifiers, the Qualifiers window is blank.

  3. To close the Qualifiers window, click OK or Cancel.

The following screen shows the qualifiers for the Element property of the Win32_OperatingSystem object.


Editing Object and Property Qualifiers

To edit object and property qualifiers

  1. Select an object in the Object Explorer.
  2. Display the Qualifiers (object or property) window for the qualifiers to edit.
  3. Click the field to change.
  4. If an arrow appears when you select the field, click the arrow and choose a value from the list that appears.

    If no arrow appears, enter the new value in the field.

    5. Click the I, C, and O fields to select or cancel these settings.

    The Origin field is read-only. It indicates where the qualifier originated: local (for qualifiers defined in the current object) or propagated (for qualifiers propagated from another object).

    When you start typing, the text turns blue. The Save button becomes available to indicate that the value has not been committed yet.

  6. When you finish editing, click OK to close the Qualifiers window.
  7. In the Object Viewer, click Save.


WMI CIM Studio

WMI Common Information Model (CIM) Studio is an application designed primarily for use by developers, particularly those who are writing providers and for advanced system managers. Using this application, you can:

  • Display the class inheritance tree for a CIM repository.
  • View details on classes and instances (properties, methods, qualifiers, and associations).
  • Edit class and instance information.
  • Run selected operations.

WMI CIM Studio also provides wizards for generating and compiling MOF files and for generating framework provider code. For more information about the WMI CIM Studio, see the following topics:

  • Starting WMI CIM Studio
  • WMI CIM Studio User Interface
  • WMI CIM Studio Functions


Starting WMI CIM Studio

To start WMI CIM Studio

  1. On the Start menu, point to Programs, and then click WMI SDK.
  2. Click WMI CIM Studio.
  3. In the Connect to namespace dialog box, select a namespace.

    The default namespace is Root\CIMV2. You can choose another namespace by typing its name or clicking Browse for Namespace.

  4. After selecting the namespace, click OK.

    For instructions about how to use the WMI Login dialog box, see WMI Application Logon.


WMI CIM Studio User Interface

WMI CIM Studio contains a Class Explorer and a Class Viewer. In general, when you select classes in the Class Explorer, their details appear in the Class Viewer. The WMI CIM Studio wizards generate and compile MOF files and generate framework provider C++ code.

The following screen shot shows the WMI CIM Studio interface.


Class Explorer

The left pane in WMI CIM Studio is the Class Explorer. The Class Explorer shows the selected namespace (root\CIMV2 is the default) and the schema defined for that namespace as a class inheritance tree. The shaded symbols next to the class names indicate the type of objects defined by the class.

Symbol | Description
 | Defines a concrete regular class.
 | Defines an abstract regular class that has one or more concrete classes below it.
 | Defines an abstract regular class that has no concrete classes below it.
 | Defines a concrete association class.
 | Defines an abstract association class that has one or more concrete classes below it.
 | Defines an abstract association class that has no concrete classes below it.

Use the check boxes to select or cancel the selection of classes for the wizard operations performed in WMI CIM Studio. You can select or clear all check boxes by right-clicking anywhere in the Class Explorer and then clicking Select all or Unselect all.

For non-wizard operations, select classes by clicking the class name in the Class Explorer.

The Class Explorer includes the following buttons.

Button | Description
 | Browse for Namespace allows you to browse and select namespaces on the local computer or a remote computer. See Browsing for a Namespace.
 | Search for Class allows you to search for a specific class in the namespace. See Searching for a Class.
 | Add class adds a new class to the current repository. See Adding Class Definitions.
 | Delete class deletes a selected class from the current repository. See Deleting Class Definitions.


Class Viewer

The right pane in WMI CIM Studio is the Class Viewer, which displays details on a selected class. Using the tabs, you can display the properties, methods, and associations defined for a class. For additional information on these views, see Displaying the Definition of an Existing Class. Selecting a class in the Class Explorer automatically updates the Class Viewer display.

The Class Viewer includes the following buttons.

Button | Description
 |  | Create instance creates a new instance of a selected class. See Adding Instances of a Class for more details.
 |  | Delete instance deletes the selected instance. See Deleting Instances of a Class for more details.
 |  | Back/Forward display previously-viewed pages.
 |  | Save commits changed information to Windows Management.
 |  | Instances displays a table of all instances of a selected class. See Displaying an Instance Table.
 |  | Views displays filtered or custom views of class instance data. See Filtering Views of Class Properties and Creating and Using Custom Views of Instances.
 |  | WQL Query opens the WQL query builder where you can compose, store, and execute WQL queries. See Using the WQL Query Builder.
 |  | Help for Class displays help information on the selected class or the class of the selected instance.

For a description of the symbols displayed when viewing the properties of an object, see Displaying Class Properties.


Wizards

[This is preliminary documentation and subject to change.]

The following wizards may be invoked in WMI CIM Studio.

Provider Code Generator Wizard generates framework provider C++ code for a selected class.
MOF Generator Wizard inserts selected class definitions and/or instances from the repository into a text file in the MOF syntax.
MOF Compiler Wizard imports class definitions or instances described in a MOF file into the current repository.
Schema Validation Wizard verifies that the schema is CIM compliant, that the localized versions of the schema are consistent with the non-localized version, and that the schema meets logo certification requirements.
Help opens the WMI online documentation.

When selected, each wizard opens a series of screens that guide you through the operation.


WMI CIM Studio Functions

[This is preliminary documentation and subject to change.]

Using the WMI CIM Studio, you can:

  • Display the class inheritance tree (schema) in a specified CIM repository.
  • Search for a specific class.
  • Display the definition of an existing class (properties, qualifiers, methods, and associations).
  • Display instances of an existing class (standard or custom views).
  • Extend and modify the existing schema by adding or deleting class definitions.
  • Modify a class by adding, editing, or deleting properties, qualifiers, and methods in a class definition.
  • Add or delete instances of a class.
  • Execute methods
  • Run the Provider Code Generator Wizard, MOF file generator, and MOF file compiler on selected classes and/or instances.
  • Verify that one or more classes are CIM compliant using the Schema Validation Wizard.

Note If an error occurs while you are editing class properties or qualifiers (for example, if you enter a property type and value that are incompatible), a message box appears with a brief description of the problem. In some cases, Windows Management or the provider involved provide an error object with additional detailed information about the problem that occurred. Click Advanced to display the error object's properties. The property display contains more details on the problem that occurred.

Error objects are instances of the __ExtendedStatus class (or derivatives of this class).


Displaying a Class Inheritance Tree

By default, WMI CIM Studio sets the namespace to root\CIMV2, the default namespace on the local computer. You can view the class inheritance tree for any namespace in your system or on a network by specifying the namespace path in one of the following ways:

  • Specifying the namespace in the Classes in box
  • Selecting the namespace from the History list
  • Browsing for a namespace

Specifying the Namespace in the Classes in Box

The format for specifying a namespace in the Classes in box is as follows:

\\computer\root\namespace

For example, specifying \\EDKDOCS5\Root\CIMV2 displays the class inheritance tree for the Cimv2 namespace on the computer, EDKDOCS5. If no computer is specified, the default is the local computer. You can also specify a chain of namespaces, separating each with a backslash.

\\computer\root\namespace\namespace\namespace

Selecting a Namespace from the Classes in History List

The Classes in box keeps a list of previously-selected namespaces. Click the Classes in arrow to select a namespace from this history list.

Note The history list exists for the current session only. After you refresh or restart, the list disappears.


Searching for a Class

To search for a specific class in the namespace

  1. In the Class Explorer, click Search for Class.
  2. In the Search for Class dialog box, select one or more check boxes under Search Options to select the type of search to perform: by class name, class description, or property name. Property name searches that use system property names return no classes.
  3. Enter the full or partial text value (class name, class description, or property name) to use for this search.
  4. Click Go. The results of the search appear in the Search results pane.
  5. Click on the class to view, then click OK. This displays the chosen class in Class Explorer.


Displaying the Definition of an Existing Class

Within WMI CIM Studio, you can display the properties, qualifiers, and methods of an existing class.

  • Displaying Class Properties
  • Filtering Views of Class Properties
  • Displaying Class Methods
  • Displaying Class Qualifiers
  • Displaying Property Qualifiers
  • Displaying Method Qualifiers
  • Displaying Class Associations


Displaying Class Properties

To display properties of a class

Select the class in the Class Explorer and then click the Properties tab in the Class Viewer.

Symbols on the Properties tab provide the following information about the class.

Symbol | Description
 | Indicates a key property.
 | Indicates a system property. System property names are preceded by a double underscore (for example, __SERVER). Note that you cannot change or delete system properties. You should not create properties that begin with a double underscore. Non-system properties are either defined by the user or inherited from parent classes. For more information, see WMI System Properties.
 | Indicates a local property.
 | Indicates an inherited property.
 | The pen on a symbol indicates that the property is writable.
 | Displays a dialog box that shows the values contained in a property array.

A small triangle in the column head indicates which column is being used to sort the information and the sort direction (up or down). You can change how the information is sorted by clicking a column head.

The following example screen shows the properties for the Win32_Printer class.


Filtering Views of Class Properties

The default view of class data shows all properties — system, local, and inherited. You can filter this view to hide system and inherited properties.

To filter views of object data

  1. Select the class to view in the Class Explorer and click the Properties tab in the Class Viewer.
  2. Click Views and select Property Filters.
  3. Select or clear the filters for the desired view:
    • Show system properties
    • Show inherited properties

    Clearing these filters hides the properties in the Properties tab display.

  4. Click OK.


Displaying Class Methods

To display class methods

Select the object in the Class Explorer and click the Methods tab in the Class Viewer.

The Methods tab shows all methods that can be applied to the selected class. For more information, see Executing Methods in CIM Studio.


Displaying Class Qualifiers

To display class qualifiers

  1. Select a class in the Class Explorer and click the Properties tab in the Class Viewer.
  2. Right-click the Properties tab and select Object qualifiers.


Displaying Property Qualifiers in the Class Explorer

Property qualifiers can only be displayed for non-system properties.

To display property qualifiers

  1. Select a class in the Class Explorer and click the Properties tab in the Class Viewer.
  2. Double-click the property whose qualifiers you want to display.

    —or—

    Right-click the property whose qualifiers you want to display and select Property qualifiers. If the class has no property qualifiers, the Qualifiers window is blank.

  3. To close the Qualifiers window, click OK or Cancel.


Displaying Method Qualifiers

To display method qualifiers

  1. Select a class in the Class Explorer and click the Methods tab in the Class Viewer.
  2. Right-click the method whose qualifiers you want to view and select Method Qualifiers.
  3. To close the Qualifiers window, click OK or Cancel.


Displaying Class Associations

To display class associations

  1. Select a class in the Class Explorer and click the Associations tab in the Class Viewer.

The class Associations tab, displayed when viewing a class (as opposed to an instance), graphically displays all associations that objects of this class can have with other objects in the namespace. This is a representation of the schema definition of which association classes can connect instances of this class to instances of other classes. The following screen shows classes whose instances could be associated to instances of the Win32_MotherboardDevice class.

On the class Associations tab:

  • The left-most object symbol always represents the current class (Win32_MotherboardDevice in the preceding screen sample).
  • Each branch from the current class represents an association of that class to another class.
  • The symbol in the middle ( [image]) represents the association object class.
  • The right-most symbols represent the classes associated with the current class.

On the class Associations tab, you can:

  • Hover over the association object symbol to display the association type.
  • Hover over the connecting lines on each side of the association object symbol to display the roles of the related classes.
  • Jump to another class by double-clicking its symbol.

    For example, double-clicking the symbol next to CIM_System in the preceding screen sample changes the display.

    Selecting another class on the class Associations tab updates all displays in the Class Viewer. In this example, the Properties and Methods tabs now display information about the CIM_System class.

  • Jump to an association object by double-clicking its symbol.

    In the preceding screen sample, the association object next to CIM_Setting is of the type CIM_ElementSetting. Selecting this symbol changes the display and updates the Properties and Methods tabs to show information for the newly-selected association object.

  • Jump to the Properties tab of an object by right-clicking the object's symbol and selecting Properties.


Displaying Instances of an Existing Class

Within WMI CIM Studio, you can open a table of all instances of a class and view the associations of an instance. You can also define and display custom views of instances.

  • Displaying an Instance Table
  • Displaying Associations of an Instance
  • Creating and Using Custom Views of Instances


Displaying an Instance Table

You can open an instance table for any class in the namespace. An instance table shows all instances of the selected class in the namespace and their common properties.

To display the instance table

  1. Select a class in the Class Explorer and click Instances ( [image]) in the Class Viewer. If there are no instances of the class, the instance table displays the message, "No Instances Available."
  2. To display the details for any individual instance, right-click the instance in the instance table, and then select Go to Object.

    This displays the object's Properties tab. Clicking Instances toggles the display between the instance table and the Properties tab for the selected object.

The following example screen shows all instances of the Win32_ProgramGroup class.


Creating and Using Custom Views of Instances

You can create and display custom views of class instance data. For more information, see the example screen in Displaying Custom Views of Object Data.

To create a custom view of class instance data

  1. Write a Microsoft® ActiveX® control that defines the format for the data display.
  2. Associate that view with the class definition by using a new custom view instance.

    After you have created a custom view and have associated it with a class instance, selecting that instance in the Class Viewer activates the Views option under the Views button.

  3. Click the Views button and select Views….
  4. In the Views window, choose a view from the list that appears and click OK.

    The WMI SDK samples directory <drive>:\<WMI-SDK-directory>\Samples\VC\CustomViews contains files and instructions for creating a sample custom view.


Displaying Associations of an Instance

To display object associations

  1. Select a class in the Class Explorer.
  2. Click Instances ( [image]) in the Class Viewer. If there are no instances of the class, the instance table displays the message, "No Instances Available."
  3. To display the details for any individual instance, right-click the instance in the instance table and then click Go to Object.

    This displays the object's Properties tab. Clicking Instances toggles the display between the instance table and the Properties tab for the selected object.

  4. Click the Associations tab in the Class Viewer.

    The Associations tab graphically displays the objects associated with the current object.

The following screen shows all objects associated with the computer system, EDKDOCS1, which is the root of the object tree in the example.

On the Associations tab:

  • The left-most object symbol always represents the current object, EDKDOCS1, as shown in the preceding screen sample.
  • Each branch from the current object represents an association of that object to another object.
  • The symbol in the middle ( [image]) represents the association object.
  • The right-most object symbols represent the objects associated with the current object.

On the Associations tab, you can also:

  • Hover over the association object symbol to display the association type.
  • Hover over the connecting lines on each side of the association object symbol to display the roles of the related objects.
  • Jump to another regular object by double-clicking its symbol.

    For example, double-clicking the symbol next to Win32Service.Name="Messenger" in the preceding screen sample changes the display.

    Selecting another object on the Associations tab updates all displays in the Class Viewer. In this example, the Properties and Methods tabs now display information about the Messenger object.

  • Jump to an association object by double-clicking its symbol.

    In the preceding screen sample, the association object next to Win32Service.Name="LanmanWorkstation" is of the type Win32ServiceToService. Selecting this symbol changes the display and updates the Properties and Methods tabs to show information for the newly-selected association object.

  • Jump to the Properties tab of an object by right-clicking the object's symbol or name and clicking Properties.
  • Reroot the associations graph by right-clicking an object symbol and selecting Make Root.
  • Open another namespace.

    Association graphs can contain objects from namespaces other than the current namespace. Right-click the object and select Go to Namespace to display the tree for the object's namespace.


Adding Class Definitions

To add a class

  1. In the Class Explorer, select the class from which to derive a new class.
  2. Click Add Class.
  3. In the Add Class dialog box, enter the name of the new class in the New Class box and then click OK.

    The Class Viewer displays the new class in the Properties tab, showing all the parent class's properties that are inherited by the new class.

Note When defining a new class which is an association, the user must define a Boolean object qualifier on the Association class and set it to TRUE to define that this is an association class. This qualifier must be propagated to all instances of the class, so check the "I" box in the qualifier definition.

To add a class at the top level

  1. In the Class Explorer, click Add Class.
  2. In the Add Class dialog box, erase any Parent value (this box should be blank).
  3. Enter the name of the new class in the New Class box and click OK.

For more information on adding properties to a new class, see Adding Class Properties.


Deleting Class Definitions

To delete a class

  1. In the Class Explorer, select the class to delete and click Delete Class.
  2. In the Delete Class Query dialog box, click Yes.

Note When you delete a class, all of its child classes are also deleted.


Modifying Class Definitions

You can modify a class by adding, editing, or deleting properties, qualifiers, and methods in a class definition.

  • Adding Class Properties
  • Renaming Classes in WMI CIM Studio
  • Deleting Class Properties
  • Editing Class Properties
  • Using the Interval Editor
  • Adding Class Methods
  • Deleting Class Methods
  • Editing Class Method Parameters
  • Adding Class, Property, or Method Qualifiers
  • Deleting Class, Property, or Method Qualifiers
  • Editing Class, Property, or Method Qualifiers

Note You cannot change the definition of a class that has subclasses because such changes can result in inconsistencies in the subclasses that cannot be reconciled. Making changes to a class that has subclasses will result in an error when trying to save these changes.


Adding Class Properties

To add a property

  1. Select the class to change in the Class Explorer. Click the Properties tab in the Class Viewer.
  2. Click the blank Name field at the bottom of the properties table and enter the new property name.
  3. Click the Type field, click the arrow, and then choose a property type from the list that appears.

    When you select the type, a default value may appear in the Value field. The Value field will determine the default value for this property. Whenever an instance of this class is created, the value you specify now will be the default value for this property.

  4. For a value other than the default in the Value field, click the field and enter the desired value.

    When you select this field and begin typing, a list may appear from which you can choose the appropriate value.

  5. If the property type is an array, click Array in the Value field to open a dialog box in which you can enter each value in the array.
  6. When you are done entering values, click OK to return to the Properties tab.
  7. To create an embedded object, do the following steps in order:
    1. Select object as the property type.
    2. Optionally, enter the name of the class to which the embedded object belongs and then click OK.
    3. By default, the Value field is set to <empty> (which represents NULL). To change this value, right-click the field, and then click Create Value.

      If you previously entered the name of the class to which the embedded object belongs, the Embedded Object dialog box opens the Properties tab for that class. Otherwise, the display is blank.

    4. Enter the name of the class to which the embedded object belongs in the Class field and press ENTER to display the Properties tab for that class.
    5. Edit the properties and/or qualifiers for the embedded object, if necessary, and then click OK to return to the Class Viewer.
  8. Click Save to save your changes.


Renaming Classes in WMI CIM Studio

To rename a class

Click a class in the Class Explorer tree; then, click the same node again. If the selected class can be renamed, the class name becomes editable and can be changed. If not, an error or warning message will appear.


Deleting Class Properties

To delete a property

  1. Select a class in the Class Explorer and click the Properties tab in the Class Viewer.
  2. Click the gray box to the left of the property to delete.

    This step selects the entire property entry.

  3. Press the DELETE key.
  4. Click OK to delete the property.
  5. Click Save to save your changes.


Editing Class Properties

To edit a property field

  1. Click a class in the Class Explorer and click the Properties tab in the Class Viewer.
  2. Click the field to change.
  3. If an arrow appears when you select the field, click the arrow and choose a value from the list that appears.

    —or—

    If no arrow appears, enter the new value in the field.

    When you start typing, the text turns blue, and the Save button becomes active. This indicates that the value has not been committed yet. If you edit a Value field that contains an array, a dialog box appears that shows each value in the array.

  4. Edit the values to change and then click OK to return to the Properties tab.

    If the property type is an object, the Value field contains either <empty> (which represents NULL) or an Object button.

    To change the Value field, do one of the following:

    • Click Object to open the Embedded Object dialog box.

      You can edit properties and qualifiers from this dialog box in the same way as on the Class Viewer Properties tab. Click OK to return to the Class Viewer.

    • Right-click Object and select Set to <empty>.
    • Right-click the <empty> value and select Create Value.

      This step opens the Embedded Object dialog box. Enter the name of the class to which the object belongs. The Properties tab for that class appears. You can edit properties and qualifiers the same way as on the Class Viewer Properties tab. Click OK to return to the Class Viewer.

  5. When you have finished editing, click Save. After the changes are saved, the text turns black.


Using the Interval Editor

An interval is a form of the DATETIME data type that represents an interval of time. Typically, intervals are stored as large integers, which often makes them difficult to work with. WMI simplifies working with intervals by displaying them in a human-readable form using days, hours, minutes, and seconds. By providing an interval editor that lets you add or edit intervals in a human-readable format, WMI also simplifies the task of adding or editing intervals.

You can make a property describe an interval by defining the property as having a DATETIME data type and then defining a qualifier for this property named subtype with a value of "Interval". To add an interval property to a class and set an interval value for the property using the interval editor, follow this procedure.

To add an interval property to a class

  1. Select a class to edit.
  2. On the Properties tab in Class Viewer, add a property with a type of DATETIME.
  3. Right-click the property and select property qualifiers from the context menu.
  4. In the Property Qualifiers dialog box, enter a qualifier named "subtype" and set its value to "interval".
  5. Click OK.

    When you attempt to enter a value for the property, the interval editor will appear.

    The top box is used to specify the number of days in the interval. The bottom box is used to specify hours, minutes, and seconds.

    For more information about intervals, see Interval Format.


Adding Class Methods

You can add methods only to classes, not instances.

To add a method

  1. Display the Methods tab for the class to work with. See Displaying Class Methods.
  2. Enter the method name in the Name box.
  3. Define the method's qualifiers.

    See Adding Class, Property, or Method Qualifiers, Declaring Methods, and Using Qualifiers.

  4. To define the method's parameters, right-click the method and click Edit Method Parameters.
  5. In the Method Parameters window, for each input and output parameter, enter the parameter Name, Type, and Value.
  6. Click OK to save the parameters and return to the Methods tab.

    —or—

    Click Apply to save the changes and remain in the Method Parameters window.


Deleting Class Methods

You can delete methods only from classes, not instances.

To delete a method

  1. Display the Methods tab for the class to work with.

    See Displaying Class Methods.

  2. Click the gray box to the left of the method to delete.

    This selects the entire method entry.

  3. Click Delete.
  4. Click OK to delete the method and click Save.


Editing Class Method Parameters

You can add, edit, or delete method parameters for classes. For instances, you can only edit method parameter values.

To edit method parameters

  1. Display the Methods tab for the class or instance to edit.

    See Displaying Class Methods.

  2. Right-click the method to edit and select Edit Method Parameters.
  3. In the Method Parameters window, select and edit the fields to change.

    In some cases, selecting an item produces a list, from which you can select new values.

  4. Click OK to save the changes and return to the Methods tab.

    —or—

    Click Apply to save the changes and remain in the Method Parameters window.


Adding Class, Property, or Method Qualifiers

To add qualifiers

  1. Open the Qualifiers window for the desired class, property, or method. For instructions, see Displaying Class Qualifiers, Displaying Property Qualifiers, or Displaying Method Qualifiers.
  2. Click the blank Name field and select a standard qualifier from the list or enter a new qualifier name.

    When you complete the Name field, default entries appear in the remaining fields.

  3. To accept the defaults and close the Qualifiers window, click OK. See step 8 for instructions on saving the new qualifiers.

    To override the defaults, see steps 4 through 8.

  4. Click the Type field and choose a type from the list.

    When you select the type, a default value may appear in the Value field.

  5. Click the I, C, and O fields to select or cancel these settings.

    The Instances (I) field, if selected, specifies that this qualifier will be propagated automatically to all instances of this class. The Class (C) field, if selected, specifies that this qualifier will be propagated automatically to all classes derived from this class. The Origin (O) field is read-only. It indicates where the qualifier originated: local (for qualifiers defined in the current object) or propagated (for qualifiers propagated from another object).

  6. Click the Value field and enter the desired value.

    When you select this field and begin typing, a list may appear from which you can choose the appropriate value.

  7. When you have finished editing, click OK to close the Qualifiers window.
  8. In the Class Viewer, click Save to save your changes.


Deleting Class, Property, or Method Qualifiers

To delete qualifiers

  1. Open the Qualifiers window for the desired class, property, or method. For instructions, see Displaying Class Qualifiers, Displaying Property Qualifiers, or Displaying Method Qualifiers.
  2. Click the gray box to the left of the qualifier to delete. This selects the entire qualifier entry.
  3. Press the Delete key.
  4. Click OK to delete the qualifier.
  5. Click OK to close the Qualifiers window.
  6. In the Class Viewer, click Save to save your changes.


Editing Class, Property, or Method Qualifiers

To edit qualifiers

  1. Open the Qualifiers window for the desired class, property, or method. For instructions, see Displaying Class Qualifiers, Displaying Property Qualifiers, or Displaying Method Qualifiers.
  2. Click the field to change.

    If an arrow appears when you select the field, click the arrow and choose a value from the list that appears. If no arrow appears, type the new value in the field.

    3. Click the I, C, and O fields to select or cancel these settings.

    The Instances (I) field indicates that this qualifier will be propagated automatically to all instances of this class. The Class (C) field indicates that this qualifier will be propagated automatically to all classes derived from this class. The Origin (O) field is read-only. It indicates where the qualifier originated: local (for qualifiers defined in the current object) or propagated (for qualifiers propagated from another object).

    When you start typing, the text turns blue. This indicates that the value has not been committed yet.

  4. When you have finished editing, click OK to close the Qualifiers window.
  5. In the Class Viewer, click Save.
  6. Click Yes to save your changes.


Adding Instances of a Class

To add an instance of a class

  1. In the Class Explorer, select the class for which to create an instance.
  2. Click Create instance in the Class Viewer.

    The viewer displays data for the new instance.

  3. Enter values for the key property fields.

    For information on editing properties, see Editing Class Properties.

  4. When you have finished editing the key fields, click Save.

Note You cannot add instances of abstract classes. An abstract class is used only as a template for derived classes and cannot have instances. You cannot add instances to any class with children (subclasses). The class you add to must have at least one key property.


Deleting Instances of a Class

To delete an instance of a class

  1. Open the instance table for the desired class. For instructions, see Displaying an Instance Table.
  2. Click the gray box to the left of the instance to delete.

    This selects the entire instance entry.

  3. Click Delete instance in the Class Viewer.
  4. You will see the Deleting an Instance dialog box. Click Yes to delete the instance.


Executing Methods in CIM Studio

Regular methods can be executed on instances, if they are implemented and not disabled (marked by qualifiers on the method). Methods marked with the [static] qualifier can also be executed on a class. You can execute methods on instances or on classes defined as static but not on instances of static classes.

To execute a method

  1. Display the Methods tab for the object to work with. For a class, select the class in the Class Explorer and click the Methods tab in the Class viewer. For an instance, do these steps in order:
    1. Click the class in the Class Viewer and click Instances ( [image]).
    2. Right-click the instance to work with and select Go to Object.
    3. Click the Methods tab.
  2. Right-click the method and select Execute Method.
  3. The Parameters column shows the parameters defined for this method and their default values. Before executing the method, set the values for the parameters by editing their values in this table.

    The direction of the parameters is indicated by the symbol in the first column.
    Symbol Description
    Indicates an input property.
    Indicates an output property.
    Indicates an input/output property.

  4. Click Execute.

    When the method is done executing, you can see the resulting parameter values, including the return value.


Using the WQL Query Builder

[This is preliminary documentation and subject to change.]

The WQL Query Builder lets you write, save, and execute WMI Query Language (WQL) queries.

To use the WQL Query Builder

  1. Click the WQL Query symbol in the Class Viewer ( [image]).
  2. To use a query, select the query from the list of available queries and click Execute.
  3. To compose and execute a new query, enter the new query in the Query box, and then click Execute. To save this query, enter a new name in the Name box, and then click Save Query. The query will be added to the list of available queries.

    For example, to create a query that displayed an instance of Win32_Process with a process name of "Winmgmt.exe", you would enter the following information:

    SELECT * FROM Win32_Process WHERE Name="winmgmt.exe"
  4. To edit an existing query, select the query to edit from the list of available queries and make changes to the information in the Query box. Click Save Query and the query will be updated.
  5. To delete an existing query, select the query to delete from the list of available queries and click Remove Query and the query will be deleted.

For more information about queries, see WMI Query Language.


Using the MOF Generator Wizard

The MOF Generator Wizard generates a MOF file for class definitions and/or instances from an existing repository. Typically, you run this wizard when you have created a new class or when you want to port existing repository information to another computer.

To generate a MOF file

  1. In the Class Explorer, select the check boxes of the classes to insert in the MOF file.
  2. Double-click the MOF Generator Wizard symbol.
  3. On the welcome screen, click Next.

    The next screen shows each class selected in step 1.

  4. For each class, do the following steps in order:
    • Select the class name from the Classes to generate code for list. The instances of that class, if any, appear in the right pane.
    • Choose whether you want the class definition in the MOF file by selecting the Include class definition check box.
    • Select the check boxes for the instances to be included in the MOF file. If you want all instances to be included, click Select All.
  5. Click Next.
  6. Enter a file name in the MOF File Name box and the directory where you want it to reside, or use Browse to select a directory.
  7. To generate a Unicode MOF file, select the UNICODE check box.
  8. Click Finish.
  9. Click OK to confirm MOF file generation and close the wizard.


Using the MOF Compiler Wizard

The MOF Compiler Wizard compiles the MOF file into a repository, importing any class definitions or instances from the MOF file into the current repository. You can also use this wizard to check the syntax of a MOF file and to create a binary MOF file.

  • Compiling a MOF File
  • Logging on to the MOF Compiler Wizard
  • Checking the Syntax of a MOF File
  • Creating a Binary MOF File


Compiling a MOF File

To compile a MOF file

  1. Double-click the MOF Compiler Wizard symbol in the Class Viewer. When the welcome screen appears, select Compile a .MOF file.
  2. Click Next.
  3. Enter the path and file name for the MOF file to compile (or use Browse to find the file). Then, enter the namespace where the MOF file should be loaded.

    If you select a namespace on a remote computer, click Username to display a login dialog box. Enter your user name and password for the computer where the namespace resides and click OK. Note that MOF files containing the #pragma namespace directive will override this selection.

  4. Click Next.
  5. Select or cancel the selection of the appropriate compiler options.

    You can modify classes and instances that are already in the namespace, and add new classes and instances to the namespace.

  6. Click Finish to compile the file.
  7. Click OK to confirm successful compilation.


Logging on to the MOF Compiler Wizard

Use the MOF Compiler Wizard User Credentials dialog box to provide information when compiling a MOF file on a remote computer. You can reach this dialog box by clicking Username in the MOF Compiler Wizard.

You can connect to a remote computer as either the current user or a different user. If you do not specify a user name or password, the credential's of the current user will be used. Otherwise, enter a valid user name and password for the remote computer.

To complete the MOF Compiler Wizard User Credentials dialog box

  1. If you are logging on as the current user on the remote computer, click OK.
  2. If you are logging in on a remote computer with credentials that are different than the current user, enter your information in Username and Password. The user name can be in the form domain\user.
  3. Enter the kind of authentication to use in Authority.
    • If the text you enter in Authority begins with the string "kerberos:", Kerberos authentication will be used and the text in Authority should contain a Kerberos principal name. For example, Kerberos:<principal name>.
    • If the text you enter in Authority begins with the string "NTLMDOMAIN:", NTLM authentication will be used and text in Authority should contain a NTLM domain name. For example, NTLMDOMAIN:<domain name>.
    • If you leave this box empty when connecting to a remote system, the operating system will negotiate with DCOM to determine whether NTLM or Kerberos authentication will be used
  4. Click OK.

Note The MOF Compiler Wizard User Credentials dialog box should only be used when connecting to remote namespaces. The connection will fail and you will see an error if you attempt to provide user credentials for a local connection.

You must be an authorized WMI user on a remote system before you will be allowed to connect to the remote system. You can use the WMI Control application on the remote system to set permissions for WMI users. The WMI Control help file documents how to use this control.

To execute the WMI Control application

From the Start menu, click Run and enter Wbemcntl (in Windows 95/98 and Microsoft® Windows NT® version 4.0). In Windows 2000, enter Wmimgmt.msc.


Checking the Syntax of a MOF File

To check the syntax of a MOF file

  1. Double-click the MOF Compiler Wizard symbol in the Class Viewer. When the welcome screen appears, select Check the syntax of a .MOF file.
  2. Click Next.
  3. Enter the path and file name for the MOF file to check or use Browse to find the file.
  4. Click Finish.

    The wizard checks the file's syntax and reports the results in a message box.

  5. Click OK.


Creating a Binary MOF File

To create a binary MOF file

  1. Double-click the MOF Compiler Wizard symbol in the Class Viewer. When the welcome screen appears, select Create a binary .MOF file.
  2. Click Next.
  3. Enter the path and file name for the MOF file to compile or use Browse to find the file.
  4. Enter the name of the binary MOF file to be created.
  5. Enter the directory where the binary MOF file should be created or use Browse to find a directory.
  6. To perform syntax checks, select the Perform WMI syntax checks check box.

    This option is only used for building binary MOF files for use by WDM device drivers. Choosing this option invokes a separate binary MOF file checker, which runs after the binary MOF file is created. To use this option under Windows 2000, the Windows 2000 DDK must first be installed.

  7. Click Next.
  8. Select or cancel the selection of the appropriate compiler options.

    You can modify classes and instances that are already in the namespace, and you can add new classes and instances to the namespace.

  9. Click Finish to compile the file.
  10. Click OK to confirm successful compilation.

Note You can also use the WMI MOF compiler to create binary MOF files from the command line. For more information about compiling binary MOF files, see MOF Compiler.


Using the Schema Validation Wizard

[This is preliminary documentation and subject to change.]

The Schema Validation Wizard verifies that a schema is CIM and WMI compliant. You can use this wizard to validate one or more classes within a schema or the entire schema itself. The validation process provides additional checks not covered by the MOF compiler. For complete details on the CIM standard, see the CIM Specification v2.0 at http://www.dmtf.org/. For details on the WMI specific compliance criteria, see Checking Correctness and CIM Compliance.

After you select the classes or schema to validate, you can choose to have the wizard perform the following optional tasks:

  • Verify that the classes or schema are CIM and WMI compliant.
  • Verify that the schema meets the WMI/Windows 2000 Logo Requirements.
  • Verify that the localized versions of the schema are consistent with the base schema.

The wizard provides a progress bar to visually represent how much of the schema has been validated. When the validation process is complete, the Validation Results dialog box displays any warning and error messages that occurred during the validation process. To be compliant, you must resolve all error conditions.


Selecting a Schema

[This is preliminary documentation and subject to change.]

The Select a Schema dialog box identifies the scope of the schema to validate. There are two options for selecting the scope of the schema—you can select individual classes or an entire schema.

To select individual classes

  1. In the Class Explorer, select the class to validate. You can select one or more classes.
  2. Double-click the Schema Validation Wizard symbol ( [image]) in the Class Viewer to activate the wizard.
  3. Click Next.
  4. In the Select a Schema dialog box, select the Use selected classes option. You can include descendents and associations of the selected classes by selecting these options: Selecting Select descendents of selected classes validates all classes derived from the class. Selecting Select associators of selected classes validates the association classes that contain references to the selected class and all classes referenced in the association.
  5. Click Next.

To select an entire schema

  1. Double-click the Schema Validation Wizard symbol in the Class Viewer to activate the wizard. It does not matter whether classes have been selected in the Class Explorer.
  2. Click Next.
  3. In the Select a Schema dialog box, select the Select classes by schema name option.
  4. Enter the schema name in the Select the schema to be validated box. The schema name is considered to be the first part of the class name before the first underscore, such as Win32.
  5. Enter the location of the namespace in the Select the namespace where this schema can be found box. This box defaults to the namespace selected in the Class Explorer.
  6. Click Next.


Checking Correctness and CIM Compliance

[This is preliminary documentation and subject to change.]

The Correctness and CIM Compliance dialog box lets you choose whether to perform CIM and WMI compliance checking on the selected classes or schema. It is recommended that you do not select this option if you have already performed compliance checking and have verified that your schema is compliant. This is a costly process that should be avoided for classes and schemas that are already compliant.

The following WMI specific compliance criteria is verified:

  • Correct use of WMI Standard Qualifiers
  • CIM Read qualifier is specified for each property
  • Content of the CIM Description qualifier provides appropriate reference material. For more details, see Valid Description.

To perform CIM and WMI compliance validation

  1. Select the Check for correctness and CIM compliance option.
  2. Click Next.

To bypass CIM and WMI compliance validation

  1. Clear the Check for correctness and CIM compliance option.
  2. Click Next.


Verifying Windows 2000 Logo Requirements

[This is preliminary documentation and subject to change.]

The Windows 2000 Logo Requirements dialog box lets you verify that you have met the "Rules for extending the Cimv2 namespace" specified in Appendix A of the Server Application Specification. You can download the specification from http://msdn.microsoft.com/winlogo/win2000.asp.

You only need to perform these checks if you are:

  • Extending the CIMV2 namespace or a namespace that contains the CIM and Win32 objects
  • Interested in receiving the Windows 2000 Logo for your product.

If you choose to validate your schema against the Windows Logo requirements, you must select the Check for Windows 2000 logo requirements option. Whether you select the other two options depends on the support your product provides. Select Computer System Management if you are extending the schema to represent a computer system. Select Device Management if you are extending the schema to represent a device.


Verifying Consistent Localization

[This is preliminary documentation and subject to change.]

The Localization dialog box verifies that if you provide localized versions of your schema, they are consistent with the base schema. This means that each class in the base schema is represented in the localized namespace and the only difference between the classes are the specified qualifiers. However, properties that do not provide localized values may be excluded from the class.

For details on providing localized versions of your schema, see WMI Localization.


Validating Schema

[This is preliminary documentation and subject to change.]

The Validating Schema dialog box initiates the validation process. The dialog box uses a progress bar for each of the validation steps you requested.


Displaying Validation Results

[This is preliminary documentation and subject to change.]

The Validation Results dialog box shows all warning and error conditions found during the validation process. The following information is provided for each condition:

  • Type, such as warning or error
  • Error, such as Invalid Mapping Strings
  • Source, such as the class, property, method, or qualifier that caused the error
  • Description, a brief description of the warning or error

In addition, the dialog box lets you save the contents of the list to a file by clicking Save As… and providing a file name.

If the brief description is not adequate, you can click Details… for more information about the error or warning.

When you validate the schema for CIM compliance, two additional text strings are shown on the dialog box, Subgraphs and Root Objects. The Subgraphs text string contains the count of the number of schema islands found in the schema. A schema island is a class or set of classes that you can traverse using inheritance or associations. If you have two classes that you cannot traverse using inheritance or associations, then they are in two separate subgraphs.

The Root Objects text string contains the number of class trees that contain descendants.


WMI Event Registration Tool

The WMI Event Registration Tool is designed for developers and system managers. It provides a graphical interface for what may also be accomplished programmatically. The WMI Event Registration Tool allows you to create, display, and modify the event consumers, filters, and timers for a given namespace and any bindings between filters and consumers. By using the WMI Event Registration Tool, you can do the following:

  • View properties of the defined consumer, filter, and timer system classes and instances.
  • Add or delete event consumer instances.
  • Add or delete event filter instances.
  • Add or delete event timer instances.
  • Edit instance properties.
  • Register consumers for events by binding consumer and filters.

Note You must install Windows Management and create a repository of classes on the target computer before you can use the WMI Event Registration Tool. One of the methods for creating a repository of classes is to compile a MOF file in the system directory where the WMI Core is installed. To compile the MOF file, type the following at the command-line prompt:

mofcomp <filename.mof>.

For more information, see MOF Compiler.

The examples in the following topics use the Eviewer.mof file found in the WMI SDK. This MOF file contains the classes and instances required to declare and register the WMI Event Viewer consumer provider with the Event subsystem. This MOF file is compiled automatically when Windows Management is first started, so that the WMI Event Viewer consumer is registered as a permanent event consumer by default. For more information on the required schema for this type of registration, see Registering Class and Instance Providers.

To open the WMI Event Registration Tool

  1. From Start, point to Programs and click WMI SDK.
  3. Click Event Registration. For instructions in using the WMI Login dialog box, see WMI Application Logon.

See Also

Timer Events, Permanent Event Consumers


WMI Event Registration Tool Interface

The left pane of the WMI Event Registration Tool displays the event related classes. The right pane displays any bindings you have defined between consumers and filters. An example of a WMI Event Registration Tool screen is shown below.

The left pane of the WMI Event Registration Tool shows the inheritance tree for the event-related classes (consumers, filters, and timers) contained in the current namespace. You can select the inheritance tree that will be displayed from the list box in the upper left corner of this window. Next to the first list box is another list that allows you to select the current namespace. By default, the root\CIMV2 namespace on the local computer is displayed. You can select a different namespace or a namespace on a remote computer. The tree shows system classes and instances of those classes.

The left pane of the WMI Event Registration Tool includes the following buttons and symbols.

Button | Description
 | Browse for Namespace allows you to browse and select namespaces on the local computer or a remote computer.
 | New Instance allows you to define another instance of the selected consumer, filter, or timer.
 | Edit Instance Properties allows you to view and modify some properties of the selected instance.
 | Delete Instance deletes the selected instance.
 | A symbol that denotes a class.
 | A symbol that denotes an instance.

The right pane of the WMI Event Registration Tool shows the bindings you have defined between consumers and filters. If you select consumers in the left pane, filters appear in the right pane. Similarly, if you select filters in the left pane, consumers appear in the right pane.

The right pane of the WMI Event Registration Tool includes the following buttons:

Button | Description
 | Register registers the selected filter-consumer combination.
 | View Instance Properties allows you to view some properties of the selected instance.

Double-click the Help button [image] to display online Help.


WMI Event Registration Tool Functions

This section describes the functions you can perform in the WMI Event Registration Tool:

  • Viewing class properties
  • Creating an event consumer instance
  • Creating an event filter instance
  • Creating an event timer instance
  • Registering a consumer for an event


Viewing Class Properties

Although you cannot modify any properties of a system class, you can view its properties.

To view class properties

In the left pane of the WMI Event Registration Tool, click the class and then click View Class Properties.

—or—

In the left pane of the WMI Event Registration Tool, right-click a class and then select View Class Properties.

See Also

WMI Event Registration Tool Functions


Creating an Event Consumer Instance

You create event consumers as instances of a given class. This version of WMI contains a predefined EventViewerConsumer class, which is a subclass of the __EventConsumer system class.

To create an event consumer instance

  1. From the list of inheritance trees, select Consumers.
  2. Expand the tree associated with the system class __EventConsumer.
  3. Click the class you want to instantiate, and click the New Instance button.

    —or—

  4. Right-click the class to instantiate, and select New Instance.
  5. In the Edit new instance properties dialog box, enter strings in the Description and Name boxes, and enter a value in the Severity box.
  6. Click OK to create the instance.

As an example, the following information would define an instance that, when used with the ServiceStoppedEvent filter, triggers an event notification and displays it in WMI Event Viewer when a system service is stopped.

  • In the Description box, enter Service was stopped.
  • In the MachineName box, enter the computer name (without \\) to identify the computer that will RECEIVE/CONSUME the events bound to this consumer. Leave this field blank to specify the local computer.
  • In the Name box, enter ServiceStopped.
  • In the Severity box, enter 1.

Another example would define a consumer that works with IntervalTimerFilter or AbsTimerFilter. This triggers an event notification and displays it in the WMI Event Viewer at regular intervals or at a particular date and time.

  • In the Description box, enter TimerEventReceived.
  • In the Name box, enter TimerEvent.
  • In the Severity box, enter 2.

See Also

WMI Event Registration Tool Functions, Permanent Event Consumers, __EventConsumer


Creating an Event Filter Instance

Event filters define criteria for receiving event notifications. You create event filters as instances of a given class. This version of WMI contains the predefined __EventFilter system class.

To create an event filter instance

  1. From the list of inheritance trees, select Filters.
  2. Click the class you want to create an instance and then click New Instance.

    —or—

    Right-click the class, and then click New Instance.

  3. In the Edit new instance properties dialog box, enter the following information:
    • In the Name box, enter a name for the filter.
    • In the Query box, enter a WQL SELECT statement that specifies the event criteria.
    • In the Query Language box, enter WQL.
  4. Click OK to create the instance.

As an example, the following information would define a filter that works with the ServiceStopped consumer to display an event message in WMI Event Viewer when a system service is stopped.

  • In the Name box, enter ServiceStoppedEvent.
  • In the Query box, enter the following WQL SELECT statement to specify the event criteria:
    SELECT * FROM __InstanceModificationEvent WITHIN 5 WHERE TargetInstance isa "Win32_Service" AND TargetInstance.State="Stopped"
  • In the Query Language box, enter WQL.

As another example, this information would define a filter that works with the TimerEvent consumer and IntervalTimer to display an event notification in WMI Event Viewer every 5 seconds.

  • In the Name box, enter IntervalTimerFilter.
  • In the Query box, enter the following WQL SELECT statement to specify the event criteria:
    SELECT * FROM __TimerEvent
  • In the Query Language box, enter WQL.

This information would define a filter that works with the TimerEvent consumer and AbsTimer to display an event notification in WMI Event Viewer at a specified date and time.

  • In the Name box, enter AbsTimerFilter.
  • In the Query box, enter the following WQL SELECT statement to specify the event criteria:
    SELECT * FROM __TimerEvent WHERE TimerId="AbsTimer"
  • In the Query Language box, enter WQL.

See Also

WMI Event Registration Tool Functions, __EventFilter, Creating an Event Filter, Event Queries, WMI Query Language


Creating an Event Timer Instance

Timer events may be of the absolute or interval type. Absolute timer events occur at a particular date and time, while interval timer events occur at regular intervals.

You create event timers as instances of a given class. This version of the WMI Event Registration Tool provides two subclasses of __TimerInstruction: __AbsoluteTimerInstruction and __IntervalTimerInstruction. You can create an instance with either or both of these.

To create an absolute event timer instance

  1. From the list of inheritance trees, select Timers.
  2. Expand the tree to expose the subclasses.
  3. Click __AbsoluteTimerInstruction and then click New Instance.

    —or—

    Right-click __AbsoluteTimerInstruction and then click New Instance.

  4. In the Edit new instance properties dialog box, click the Value field of the EventDateTime row.
  5. In the Time dialog box, set the date, time, and time zone, and then click OK. The date and time must be valid for an event to occur.
  6. In the TimerId field of the Edit new instance properties dialog box, enter a name for the timer.
  7. Click OK to create the instance.

The following example would create an absolute timer instruction that works with the TimerEvent consumer and AbsTimerFilter to display an event notification in the WMI Event Viewer at a particular date and time.

  • In the TimerId box of the Edit new instance properties dialog box, enter AbsTimer.

To create an interval event timer instance

  1. From the list of inheritance trees, select Timers.
  2. Expand the tree to expose the subclasses.
  3. Click __IntervalTimerInstruction and click the New Instance button.

    —or—

    Right-click on __IntervalTimerInstruction and select New Instance.

  4. In the Edit new instance properties dialog box, in the IntervalBetweenEvents box, enter a value in milliseconds.
  5. In the TimerId box, enter a name for the timer.
  6. Click OK to create the instance.

The following example would create an interval timer that works with the TimerEvent consumer and AbsTimerFilter to display an event message in WMI Event Viewer at regular intervals.

  • In the IntervalBetweenEvents box, enter 5000. This means that the event notification will occur every 5000 milliseconds (every 5 seconds).
  • In the TimerId box, enter IntervalTimer.

See Also

WMI Event Registration Tool Functions, Timer Events, __TimerInstruction, __AbsoluteTimerInstruction, __IntervalTimerInstruction


Registering a Consumer for an Event

To register to receive an event notification, permanent consumers must create at least one of each of the following instances, which are then registered together in a process called binding:

  • Event consumer instance
  • Event filter instance

To register an event consumer for an event

  1. Select Consumers in the list of inheritance trees.
  2. Expand the whole inheritance tree, then select a consumer instance in the left pane (for example, the ServiceStopped consumer created in Creating an Event Consumer Instance).
  3. In the right pane, click the matching filter (for example, the ServiceStoppedEvent filter created in Creating an Event Filter Instance).
  4. Click Register. (The name of the Register button now changes to Unregister. Click it to unregister the selected consumer and filter.)

Note You should check the event log for errors after registering an event consumer because if an error occurs during an event consumer binding Windows Management will issue this error to Event Log.

To test the ServiceStopped consumer-filter binding after registration, open Services in Control Panel. On Microsoft® Windows® 2000 platforms, Services is in the component services folder, which is inside the administrative tools folder. Find a running service that can be safely stopped and stop it, or find a service that hasn't started, start it, and wait 5 seconds before stopping it. WMI Event Viewer appears, notifying you of the event. As shown in the WMI Event Viewer, this event is an instance of __InstanceModificationEvent.

The query in the ServiceStoppedEvent filter uses no timers. The two other example filters do.

Absolute events occur only once, at a particular date and time. If you set the EventDateTime property of the AbsTimer timer (created in Creating an Event Timer Instance) to a future date and then register the TimerEvent consumer (created in Creating an Event Consumer Instance) and the AbsTimerFilter filter (created in Creating an Event Filter Instance), WMI Event Viewer will show the timer event when it is generated at the set date.

Interval events occur at regularly occurring intervals. If you register the TimerEvent consumer and the IntervalTimerFilter filter (created in Creating an Event Filter Instance), WMI Event Viewer shows the timer event generated every five seconds.

See Also

WMI Event Registration Tool Functions, __FilterToConsumerBinding


WMI Event Viewer

WMI Event Viewer is a permanent event consumer that allows users to sort and view the details of events received. As events are generated in WMI by Windows Management or by event providers, event objects are forwarded to any consumers registered for these types of events. You can register WMI Event Viewer for any event filters, so you can view only incoming events that match the filters.

With WMI Event Viewer, you can:

  • View Windows Management-generated events and event information, such as the event's date and time, class, point of origin, and a description.
  • View event instance properties.
  • Start the WMI Event Registration Tool.
  • Clear the display.

Note To use WMI Event Viewer in any namespace other than CIMV2, you must first compile it into the new namespace (at the command prompt, enter mofcomp eviewer.mof). Because Eviewer.mof contains the statement #pragma namespace("\\root\\cimv2"), you must edit Eviewer.mof before compiling and replace "cimv2" in the #pragma statement with the name of the new namespace.

You can start WMI Event Viewer manually using the "WMI Event Viewer" shortcut in the WMI SDK program group. However, this is not necessary for WMI Event Viewer to function because, as a permanent event consumer, it will be launched automatically by WMI whenever an event occurs that needs to be forwarded to it. To register WMI Event Viewer for different types of events, use the WMI Event Registration Tool. This tool can be launched either independently by using the shortcut in the WMI SDK program group or from WMI Event Viewer itself by clicking Register.

Note You must install Windows Management and create a repository of classes on the target computer before you use WMI Event Viewer. One of the methods for creating a repository of classes is to compile a MOF file in the directory where the SDK was installed. (Typically, the location would be C:\Program Files\WMI.)

To compile the MOF file, type the following command:

mofcomp <filename.mof>.

For more information, see MOF Compiler.

The Eviewer.mof file installed in the WMI SDK directory along with WMI Event Viewer contains the classes and instances required to declare and register the WMI Event Viewer Consumer Provider with the WMI event subsystem. This MOF file is compiled automatically when the Windows Management Service is first started, so that the WMI Event Viewer consumer is registered as a permanent event consumer by default. For more information about the required schema for this type of registration, see Registering an Event Consumer Provider.

Note All permanent event consumers, including WMI Event Viewer, require specific distributed COM (DCOM) permissions to launch automatically on a remote computer for a registered event.

To open WMI Event Viewer

  1. On the Start menu, point to Programs, and then click WMI SDK.
  2. Click WMI Event Viewer.

To set the launch permissions for WMI Event Viewer

  1. Run the Dcomcnfg.exe program from the remote computer's system directory.
  2. On the Applications tab of the Distributed COM Configuration Properties dialog box, select WMI Event Viewer and click Properties.
  3. On the Security tab of the WMI Event Viewer Properties dialog box, select the Use custom launch permissions option and click Edit.
  4. In the Registry Value Permissions dialog box, click Add.
  5. When the Add Users and Groups dialog box appears, select Everyone from the list of users and groups.
  6. Click Add and then click OK.


WMI Event Viewer Interface

The WMI Event Viewer interface includes the following columns of event information.

Column | Event information
Sev | The severity of the event. This is a property of the EventViewerConsumer class, which represents the WMI Event Viewer and can be set differently in different instances of this class through the WMI Event Registration Tool.
Time | When the consumer received the event.
Event Class | The class of the received event, for example __InstanceModificationEvent.
Server | The server where the event occurred.
Description | A short description for the event. This is a property of the EventViewerConsumer class and is configured through the WMI Event Registration Tool. You can define separate consumer instances with different descriptions for the various event filters that the consumer is bound to.

With the WMI Event Viewer columns, you can:

  • Reorder the columns by selecting and dragging a column over another column.
  • Adjust the column size.
  • Sort information according to the column heading by clicking the heading.

Whenever an event is received by WMI Event Viewer (which occurs when a generated event matches an event filter for which WMI Event Viewer is registered), a line is added to the List view in WMI Event Viewer's main dialog box, which provides general information for the event.

Note As events are received and displayed in the WMI Event Viewer, the counter at the bottom of the list displays the total number of events received since the viewer was last cleared. To avoid an "Out of Memory" situation, the viewer is limited to holding 1,000 events at a time. If this number is exceeded and the viewer has not been cleared, it will flush out the oldest events to make room for the new ones. This condition is indicated by a comment at the bottom of the list.

The WMI Event Viewer interface includes the following buttons.

Button | Description
 | Register for events starts WMI Event Registration Tool.
 | View properties allows you to get the full details of the selected event. A dialog box containing the Object Viewer is displayed showing the full contents of the event object. Note that many event objects might contain further embedded objects that are related to the event. For example, an __InstanceCreationEvent event will contain an embedded object, which is the instance that triggered this event. To view the embedded objects, click Object in the Value column for the respective property.
 | Clear Viewer clears the display.


ActiveX Controls

The Windows Management Instrumentation (WMI) software development kit (SDK) provides a suite of Microsoft ActiveX controls that uses the native WMI APIs to perform logically-related functions. These controls are the GUI components that form the WMI Object Browser and WMI CIM Studio applications included in the WMI SDK. Developers can use the controls to include GUI functionality in their WMI-based client applications.

These controls are normally shipped in a CAB file, Wbemtool.cab. They are automatically extracted by any of the HTML-based application programs that use them, such as CIM Studio. To extract them, from the DOS command line in Windows 95/Windows 98, run

extract /E wbemtool.cab

In Windows 2000, run

extrac32 /E wbemtool.cab

instead. Once you have extracted them, use "regsvr32" to register the controls you want.

The WMI SDK includes the following ActiveX controls:

Control | Description
WMI Class Navigator | Displays a tree view of the class structure in a namespace of the Common Information Model (CIM) repository.
WMI Provider Wizard | Generates C++ provider framework code for specified objects.
WMI EventList | Displays events that are forwarded to it.
WMI Event Registration | Displays event filters, event consumers, and their bindings.
WMI MOF Compiler Wizard | Compiles a specified Managed Object Format (.mof) file.
WMI MOF Generator Wizard | Generates a .mof file for specified objects.
WMI Multiple Instances Viewer | Displays the details for one or more objects in a tabular format.
WMI Namespace Picker | Allows users to browse and select namespaces.
WMI Instance Navigator | Displays the associations between objects in a namespace in the CIM repository.
WMI Login | Provides login services for the WMI ActiveX controls.
WBEM Object Viewer | Displays the details for a specified object.
WMI Object Viewer Container | Provides navigation features for the WMI Object Viewer and the WMI Multiple Instances Viewer.


Creating a WMI Browser in MFC

In the following tutorial, you will create a simple Windows Management Instrumentation (WMI) browser application by using several of the controls in the WMI ActiveX® suite. You will use the Microsoft® Foundation Classes (MFC) to implement this browser.

The example code in this tutorial was built with Microsoft® Visual C++ version 6.0 running under Microsoft® Visual Studio® 97. You can also use other integrated development environments (IDEs) that support MFC to build this code.


Creating the Browser Project

To create a browser

  1. Open Microsoft Visual Studio and select the File/New menu item.
  2. Select the Projects tab from the New dialog box and then select MFC AppWizard to build the executable.
  3. Choose a location for your program and give it the name WbemBrowser.

  4. Create a single document interface (SDI) application. Then, accept ActiveX Controls and all other defaults. Your final AppWizard screen should look like this.

  5. Build the project and verify that it runs.


Adding the WBEM Navigator Control

There are actually two different WMI navigator controls: the class navigator and the instance navigator. You are going to use only the instance navigator in this example, which we will simply call the navigator.

To create a navigator

  1. From the Project menu, click Add to Project and Components and Controls.

    When the Components and Controls Gallery dialog box appears, select the Registered ActiveX Controls folder. In it, you should see the suite of WMI ActiveX controls registered by your WMI SDK installation .

  2. From the list of controls, select WMI Instance Navigator Control.

  3. Click Insert and then OK. When you see the Confirm Classes dialog, click OK again and then click Close.

    This step will add a wrapper class for the WMI Instance Navigator control to your project, giving it the name CNavigator.

  4. Modify the CWbemBrowserView class so that it displays the navigator control. To do this, first add a navigator control member variable to the class.
  5. Add a Boolean member variable called m_bReady.
  6. Add the following boldfaced text to the CWbemBrowserView class definition:
    // Attributes
public:
    CWbemBrowserDoc* GetDocument();

    CNavigator m_Navigator;
    bool m_bReady;
  7. Include the Navigator.h file at the beginning of both the MainFrm.cpp and the WbemBrowser.cpp files.
    #include "navigator.h"

#include "MainFrm.h"
#include "WbemBrowserDoc.h"
#include "WbemBrowserView.h"

    Then, include the Navigator.h file at the beginning of WbemBrowserView.cpp.

    #include "navigator.h"

#include "WbemBrowserDoc.h"
#include "WbemBrowserView.h"

    The CNavigator class is derived from the CWnd class. When you create the CWbemBrowserView window, you should also create the navigator control window. The CNavigator::Create method maps closely to the CWnd::CreateControl method. All of the parameters passed to CNavigator::Create are simply passed on to CWnd::CreateControl.

  8. Use ClassWizard to generate the CWbemBrowserView::Create method and then fill it with the bolded lines of code.
    BOOL CWbemBrowserView::Create(
    LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle,
    const RECT& rect, CWnd* pParentWnd, UINT nID,
    CCreateContext* pContext)
{
    int nReturn = CWnd::Create(
        lpszClassName, lpszWindowName, dwStyle, rect,
        pParentWnd, nID, pContext);
    if (nReturn == 0)  return FALSE;

    // Create the instance navigator display window.
    BOOL bReturn = m_Navigator.Create(
        "Navigator",
        NULL,
        WS_CHILD | WS_VISIBLE,
        CRect(CPoint(0,0), CSize(0,0)),
        this,
        0);

    return bReturn;
}
  9. In order to fill the client area of the view with the control, you must override the view's OnSize method. Use the Class Wizard to generate code for the WM_SIZE event and add the following boldfaced lines to it:
    void CWbemBrowserView::OnSize(UINT nType, int cx, int cy)
{
    CView::OnSize(nType, cx, cy);

    if (::IsWindow(m_Navigator.m_hWnd))
        m_Navigator.MoveWindow(CRect(CPoint(0,0), CSize(cx,cy)));
}
  10. Build the project and run it.

    The WbemBrowser navigation control should appear and completely fill the client area of the frame.

  11. Call the CNavigator::OnReadySignal method to initialize the navigator control.

    This code must be called only once, after the navigator control window is fully created.

  12. To the CWbemBrowserView constructor, add the following code.
    CWbemBrowserView::CWbemBrowserView()
{
    m_bReady = false;
}
  13. Add the lines of bolded text to the CBrowserView::OnDraw method.
    void CWbemBrowserView::OnDraw(CDC* pDC)
{
    CWbemBrowserDoc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);

    // Initialize the navigator.
    if (!m_bReady) {
         m_bReady = true;
         m_Navigator.OnReadySignal();
    }
}
  14. Build the project and run it.

    The CNavigator::Create method creates the navigator control window. The CNavigator::OnReadySignal method informs the navigator that it can initialize itself. The navigator displays a Connect to namespace dialog in order to initialize its NameSpace property. The Connect to namespace dialog box appears with the suggested default of Root\CIMV2.

    Clicking OK accepts this default, but the connection fails anyway, because you have not yet logged into a WMI server. As a result, the following Instance Explorer Message dialog box appears.


Adding the WBEM Login Control

However, before you can display the instances in a namespace, you will have to log into a WMI server. To do this, you must add the WBEM Login Control to the browser and use it to log into your machine.

To add a WBEM Login control

  1. From the Project menu, click Add to Project and Components and Controls. When the Components and Controls Gallery dialog box appears, select the Registered ActiveX Controls folder.

  2. Select WBEM Login Control and add it to your project. Then, accept the default wrapper class, CSecurity.

  3. Modify the CWbemBrowserView class to add an instance of the login control. Follow the example given above for the navigator control.
  4. In the CWbemBrowserView class definition, add the bolded text to the code.
        CNavigator m_Navigator;
    CSecurity m_Security;
    bool m_bReady;
  5. To the beginning of the MainFrm.cpp and WbemBrowser.cpp files, add the bolded text.
    #include "navigator.h"
#include "security.h"

#include "MainFrm.h"
#include "WbemBrowserDoc.h"
#include "WbemBrowserView.h"
  6. To the beginning of the WbemBrowserView.cpp file, add the bolded text.
    #include "navigator.h"
#include "security.h"

#include "WbemBrowserDoc.h"
#include "WbemBrowserView.h"
  7. Add the bolded text to the CWbemBrowserView::Create method.
        // Create the instance navigator display window.
    BOOL bReturn = m_Navigator.Create(
        "Navigator",
        NULL,
        WS_CHILD | WS_VISIBLE,
        CRect(CPoint(0,0), CSize(0,0)),
        this,
        0);

    if (!bReturn)  return FALSE;

    // Create the login control window.
    bReturn = m_Security.Create(
        "Security",
        NULL,
        WS_CHILD | WS_VISIBLE,
        CRect(CPoint(0,0), CSize(0,0)),
        this,
        0);

    if (bReturn)
        m_Security.SetLoginComponent("Some Machine");

    return bReturn;

The CSecurity::LoginComponent property suggests which WMI component to log into. The text is holds appears later as part of the Login dialog box label.


Connecting the Navigator to the Login Control

The navigator control recognizes the namespace but not the WMI server. To access a namespace, the control must first obtain an IWbemServices pointer from the server. The control gets this information by firing an event, which is subsequently passed to the login control. The login control displays a dialog box that requests the server name. The login control takes the namespace and server name and creates an IWbemServices interface pointer, which is passed back to the navigator.

In response to a call to the CNavigator::OnReadySignal method, the navigator control triggers the CNavigator::GetIWbemServices event. You must handle this event in CWbemBrowserView and connect it to the CSecurity::GetIWbemServices method, which returns an IWbemServices interface pointer to the requested namespace. You will pass this pointer back to the navigator control.

In summary, to connect the navigator to the login control, you must implement these steps:

  1. Create an event sink map in the CWbemBrowserView.
  2. Add CNavigator::GetIWbemServices to the map.
  3. Implement a CWbemBrowserView handler for the event.
  4. Call the CSecurity::GetIWbemServices method in the handler.
  5. Return the IWbemServices pointer to the navigator.

The CNavigator events in the wizard-generated Navigator.cpp file do not have wrappers. This is because controls do not handle their own events; they merely fire them. Control events must be handled somewhere else, in this case, in the CWbemBrowserView class. Unfortunately, there is no simple way for the Developer Studio wizards to add event handlers to CView-based classes. You will have to use a technique described in "HOWTO: Handling Events for ActiveX Controls in a CWnd" (Knowledge Base article number Q147740).

The trick is to take advantage of the fact that the Resource Editor can add ActiveX controls to a dialog box and the ClassWizard can add event handlers to a CDialog-based class.

To generate ActiveX wrappers

  1. Click the ResourceView tab and open the dialog box folder.

    The only dialog box you have at the moment is IDD_ABOUTBOX. You will borrow this dialog box and restore it later.

  2. Display the IDD_ABOUTBOX dialog box.

    Notice that buttons have been added to the Resource Editor control palette for both the WBEM Instance Navigator and WBEM Login controls.

  3. Click the WBEM Instance Navigator button and add it to the dialog box.

  4. To bring up the ClassWizard, press CTRL+W .

    You will see IDC_INSTNAVCTRL1 in the Object IDs pane and a list of the control's events in the Messages pane.

  5. Add a function for each event, accepting the default names.

    It is easier to add functions for all events now than to add them later, one at a time.

  6. Open WbemBrowser.cpp and move the following bolded lines of code from the definition of the CAboutDlg class to the CWbemBrowserView class in WbemBrowserView.h.

    Be sure to insert these lines between the AFX_MSG brackets, just after the OnSize entry. The modified lines are displayed in boldface below, just after the move.

    // Implementation
protected:
    //{{AFX_MSG(CWbemBrowserView)
    afx_msg void OnSize(UINT nType, int cx, int cy);
    afx_msg void OnNotifyOpenNameSpaceInstnavctrl1(LPCTSTR lpcstrNameSpace);
    afx_msg void OnViewObjectInstnavctrl1(LPCTSTR bstrPath);
    afx_msg void OnViewInstancesInstnavctrl1(LPCTSTR bstrLabel, const VARIANT FAR& vsapaths);
    afx_msg void OnQueryViewInstancesInstnavctrl1(LPCTSTR pLabel, LPCTSTR pQueryType, LPCTSTR pQuery, LPCTSTR pClass);
    afx_msg void OnGetIWbemServicesInstnavctrl1(LPCTSTR lpctstrNamespace, VARIANT FAR* pvarUpdatePointer, VARIANT FAR* pvarServices, VARIANT FAR* pvarSC, VARIANT FAR* pvarUserCancel);
    DECLARE_EVENTSINK_MAP()
    //}}AFX_MSG
    DECLARE_MESSAGE_MAP()
  7. Move the following bolded lines of code from the implementation of the CAboutDlg class to the end of the WbemBrowserView.cpp file:
    • Replace each occurrence of the text "CAboutDlg" with "CWbemBrowserView".
    • Replace the single occurrence of "CDialog" with "CView". These modified lines are displayed below, just after the move.
    BEGIN_EVENTSINK_MAP(CWbemBrowserView, CView)
    //{{AFX_EVENTSINK_MAP(CWbemBrowserView)
    ON_EVENT(CWbemBrowserView, IDC_INSTNAVCTRL1, 1 /* NotifyOpenNameSpace */, OnNotifyOpenNameSpaceInstnavctrl1, VTS_BSTR)
    ON_EVENT(CWbemBrowserView, IDC_INSTNAVCTRL1, 2 /* ViewObject */, OnViewObjectInstnavctrl1, VTS_BSTR)
    ON_EVENT(CWbemBrowserView, IDC_INSTNAVCTRL1, 3 /* ViewInstances */, OnViewInstancesInstnavctrl1, VTS_BSTR VTS_VARIANT)
    ON_EVENT(CWbemBrowserView, IDC_INSTNAVCTRL1, 4 /* QueryViewInstances */, OnQueryViewInstancesInstnavctrl1, VTS_BSTR VTS_BSTR VTS_BSTR VTS_BSTR)
    ON_EVENT(CWbemBrowserView, IDC_INSTNAVCTRL1, 5 /* GetIWbemServices */, OnGetIWbemServicesInstnavctrl1, VTS_BSTR VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT)
    //}}AFX_EVENTSINK_MAP
END_EVENTSINK_MAP()

void CWbemBrowserView::OnNotifyOpenNameSpaceInstnavctrl1(LPCTSTR lpcstrNameSpace)
{
}
void CWbemBrowserView::OnViewObjectInstnavctrl1(LPCTSTR bstrPath)
{
}
void CWbemBrowserView::OnViewInstancesInstnavctrl1(LPCTSTR bstrLabel, const VARIANT FAR& vsapaths)
{
}
void CWbemBrowserView::OnQueryViewInstancesInstnavctrl1(LPCTSTR pLabel, LPCTSTR pQueryType, LPCTSTR pQuery, LPCTSTR pClass)
{
}
void CWbemBrowserView::OnGetIWbemServicesInstnavctrl1(LPCTSTR lpctstrNamespace, VARIANT FAR* pvarUpdatePointer, VARIANT FAR* pvarServices, VARIANT FAR* pvarSC, VARIANT FAR* pvarUserCancel)
{
}
  8. Return to the Resource Editor and delete the navigator control from the IDD_ABOUTBOX dialog, without saving any changes.
  9. Add a #define statement for IDC_INSTNAVCTRL1 after the include statements at the beginning of the WbemBrowserView.cpp file.
    #include "navigator.h"
#include "security.h"

#define IDC_INSTNAVCTRL1                1000
  10. To complete the connection between the WMI Navigator control and the view window , you must change the last parameter in the CWbemBrowserView::Create call to CNavigator::Create. Change it to IDC_INSTNAVCTRL1.
        nReturn = m_Navigator.Create(
        "Navigator",
        NULL,
        WS_CHILD | WS_VISIBLE,
        CRect(CPoint(0,0), CSize(0,0)),
        this,
        IDC_INSTNAVCTRL1);

    Events fired by the navigator control will now go to event handlers in the CWbemBrowserView class.

    After the namespace connection dialog box has appeared in response to the CNavigator::OnReadySignal method, the navigator control fires the CNavigator::GetIWbemServices event for the requested namespace. This event is now handled in the CWbemBrowserView::OnGetIWbemServicesInstnavctrl1 event handler.

  11. To connect the CWbemBrowserView::OnGetIWbemServicesInstnavctrl1 event handler to the CSecurity::GetIWbemServices method, add the following bolded code. which returns an IWbemServices interface pointer to the requested namespace.
    void CWbemBrowserView::OnGetIWbemServicesInstnavctrl1(LPCTSTR lpctstrNamespace, VARIANT FAR* pvarUpdatePointer, VARIANT FAR* pvarServices, VARIANT FAR* pvarSC, VARIANT FAR* pvarUserCancel)
{
    m_Security.GetIWbemServices(
        lpctstrNamespace,
        pvarUpdatePointer,
        pvarServices,
        pvarSC,
        pvarUserCancel);
}
  12. Build the project and execute it.

    The namespace connection dialog box will now be followed by the login dialog box.

    Clicking OK logs into the current server and displays the instance tree.

    The Navigator control is now fully functional. You can double-click the root node, for example, to expand the instance tree.

    Note While building the object instance tree, the navigator control may time out. Should this happen, the Server Busy message box appears.

    If you see this message box, use the system Task Manager to terminate the Untitled – WbemBrowser task and run the browser again.


Creating the Splitter Window

Compare the browser you've created so far with the WMI Object Browser application that ships with the WMI SDK. You'll quickly see that you've created the Object Explorer, which is located in the left pane of a split window. To complete the WMI browser, you must also create the Object Viewer, which will be located in the browser's right pane.

To display your navigator control in the left pane of a split window, you must follow this general process:

  • Add a CObjectView class instance to the project.
  • Create a static splitter window in the CMainFrm main frame.
  • Put CWbemBrowserView in the left pane and CObjectView in the right pane.

To create the Object Viewer

  1. To add a new CObjectView class to your project, use the New Class dialog box of the ClassWizard; choose CView as the base class.

  2. Add a CSplitterWnd member variable by adding the following bolded text to the CMainFrm class definition.
    // Attributes
public:
    CSplitterWnd m_wndSplitter;
  3. Include WbemBrowserDoc.h, WbemBrowserView.h, and ObjectView.h at the beginning of MainFrm.cpp. Also, include WbemBrowserDoc.h, since it is required by WbemBrowserView.h.
    #include "MainFrm.h"
#include "WbemBrowserDoc.h"
#include "WbemBrowserView.h"
#include "ObjectView.h"
  4. Use ClassWizard to create the CMainFrame::OnCreateClient method. Replace the body of this method with the following lines of bolded text.
    BOOL CMainFrame::OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext)
{
    // Calculate the size of half of the client area.
    CRect r;
    GetClientRect(&r);
    CSize size = CSize(r.Width()/2, r.Height());

    // Create a splitter with 1 row, 2 columns.
    if (!m_wndSplitter.CreateStatic(this, 1, 2))
    {
        TRACE("Failed to create the static splitter\n");
        return FALSE;
    }
    // Add the first splitter pane -- the view in column 0.
    if (!m_wndSplitter.CreateView(
        0, 0, RUNTIME_CLASS(CWbemBrowserView), size, pContext))
    {
        TRACE("Failed to create the first pane\n");
        return FALSE;
    }
    // Add the second splitter pane -- the view in column 1.
    if (!m_wndSplitter.CreateView(
        0, 1, RUNTIME_CLASS(CObjectView), CSize(0, 0), pContext))
    {
        TRACE("Failed to create the second pane\n");
        return FALSE;
    }

    // Select the rightmost pane.
    SetActiveView((CView*) m_wndSplitter.GetPane(0,1));
    return TRUE;
}
  5. Build the project and run it. The navigator should appear in the left pane of a split window. The right pane will be empty.


Adding the WBEM Object Viewer Container Control

You can use the WBEM Object Viewer Container control to display the properties, methods, and associations of an object. You can add the Object Viewer container control to the CObjectView class the same way you added the navigator control to the CWbemBrowserView class.

To add the Object Viewer container control

  1. To open the Components and Controls Gallery dialog box, select Project\Add to Project\Components and Controls. From the dialog box, select Registered ActiveX Controls.

  2. Select WBEM Object Viewer Container Control and add the control to your project.
  3. Accept the default wrapper class name, CSingleView.

  4. Modify the CObjectView class to add an instance of the object viewer container control. In the CObjectView class definition, add the following bolded text to the code.
    // Attributes
public:
    CWBEMViewContainer m_ViewContainer;
  5. To the beginning of the MainFrm.cpp file, add the following code.
    #include "navigator.h"
#include "security.h"
#include "wbemviewcontainer.h"

#include "MainFrm.h"
#include "WbemBrowserDoc.h"
#include "WbemBrowserView.h"
#include "ObjectView.h"
  6. To the beginning of the ObjectView.cpp file, add the following code.
    #include "stdafx.h"

#include "wbemviewcontainer.h"

#include "WbemBrowser.h"
#include "ObjectView.h"
  7. Use ClassWizard to create the CObjectView::Create method. Replace the body of the method by adding the following bolded text to the code.
    BOOL CObjectView::Create(LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CCreateContext* pContext)
{
    BOOL bResult =
    CWnd::Create(lpszClassName, lpszWindowName, dwStyle, rect, pParentWnd, nID, pContext);
    if (!bResult)  return FALSE;

    bResult = m_ViewContainer.Create(
        "Hmmv",
        NULL,
        WS_CHILD | WS_VISIBLE,
        rect,
        this,
        0);

    m_ViewContainer.SetStudioModeEnabled(FALSE);

    return bResult;
}

    The CWBEMViewContainer::StudioModeEnabled property determines whether the object view will accept editing commands. SetStudioModeEnabled(FALSE) sets the view to be read-only, and to not respond to editing commands.

  8. To fill the client area of the view with the Object Viewer Container control, override the OnSize event handler. Use ClassWizard to generate code for the WM_SIZE event and add the following bolded text to the code.
    void CObjectView::OnSize(UINT nType, int cx, int cy)
{
    CView::OnSize(nType, cx, cy);

    if (::IsWindow(m_ViewContainer.m_hWnd))
        m_ViewContainer.MoveWindow(CRect(CPoint(0,0), CSize(cx,cy)));
}
  9. Build the project and run it.

    The navigator should appear in the left pane, and the Object Viewer container should appear in the right pane.


Connecting the Object View Pane to the Object Viewer Container Control

In response to a call to the CNavigator::OnReadySignal method, the navigator opens the Connect to Namespace dialog box and then the Login dialog box. When the namespace is opened, the navigator triggers the CNavigator::OnNotifyOpenNameSpace event. You will need to connect this event to the CWBEMViewContainer::SetNameSpace method, which tells the object viewer container which WMI namespace to connect to. This method, in turn, fires the CWBEMViewContainer::GetIWbemServices event to obtain an interface pointer the namespace specified. You will need to handle this event in the CObjectView class.

CWBEMViewContainer events in the Wbemviewcontainer.cpp file do not have wrappers. These events must be handled in the CObjectView class. , you will have to use the same technique you used to connect the navigator events to the CWbemBrowserView class.

To generate ActiveX wrappers

  1. From Microsoft Visual Studio, click the ResourceView tab and open the dialog box folder. Open the IDD_ABOUTBOX dialog box.
  2. Click the WBEM Object Viewer Container button and add it to the dialog box.

  3. To open the MFC Class Wizard dialog box, press CTRL+W .

    You will see IDC_OBJVIEWERCTRL1 in the Object IDs pane and a list of the control's events in the Messages pane.

  4. Add a function for each event, accepting the default names.
  5. Open WbemBrowser.cpp and move the following lines from the definition of the CAboutDlg class to the CObjectView class in the ObjectView.h file.
        afx_msg void OnGetIWbemServicesObjviewerctrl1(LPCTSTR szNamespace, VARIANT FAR* pvarUpdatePointer, VARIANT FAR* pvarServices, VARIANT FAR* pvarSc, VARIANT FAR* pvarUserCancel);
    afx_msg void OnNOTIFYChangeRootOrNamespaceObjviewerctrl1(LPCTSTR szRootOrNamespace, long bChangeNamespace, long bEchoSelectObject);
    afx_msg void OnReadyStateChangeObjviewerctrl1();
    afx_msg void OnRequestUIActiveObjviewerctrl1();
    DECLARE_EVENTSINK_MAP()

    Insert these lines between the AFX_MSG brackets, just after the OnSize entry. After moving the code, the results should look like this.

        // Generated message map functions
protected:
    //{{AFX_MSG(CObjectView)
    afx_msg void OnSize(UINT nType, int cx, int cy);
    afx_msg void OnGetIWbemServicesObjviewerctrl1(LPCTSTR szNamespace, VARIANT FAR* pvarUpdatePointer, VARIANT FAR* pvarServices, VARIANT FAR* pvarSc, VARIANT FAR* pvarUserCancel);
    afx_msg void OnNOTIFYChangeRootOrNamespaceObjviewerctrl1(LPCTSTR szRootOrNamespace, long bChangeNamespace, long bEchoSelectObject);
    afx_msg void OnReadyStateChangeObjviewerctrl1();
    afx_msg void OnRequestUIActiveObjviewerctrl1();
    DECLARE_EVENTSINK_MAP()
    //}}AFX_MSG
    DECLARE_MESSAGE_MAP()
};
  6. Move the following bolded lines of text from the implementation of the CAboutDlg class to the end of the ObjectView.cpp file.

    Replace each occurrence of CAboutDlg with CObjectView. Then, replace the single occurrence of CDialog with CView. These modified lines are displayed below, just after the move.

    BEGIN_EVENTSINK_MAP(CObjectView, CView)
//{{AFX_EVENTSINK_MAP(CObjectView)
    ON_EVENT(CObjectView, IDC_OBJVIEWERCTRL1, 1 /* GetIWbemServices */, OnGetIWbemServicesObjviewerctrl1, VTS_BSTR VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT VTS_PVARIANT)
    ON_EVENT(CObjectView, IDC_OBJVIEWERCTRL1, 2 /* NOTIFYChangeRootOrNamespace */, OnNOTIFYChangeRootOrNamespaceObjviewerctrl1, VTS_BSTR VTS_I4 VTS_I4)
    ON_EVENT(CObjectView, IDC_OBJVIEWERCTRL1, -609 /* ReadyStateChange */, OnReadyStateChangeObjviewerctrl1, VTS_NONE)
    ON_EVENT(CObjectView, IDC_OBJVIEWERCTRL1, 3 /* RequestUIActive */, OnRequestUIActiveObjviewerctrl1, VTS_NONE)
    //}}AFX_EVENTSINK_MAP
END_EVENTSINK_MAP()

void CObjectView::OnGetIWbemServicesObjviewerctrl1(LPCTSTR szNamespace, VARIANT FAR* pvarUpdatePointer, VARIANT FAR* pvarServices, VARIANT FAR* pvarSc, VARIANT FAR* pvarUserCancel)
{
}
void CObjectView::OnNOTIFYChangeRootOrNamespaceObjviewerctrl1(LPCTSTR szRootOrNamespace, long bChangeNamespace, long bEchoSelectObject)
{
}
void CObjectView::OnReadyStateChangeObjviewerctrl1()
{
}
void CObjectView::OnRequestUIActiveObjviewerctrl1()
{
}
  7. Return to the Resource Editor and delete the Object Viewer Container control from the IDD_ABOUTBOX dialog box, without saving any changes.
  8. In ObjectView.cpp, add a #define statement for IDC_OBJVIEWERCTRL1 after the include statements.
    #include "WbemBrowser.h"
#include "ObjectView.h"

#define IDC_OBJVIEWERCTRL1              1001
  9. To complete the connection between the object viewer container and the view window, change the last parameter in the CObjectView::Create call to CWBEMViewContainer::Create. Change it to IDC_OBJVIEWERCTRL1.
        bResult = m_ViewContainer.Create(
        "Hmmv",
        NULL,
        WS_CHILD | WS_VISIBLE,
        rect,
        this,
        IDC_OBJVIEWERCTRL1);

    Events fired by the object viewer container will now go to event handlers in the CObjectView class.

  10. Build the project and verify that it runs.

    You will see no changes yet, since you have not yet connected the navigator to the object viewer container.


Connecting the Navigator Control to the Object Viewer Container Control

In response to a call to the CNavigator::OnReadySignal method, the navigator eventually triggers the CNavigator::OnNotifyOpenNameSpace event to notify the container that it has successfully connected to a namespace. You will need to connect this event to the CWBEMViewContainer::SetNameSpace method. This method, in turn, fires the CWBEMViewContainer::GetIWbemServices event to obtain an interface pointer to the requested namespace. You will need to handle this event by connecting it to the CSecurity::GetIWbemServices method, which returns an IWbemServices interface pointer to the requested namespace. You will pass this pointer back to the Object View Container control. You must use the same CSecurity object that you initialized in the CWbemBrowserView class.

In summary, to connect the navigator to the object viewer container, you will need to implement these steps:

  • Give the CWbemBrowserView view a pointer to the Object Viewer Container control and give the CObjectView a pointer to the WMI Navigator and WMI Login controls. With this approach, all three controls can communicate with each other.
  • Connect the CNavigator::OnNotifyOpenNameSpace event to the CWBEMViewContainer::SetNameSpace method.

    This step initializes the NameSpace property and fires the GetIWbemServices event.

  • Call the CSecurity::GetIWbemServices method from the CWBEMViewContainer::GetIWbemServices event handler.

To allow the WMI Navigator, WMI Login, and WMI Object Viewer Container controls to communicate, you must add a pointer to the Object Viewer Container control to the CWbemBrowserView class and add pointers to the WMI Navigator and WBEM Login controls to the CObjectView class. The following procedure provides the details.

To connect WMI Navigator and WMI Object Viewer Container controls

  1. Add a forward reference to the CWBEMViewContainer class to the beginning of the WbemBrowserView.h file just before the CWbemBrowserView class definition.
  2. Add a member pointer to the CWBEMViewContainer object to the CWbemBrowserView class definition.
    class CWBEMViewContainer;

class CWbemBrowserView : public CView
{
protected: // create from serialization only
    CWbemBrowserView();
    DECLARE_DYNCREATE(CWbemBrowserView)

// Attributes
public:
    CWbemBrowserDoc* GetDocument();

    CNavigator m_Navigator;
    CSecurity  m_Security;
    bool m_bReady;

    CWBEMViewContainer* m_pViewContainer;
  3. Include the Wbemviewcontainer.h file at the beginning of the WbemBrowserView.cpp file.
    #include "WbemBrowserDoc.h"
#include "WbemBrowserView.h"
#include "wbemviewcontainer.h"
  4. Following the same pattern described in steps 1 through 3, add forward references to the CNavigator and CSecurity classes to the beginning of the ObjectView.h file just before the CObjectView class definition.
  5. Add member pointers to the CNavigator and CSecurity objects to the CWbemBrowserView class definition by adding the following bolded lines of text to the code.
    class CNavigator;
class CSecurity;

class CObjectView : public CView
{
protected:
    CObjectView();           // protected constructor used by dynamic creation
    DECLARE_DYNCREATE(CObjectView)

// Attributes
public:
    CWBEMViewContainer m_ViewContainer;

    CNavigator* m_pNavigator;
    CSecurity*  m_pSecurity;
  6. Include Navigator.h and Security.h at the beginning of ObjectView.cpp.
    #include "WbemBrowser.h"
#include "ObjectView.h"
#include "navigator.h"
#include "security.h"
  7. You may build the project at this point to verify that it builds without errors. The logical place to initialize the new member pointers is in the CMainFrm::OnCreateClient method, because CMainFrm recognizes both views.
        // Select the rightmost pane.
    SetActiveView((CView*) m_wndSplitter.GetPane(0,1));

    // Connect the two views together.
    CWbemBrowserView* pBrowserView;
    CObjectView* pObjectView;

    pBrowserView = (CWbemBrowserView*) m_wndSplitter.GetPane(0,0);
    pObjectView = (CObjectView*) m_wndSplitter.GetPane(0,1);

    pBrowserView->m_pViewContainer = &pObjectView->m_ViewContainer;
    pObjectView->m_pNavigator = &pBrowserView->m_Navigator;
    pObjectView->m_pSecurity  = &pBrowserView->m_Security;

    return TRUE;
  8. To connect the CNavigator::OnNotifyOpenNameSpace event to the CWBEMViewContainer::SetNameSpace method, add the following bolded lines of code to the CWBEMBROWSERVIEW::ONNOTIFYOPENNAMESPACEINSTNAVCTRL1 event handler.
    void CWbemBrowserView::OnNotifyOpenNameSpaceInstnavctrl1(LPCTSTR lpcstrNameSpace)
{
    m_pViewContainer->SetNameSpace(lpcstrNameSpace);
}

    This step initializes the NameSpace property and fires the CWbemBrowserView::GetIWbemServices event.

  9. To call the CSecurity::GetIWbemServices method from the CWBEMVIEWCONTAINER::GETIWBEMSERVICES event handler, add the following bolded lines of code to the COBJECTVIEW::ONGETIWBEMSERVICESOBJVIEWERCTRL1 event handler:
    void CObjectView::OnGetIWbemServicesObjviewerctrl1(LPCTSTR szNamespace, VARIANT FAR* pvarUpdatePointer, VARIANT FAR* pvarServices, VARIANT FAR* pvarSc, VARIANT FAR* pvarUserCancel)
{
    m_pSecurity->GetIWbemServices(szNamespace, pvarUpdatePointer, pvarServices, pvarSc, pvarUserCancel);
}

    At this point, the object viewer container control is initialized with an IWbemServices pointer, pointing to the selected namespace on the selected server, the one you logged into. The navigator control then fires a CNavigator::ViewObject event, passing it the fully qualified instance object path to the currently selected node, initially the root node. The syntax of a fully qualified instance object path is:

    \\Server\Namespace:Class.KeyName="KeyValue"

    In our example, the instance object path is:

    \\A-MTRACY1\root\CIMV2:Win32_ComputerSystem.Name="A-MTRACY1"

    This reads, "The instance of the Win32_ComputerSystem class from the root\CIMV2 namespace on the MTRACY1 machine, whose key property KeyName is "A-MTRACY1".

    Whenever the user selects a node in the tree that represents a WMI object, the ViewObject event is fired, and the selected object's path is a parameter. You must use this instance object path to set the CWBEMViewContainer::ObjectPath property. The ObjectPath property selects the object instance whose properties, methods, and associations are displayed by the object viewer container in the right pane of the browser.

  10. To connect the CNavigator::ViewObject event to the CWBEMViewContainer::ObjectPath property, add the following lines of bolded code to the CWBEMBROWSERVIEW::ONVIEWOBJECTINSTNAVCTRL1 event handler.
    void CWbemBrowserView::OnViewObjectInstnavctrl1(LPCTSTR bstrPath)
{
    // Convert LPCTSTR to VARIANT of type VT_BSTR
    COleVariant varPath(bstrPath);

    m_pViewContainer->SetObjectPath(varPath);
}
  11. Build the project and run it.

    You should see the properties, methods, and associations of the root node in the right pane of the browser.

One connection between the navigator and the object viewer container remains to be made. As you have seen, clicking a regular object node in the left pane of the browser generates a CNavigator::ViewObject event. But clicking a group object (one that has a folder as part of its icon) generates a CNavigator::QueryViewInstances event instead.

  12. A group object can be displayed by the object viewer container's QueryViewInstances method. To connect the CNavigator::QueryViewInstances event to the CWBEMViewContainer::QueryViewInstances method, add the following lines of bolded code to the CWBEMBROWSERVIEW::ONQUERYVIEWINSTANCESINSTNAVCTRL1 event handler:
    void CWbemBrowserView::OnQueryViewInstancesInstnavctrl1(LPCTSTR pLabel, LPCTSTR pQueryType, LPCTSTR pQuery, LPCTSTR pClass)
{
    m_pViewContainer->QueryViewInstances(pLabel, pQueryType, pQuery, pClass);
}
  13. Build the project and run it. Then, select a group object.

    You should see the associations of the selected object displayed in the right pane of the browser.

    This completes the tutorial on creating a WMI browser in MFC.


Cabinet File Extraction Application

[This is preliminary documentation and subject to change.]

CabExtract.exe is a command-line application. It is intended for use by Independent Software Vendors (ISVs) to properly extract and register the Windows Management Instrumentation (WMI) redistributable Microsoft® ActiveX® controls from Wbemtool.cab. CabExtract.exe is also redistributable.

Note CabExtract.exe is not intended to be a general tool for extracting files from cabinet files (.cab files) and is therefore not supported in this capacity. It is only supported for use with the WMI ActiveX controls.

By incorporating CabExtract.exe into your setup program, you can safely redistribute ActiveX controls (*.ocx files) along with your software products. CabExtract.exe automatically extracts ActiveX controls along with their associated DLLs into the proper location during your software's setup process.

Note For licensing information on the redistribution of CabExtract.exe and ActiveX controls, see Redist.txt in the SDK License folder in the SDK installation directory.

This section contains the following topics:

  • About CabExtract.exe
  • Using CabExtract.exe
  • CabExtract.exe Reference


About CabExtract.exe

[This is preliminary documentation and subject to change.]

You run CabExtract.exe by specifying the ActiveX control (*.ocx file) you want to extract. When the ActiveX control is extracted, all of its dependent DLL files are automatically extracted as well. The extracted files are copied to a standard destination folder defined in the WBEMTool.inf file, which is in the Wbemtool.cab file.


Wbemtool.cab

[This is preliminary documentation and subject to change.]

The Wbemtool.cab file contains all the WMI-specific ActiveX controls. When you use CabExtract.exe on Wbemtool.cab, all ActiveX control files and associated DLL files are placed in the %SYSTEMROOT%\System32 folder. You must not install or move them to another folder because other applications might be using the same set of controls. Only one version of a control with a particular class identifier can be registered with the system at one time. CabExtract.exe performs control version checking before overwriting existing controls. The extracted files are automatically registered with Microsoft Windows NT, Microsoft Windows 2000, Microsoft Windows 95, or Microsoft Windows 98.

To install every ActiveX control contained in Wbemtool.cab, run CabExtract.exe on Wbemtool.cab, specifying the class identifier of WBEMObjView.ocx ({5B3572AB-D344-11CF-99CB-00C04FD64497}). All of the other .ocx and DLL files will be installed.


Wbemtool.cab Files

[This is preliminary documentation and subject to change.]

To install every ActiveX control contained in Wbemtool.cab, specify the class identifier and version of WBEMObjView.ocx ({5B3572AB-D344-11CF-99CB-00C04FD64497}). All of the other .ocx and DLL files will be installed. If you do not need to extract every file from Wbemtool.cab, supply CabExtract.exe with the class identifier and version of the ActiveX control you want.

The Wbemtool.inf file is an ActiveX information file that contains all the file names and class identifiers used to compile Wbemtool.cab. The following table shows the individual files (and their associated CLSIDs) that you might extract from Wbemtool.cab.

Module | Class Identifier | Version Number
WBEMObjView.ocx | {5B3572AB-D344-11CF-99CB-00C04FD64497} | BUILDFILEVERSION
WBEMSingleView.ocx | {2745E5F5-D234-11D0-847A-00C04FD7BB08} | BUILDFILEVERSION
WBEMInstNav.ocx | {C7EADEB3-ECAB-11CF-8C9E-00AA006D010A} | BUILDFILEVERSION
WBEMMultiView.ocx | {FF371BF4-213D-11D0-95F3-00C04FD9B15B | BUILDFILEVERSION
WBEMClassNav.ocx | {C587B673-0103-11D0-8CA2-00AA006D010A} | BUILDFILEVERSION
WBEMLogin.ocx | {9C3497D6-ED98-11D0-9647-00C04FD9B15B} | BUILDFILEVERSION
WBEMHelp.ocx | {CFB6FE45-0D2C-11D1-964B-00C04FD9B15B | BUILDFILEVERSION
WBEMEventReg.ocx | {0DA25B05-2962-11D1-9651-00C04FD9B15B} | BUILDFILEVERSION
WBEMMOFComp.ocx | {B2345983-5CF9-11D0-95FD-00C04FD9B15B} | BUILDFILEVERSION
WBEMMOFWiz.ocx | {F3B3A403-3419-11D0-95F8-00C04FD9B15B} | BUILDFILEVERSION
WBEMProvWiz.ocx | {35E9CBD3-3911-11D0-8FBD-00AA006D010A} | BUILDFILEVERSION
WBEMNSPicker.ocx | {C3DB0BD3-7EC7-11D0-960B-00C04FD9B15B} | BUILDFILEVERSION
WBEMEventList.ocx | {AC146530-87A5-11D1-ADBD-00AA00B8E05A} | BUILDFILEVERSION
mfc42u.dll |  | 4,20,0,6168
msvcrt.dll |  | 4,20,0,6201
msvcirt.dll |  | 4,20,0,6164
moengine.dll |  | BUILDFILEVERSION
WBEMUtils.dll |  | BUILDFILEVERSION
WBEMGrid.dll |  | BUILDFILEVERSION
WBEMLoginDlg.dll |  | BUILDFILEVERSION

Note Substitute the actual build file version number for BUILDFILEVERSION. To find the build file version number, right-click CabExtract.exe, click Properties, and then click the Version tab. You can select the version number and copy it for use at the command prompt. The version number is the same for all files, including the cab extractor and ActiveX controls, in any given build.


Using CabExtract.exe

[This is preliminary documentation and subject to change.]

CabExtract.exe is a command-line application. It is intended for use by Independent Software Vendors (ISVs) to properly extract and register the Windows Management Instrumentation (WMI) redistributable Microsoft ActiveX controls from Wbemtool.cab. CabExtract.exe is also redistributable.

Note CabExtract.exe is not intended to be a general tool for extracting files from cabinet files (.cab files) and is therefore not supported in this capacity. It is only supported for use with the WMI ActiveX controls.

The following topics describe how to use CabExtract.exe:

  • Extracting Files from Wbemtool.cab
  • CabExtract.exe Example


Extracting Files from Wbemtool.cab

[This is preliminary documentation and subject to change.]

The following steps describe how to extract files from Wbemtool.cab.

To use CabExtract.exe to extract files from Wbemtool.cab

  1. Click Start, point to Programs, and click Command Prompt.
  2. Navigate to Program Files/Redist/WMI, which is the folder that contains Wbemtool.cab.
    1. Type cabextract followed by a space.
    2. Type the name of the cabinet file (Wbemtool.cab), followed by a space.
    3. Type the class ID of the ActiveX control you want, followed by a space.
    4. Type the version number of the ActiveX control you want.
    5. Press Enter.

When the .ocx file is extracted, all files that support the .ocx file are automatically extracted as well. The extracted files are copied to the destination folder originally specified in the initialization file (*.ini) used to create the cabinet file. Additionally, the extracted files are registered with the user's computer.

To install every ActiveX control contained in Wbemtool.cab, run CabExtract.exe on Wbemtool.cab, specifying the class identifier of WBEMObjView.ocx ({5B3572AB-D344-11CF-99CB-00C04FD64497}). All of the other .ocx and DLL files will be installed.

If you choose to extract the ActiveX information programmatically rather than with CabExtract.exe, you can use the CoGetClassObjectFromURL function. For more information on this API, see the Microsoft COM API documentation on the MSDN web site on http://msdn.microsoft.com.


CabExtract.exe Example

[This is preliminary documentation and subject to change.]

The following example shows how to extract the login ActiveX control called WBEMLogin.ocx. The class identifier of the ActiveX control is {9C3497D6-ED98-11D0-9647-00C04FD9B15B}, and the version number is 1.50.1015.0.

"C:\Program Files\WBEM\Redist\CabExtract.exe" "E:\Program Files\WBEM\Redist\WbemTool.cab" {9C3497D6-ED98-11D0-9647-00C04FD9B15B} 1.50.1015.0

Note Use the full path when specifying both CabExtract.exe and Wbemtool.cab. Quotation marks surround the full path of both the cab extraction utility file and the .cab file. This prevents the space between Program and Files from being interpreted as a delimiter.

Substitute the actual build file version number for BUILDFILEVERSION. To find the actual build file version number, right-click CabExtract.exe, click Properties, and then click the Version tab. You can select the version number and copy it for use at the command prompt. The version number will be the same for all files, including the cab extractor and ActiveX controls, in any given build.


CabExtract.exe Reference

[This is preliminary documentation and subject to change.]

Input Parameter | Description
Cabfile | The name of the cabinet file from which you want to extract the ActiveX control. Example: cabfile.cab
Class ID | The class identifier of the ActiveX control. Example: {9C3497D6-ED98-11D0-9647-00C04FD9B15B} Note: Include the curly braces.
Version | The version number of the ActiveX control. Example: 1.50.1015.0


Managed Object Format (MOF) Language

Managed Object Format (MOF) is a compiled language created by the Distributed Management Task Force (DMTF). MOF is based on the Interface Definition Language (IDL). You can use MOF to define static or dynamic classes and class instances. You place these definitions in a file that you submit to the MOF compiler, Mofcomp.exe. The MOF compiler parses the file and adds the classes and instances defined in the file to the Common Information Model (CIM) repository.

MOF definitions of classes and instances use ASCII or Unicode text. For localization safety, all distributed MOF files are Unicode text. Users are strongly discouraged from writing MOF files in ANSI text.

To submit a MOF file to the compiler, at a command prompt enter the name of the compiler followed by the name of the file, as follows:

mofcomp MOFfilename

The MOF compiler supports a number of options that you can specify with command-line switches. For example, the following command invokes the compiler to a specific remote namespace, user name, and password:

mofcomp –N:\\machine_name\root\special –U:Joe –P:xyz  myfile.mof

For a complete description of the command-line syntax for the MOF compiler, see MOF Compiler. To view the Backus-Naur Form definition for the MOF syntax, see BNF Syntax for Managed Object Format (MOF).

Most actions performed through MOF can also be performed through calls to the Windows Management Instrumentation (WMI) API. For more information on using the WMI API instead of MOF, see WMI Application Programming and WMI Provider Programming.

For more information on MOF, see the following topics:

  • Declaring Classes
  • Declaring Instances
  • Declaring Methods
  • Using Aliases
  • Using Qualifiers
  • Using Qualifier Flavors
  • MOF Data Types
  • Specifying Comments
  • Specifying Namespaces


Declaring Classes

You can use the Managed Object Format (MOF) language to define new base classes and classes that derive from existing classes. To declare the most basic class, use the Class keyword with the name of the new class, followed by a pair of curly braces and a semi-colon.

class ClassName
{
};

Class names are case-insensitive; they must start with a letter, and they cannot have either a leading or trailing underscore. All remaining characters must be letters, digits, or underscores. It is recommended that class names have two components joined by an underscore; the vendor name is the first part and a descriptive class name is the second part. For example, this class name might describe the LogicalDisk class manufactured by CompanyX.

CompanyX_LogicalDisk

Most classes include properties that describe the data of the class. To declare a property, include the property's data type, name, and an optional default value between the curly braces.

class MyClass
{
    [key] string   strProp;
    sint32   dwProp1 = 21;
    uint32       dwProp2;
};

The MyClass class in the preceding example has three properties: a character string, a 32-bit signed integer, and a 32-bit unsigned integer. Each property is assigned a name, which is case-insensitive, and one of the data types defined by the MOF language.

The string property acts as the key for the class; its value uniquely identifies an instance of the class. As an option, a property can be assigned an initial value, as shown in the preceding example of the 32-bit signed integer.

Classes can also include methods that describe the behavior of the class. Methods are declared much as properties are. The following code illustrates how to declare a class that includes two methods: one that returns a 32-bit integer and another that has no return value. The VOID keyword can be used to indicate a method that does not have a return value.

class MyClass
{
    sint32  Method1 ();
    void    Method2 ([in] sint32 InParam);
};

Class definitions can be more complicated, including such MOF features as aliases, qualifiers, and qualifier flavors. The [key] descriptor in the sample code that declares a property preceding is an example of a standard qualifiers.

For information about creating a base class using WMI instead of the MOF language, see Creating a Base Class.


Declaring a Derived Class

You declare classes that derive from other classes in MOF syntax with a colon followed by the name of the superclass. The following statements define a superclass and a derived class.

class MyClass
{
    [key] string   strProp;
    sint32   dwProp1;
    uint32       dwProp2;
};

class MyDerivedClass : MyClass
{
    string   strDerivedProp;
    sint32   dwDerivedProp;
};

Derived classes always include the properties of their base class. WMI allows derived classes to:

  • Add new properties.
  • Add or change a qualifier on a base class property if the flavors assigned to the qualifier allow it.
  • Change the default value of a base class property.
  • More strongly type a reference or embedded object property of the base class by changing its Cimtype qualifier. For more information on using this qualifier, see WMI Standard Qualifiers.

To perform the last three operations listed preceding using MOF syntax, you must redeclare the base class property. The MOF compiler interprets this redeclaration as a request to:

  • Change the default value as specified.
  • Add or change all the qualifiers that are specified.

When the MOF compiler attempts to add a derived class to the Common Information Model (CIM) repository, the derived class's superclass must already exist. The declaration of the superclass can appear in the same MOF file as the derived class or in a different file. If the superclass is unknown, the compiler generates a runtime error.

A derived class can only have a single superclass; WMI does not support multiple inheritance. However, a superclass can have many derived classes.

Note You can define indices for derived classes, but WMI does not use these indices. Therefore, specifying an index on a derived class does not improve the performance of queries for instances of the derived class. You can improve the performance of a query on a derived class by specifying indexed properties for the derived class's parent class.

For information about creating a derived class using the WMI API instead of the MOF language, see Creating a Derived Class.


Declaring an Association Class

An association class is a special type of class that defines a relationship between two other classes. Every association class is identified by the Association qualifier. An association class has two or more ref (reference) properties that each provide a path to a namespace, class, or class instance that identifies one of the related classes. An association class can also have other types of properties.

The following example illustrates how to declare an association class. The MyAssocClass class defines a relationship between ClassX and ClassY. The ref properties PathToClassX and PathToClassY contain object paths to the instances of the classes to be associated. Object paths cannot contain spaces either within an element or between elements. For more information about object path syntax, see Object Paths.

The keyword ToInstance is one of several flavor flags that WMI defines to provide information about the use of a qualifier. ToInstance indicates that the Association qualifier is propagated to all instances of the association class. By checking this instance qualifier, the client software can determine that an instance belongs to an association class without having to retrieve the class definition to look for the Association qualifier. For more information about qualifier flavors, see Using Qualifier Flavors

[Association : ToInstance]
class MyAssocClass
{
    ClassX ref PathToClassX ;
    ClassY ref PathToClassY ;
};


Declaring Instances

To declare an instance of a class, use the Instance of keyword followed by the class name, curly braces, and a semi-colon, as shown following:

instance of ClassName
{
};

An instance of a class includes all of the properties of the class. If the class is a derived class, instances include the properties belonging to all of the classes higher in the hierarchy. Because properties are strongly typed, you cannot modify property types in instances. You can, however, set property values in instances. By default, when a class assigns a default value to a property, that value is also assigned in each of the instances. You can override this default value in an instance by placing an assignment statement between the instance declaration's curly braces, as follows.

instance of ClassName
{
    Prop = "value";
};

An instance need not provide an explicit value for a property unless the property is a key. Values for key properties must be explicitly set to enable the instance to be properly identified. You cannot set system properties in instance declarations; WMI assigns values to system properties when an instance is created.

Qualifiers can be propagated to instances. Qualifiers are optional tags that are attached to the class or properties of the class. When the flag ToInstance is associated with a qualifier attached to a class, that qualifier is propagated to all of the instances of that class. ToInstance is one of several qualifier flags known as flavors. Flavors provide information about the use of the qualifier to which they are associated. For more information about qualifiers and qualifier flavors, see Using Qualifiers and Using Qualifier Flavors.

The following class and instance declarations show how an instance specifies data for properties defined by the class. The class defines three properties: a character string, a 32-bit signed integer, and a 32-bit unsigned integer. The instance provides data values for each of these properties.

class MyClass
{
    [key] string   strProp;
    sint32   dwProp1;
    uint32       dwProp2;
};

instance of MyClass
{
    strProp = "hello";
    dwProp1 = -1;
    dwProp2 = 0xffffffff;
};

For information about creating an instance using the Windows Management Instrumentation (WMI) API instead of the Managed Object Format (MOF) language, see Creating an Instance.


Declaring Methods

Class declarations can include the declaration of one or more methods. An implementation of a method may or may not be available, depending on whether there is a class provider for the class and whether that provider supplies an implementation. Although a method definition is always passed on from a superclass to a subclass, the method's implementation may not be. The Implemented qualifier must be associated in a class with any method that has an implementation in that class. Omission of the Implemented qualifier indicates that the method has no implementation in that class. For more information on using qualifiers, see Using Qualifiers.

If a method is redeclared for a class without the Implemented qualifier, it is considered unimplemented for that class, and the invoked implementation at run time is the implementation of the superclass. The implementation of the superclass is always propagated to a derived class unless the derived class provides its own implementation. Redeclaration of a method in a derived class is useful only when a qualifier is added to or removed from the method.

When a provider supplies the implementation of a method, it must mark the class with the Provider qualifier. The value of the Provider qualifier is the name of the provider. A provider should mark classes with dynamic instances with the Dynamic qualifier. A provider must not mark classes with static instances that have Implemented methods with the Dynamic qualifier.

Every method must have a unique name. Windows Management Instrumentation (WMI) does not allow two methods with the same name and different signatures to exist in one class or within a class hierarchy. Methods cannot be overloaded.

The return value for a method must be one of the basic CIM data types, specifically, Boolean, numeric, CHAR, STRING, or DATETIME. You should list parameters with both their name and type. You must mark them either as input parameters using the In qualifier, as output parameters using the Out qualifier, or as input-output parameters using the In, Out qualifier.

Parameters are automatically marked with an Id qualifier. The Id qualifier is added by the MOF compiler, unless explicitly specified in the MOF definition of the method. Id qualifiers uniquely identify each parameter's position within the sequence of parameters in the method signature. The first parameter is assigned a value of zero. The second parameter is assigned a value of 1, and so on.

The following code illustrates parameter listing and qualifiers.

[Dynamic, Provider ("ProviderX")]
class MyClass
{
    [Implemented]
    sint32 MyMethod1 ([in, id(0)] sint32 InParam);
    [Implemented]
    void MyMethod2 ([in, id(0)] sint32 InParam,
       [out, id(1)] sint32 OutParam);
    [Implemented]
    sint32 MyMethod3 ([in, out, id(0)] sint32 InOutParam);
};

Parameters lacking initial values remain unassigned.

You cannot use the same parameter name more than once as an input parameter or more than once as an output parameter. If the same parameter name appears with both an In and an Out qualifier, the functionality is conceptually the same as using the In, Out qualifier on a single parameter. However, when using separate declarations, the input and output parameters must be exactly the same in all other respects including the number and type of qualifiers, and the id qualifier must be the same and explicitly declared for both. It is strongly recommended to use the In, Out qualifier within a single parameter declaration.

Schema objects—classes stored in the Common Information Model (CIM) repository—can be used as either parameters or return values, as the following example illustrates.

[Dynamic, Provider ("ProviderX")]
class MyClass
{
    [Implemented] sint32 MyMethod1 ([in, id(0)] Win32_LogicalDisk
        DiskParam);
    [Implemented]
    Win32_LogicalDisk MyMethod2 ([in, id(0)] string DiskVolLabel);
};

You can only pass arrays as parameters; you cannot use them as return value types. Arrays can be unbounded or have an explicit size, as is illustrated in the following code sample.

[Dynamic, Provider ("ProviderX")]
class MyClass
{
    [Implemented]
    sint32 MyMethod1 ([in, id(0)] Win32_LogicalDisk DiskParam[]);
    [Implemented]
    sint32 MyMethod2 ([in, id(0)] Win32_LogicalDisk DiskParam[32]);
};

The Managed Object Format (MOF) language supports the use of references as parameters. References are paths to namespaces, classes, or instances. References are represented by the REF data type. Using references reduces transport time and encoding if the target of the reference already exists entirely within the CIM repository. The following class definition shows how to include two references: one to an instance of the Win32_LogicalDisk class and the other to an instance of an unknown object type.

[Dynamic, Provider("ProviderX")]
class MyClass
{
    [Implemented]
    sint32 MyMethod1 ([in, id(0)] Win32_LogicalDisk ref DiskRef);
    [Implemented]
    sint32 MyMethod2 ([in, id(0)] object ref AnyObject);
};


Using Aliases

An alias is a symbolic reference in either a class or class instance declaration to an instance located elsewhere in a Managed Object Format (MOF) file. Alias names follow the same rules as instance and class names, except that alias names must begin with a dollar sign ($). Underscores can appear in an alias name following the initial character. Aliases are typically used as shortcuts to lengthy object paths.

To define an alias, add the phrase "as $AliasName" to the instance or class declaration.

class MyClass as $MyClassAlias
{
};

instance of MyClass as $MyInstanceAlias
{
};

The following examples illustrate how to use an alias as a symbolic reference to an object path. These examples declare two classes to describe a disk: the Disk class to indicate the drive letter and the DiskRef class to indicate the disk path. An alias is defined for the Disk class instance. This alias is used as the value for the PathToDisk property in the DiskRef instance.

class Disk {
    [key]  string    DriveLetter;
};

class DiskRef
{
    [key]  string    MyKey;
    Disk   ref       PathToDisk;
};

instance of Disk as $DiskAlias
{
    DriveLetter = "c";
};

instance of DiskRef
{
    MyKey      =  "hello";
    PathToDisk = $DiskAlias;
};

Aliases have scope only within the MOF file in which they are declared. They are used at compile time to make it easy to establish references. The compiler resolves aliases to the classes to which the refer, so they are not available in compiled code. As a result, client applications cannot refer to classes using aliases.

Note Windows Management Instrumentation (WMI) supports forward referencing but not circular aliases.


Using Qualifiers

Qualifiers are modifiers that can be used to describe a class, a class instance, a property, a method, or a parameter. Like properties, qualifiers each have a name, a type, and a value. Unlike properties, the values of qualifiers rarely change.

Also unlike properties, each qualifier can be associated with a flag known as a flavor. Qualifier flavors indicate how a qualifier is used. For example, the qualifiers of a base class are propagated to its derived classes only if they have been assigned the flavor ToDerivedClass. Propagated qualifiers have the values defined originally in the base class unless the qualifiers have the flavor EnableOverride. For information about adding flavors, see Qualifier Flavors.

For more information on qualifiers, see the following topics:

  • Qualifier Naming and Syntax
  • Types of Qualifiers


Qualifier Naming and Syntax

Windows Management Instrumentation (WMI) enforces few rules regarding the naming of qualifiers and their use.

Qualifier names cannot have either leading or trailing underscores and cannot begin with a digit, or contain special characters such as * & @ ! ~ \ /. Moreover, neither the standard WMI qualifiers or those included in the Distributed Management Task Force (DMTF) Common Information Model (CIM) specification can be redefined. To avoid potential conflict, a provider should prefix new qualifiers with the name of its schema.

When using Managed Object Format (MOF) syntax, you should place a qualifier in brackets before the keyword or identifier that it describes.

[QualifierName1 ("QualifierValue1")]

The following syntax shows the placement of class, property, method, and parameter qualifiers.

[qualifiers...]
class MyClass
{
    [qualifiers...]  uint32 dwNumber;
    [qualifiers...]  sint32 ValueMethod ();
    [qualifiers...]  sint32 MyMethod ([qualifiers...] sint32 Param);
};

All qualifier names are case-insensitive. Unlike property and method types, qualifier types are not explicitly declared. If no initial qualifier values are declared, the qualifier type is assumed to be Boolean with a value of TRUE. Otherwise, qualifiers are implicitly typed based on the qualifier values declared.

Valid qualifier types and their corresponding CIM and Automation types are listed in the following table.

Qualifier type | Automation type
String | VT_BSTR
Unsigned 16 bit integer, signed or unsigned 32 bit integer | VT_I4
Signed or unsigned 64-bit number | VT_BSTR
Floating point | VT_R8
Boolean | VT_BOOL

Homogeneous arrays of any of these types are supported. Qualifier arrays are specified with braces surrounding the values.

[StringArray{"hello", "there"}, SingleElementArray{3}]

Other automation types such as VT_NULL are not supported.


Types of Qualifiers

The following table lists some examples of qualifiers.

Qualifier | Used with | Purpose
Dynamic | Classes | Indicates that instances of a class are supplied by a provider.
Implemented | Methods | Indicates that an implementation of a method is available.
In | Parameters | Describes a parameter as an input parameter.
Read | Properties | Describes a property's value as read-only.
Units | Properties | Describes a property value's unit of measure.
Write | Properties | Describes a property's value as read/write.

Some of the qualifiers commonly used in Managed Object Format (MOF) syntax are defined by WMI and are known as standard qualifiers. The Dynamic and Read qualifiers are examples of standard qualifiers. Other qualifiers are included in the CIM specification, which is available from http://dmtf.org/spec/cim_spec_v20/. Still other qualifiers are defined specifically for new classes by class providers. The Units qualifier listed in the preceding table is an example of a nonstandard, provider-specific qualifier.

The following class definition is an example of a derived class that has class qualifiers. The class qualifiers, Dynamic and Provider, are standard qualifiers defined by WMI. Dynamic is a Boolean qualifier. When this qualifier is set, it indicates that instances of the class are dynamically provided. Provider is a string qualifier that supplies the name of the dynamic provider supporting the class.

[Dynamic, Provider ("ProviderX")]
class MyDerivedClass : MyClass
{
    [key] string sKey;
    [Implemented] sint32 ValueMethod();
    [Implemented] sint32 MyMethod ([in, Id(0)] sint32 Param)
};

Two standard qualifiers that are commonly used with methods are the Implemented and Static qualifiers. The Implemented qualifier indicates whether a method has an implementation available for the particular class or instance. Because the data type of this qualifier is Boolean, the qualifier's absence indicates the absence of an implementation. For more information, see Declaring Methods. The Static qualifier indicates that a method can only be called from an object path to a class definition.

Parameters to methods can have standard qualifiers that describe whether a parameter is an input parameter, an output parameter, or an input parameter and output parameter. The Id standard qualifier is required on all method parameters. It uniquely tags each parameter in a method.

[Dynamic, Provider ("ProviderZ")]
class MyMethodClass
{
    [read, write, key] STRING  MyKey;
    [implemented] sint32 MyMethod1 ([in, Id(0)] uint32 Param1);
    [static] sint32 MyMethod2 ([out, Id(0)] uint32 Param2);
    sint32 MyMethod3 ([in, Id(0)] uint32 Param3,
        [in, out, Id(1)] string Param4);
};


Using Qualifier Flavors

A qualifier flavor is a flag that describes the usage of a qualifier. The Managed Object Format (MOF) language defines several qualifier flavors that can be attached to any qualifier, regardless of the qualifier's origin. For example, the same flavor can be used to describe a standard class qualifier in Windows Management Instrumentation (WMI) such as Association or a property qualifier defined by a provider for a specific class.

However, some flavors are not appropriate for all qualifier types. The ToSubclass flavor, for example, is appropriate only for qualifiers defined for a class. It cannot be attached to a qualifier used to describe a class instance.

Flavors appear in the MOF syntax as follows. When multiple flavors are specified for a qualifier, white space acts as the delimiter.

[qualifier1 : flavor1 flavor2 flavor3, qualifier2 : flavor1]

The following table describes the flavor flags.

Flavor | Meaning
Amended | The qualifier is not required in the basic class definition and can be moved to the amendment to be localized. See WMI Localization for more information.
DisableOverride | When propagated to a derived class or instance, the value of the qualifier cannot be overridden. Because enabling a propagated qualifier to be overridden is the default, DisableOverride must be set to disallow such an override.
EnableOverride | When propagated to a derived class or instance, the value of the qualifier can be overridden. Setting EnableOverride is optional because being able to override the qualifier value is the default functionality for propagated qualifiers.
NotToInstance | The qualifier is not propagated to class instances.
NotToSubclass | The qualifier is not propagated to derived classes.
Restricted | The qualifier is not propagated to instances or derived classes.
ToInstance | The qualifier is propagated to instances.
ToSubclass | The qualifier is propagated to derived classes.

Flavors that establish whether a propagated qualifier can be overridden are valid only if ToInstance or ToSubclass is set.


MOF Data Types

The Managed Object Format (MOF) language supports many data types that can be used to assign values to properties, qualifiers, and method parameters. Some of these data types map to automation data types.

Every MOF data type has a corresponding type identifier. Type identifiers are constants defined by Windows Management Instrumentation (WMI) to represent MOF data types and are used by the WMI API to describe properties.

All MOF data types are case-insensitive.

The MOF language supports the following categories of data types:

  • Array
  • Boolean
  • Date-time
  • Embedded object
  • Enumeration
  • Numeric
  • String
  • Reference
  • Void


MOF Arrays

In addition to more standard string and numeric arrays, MOF supports many different types of arrays, such as arrays of references and embedded objects, in addition to more standard string and numeric arrays. All arrays must be one-dimensional. Arrays can be unbounded or have an explicit size.

Class MyClass
{
    sint32 MyMethod1 ([in, id(1)] Win32_LogicalDisk DiskArray1[]);
    sint32 MyMethod2 ([in, id(1)] Win32_LogicalDisk DiskArray2[32]);
};

WMI implements bounded and unbounded arrays as SAFEARRAY structures, enabling array dimensions to vary at run time. When an array is declared with an explicit size, this size is stored as a qualifier, and it is treated as the suggested maximum size. However, if necessary, WMI can expand the size. Changing the explicit size has no effect on the actual data.

Arrays are initialized by specifying values of the appropriate type in a comma-separated list.

All elements in an array must be values of the same type. If the elements of an array are of the object type, then any object is allowed in the array. On the other hand, if a specific type is declared, then only objects of that class or its subclasses are allowed.

To specify an array in a class declaration, use brackets after the property identifier. The following examples show array declarations.

class EmbedClass
{
    [key] sint32 PropOfClass;
};

class ArrayDataClass
{
    [key] string s;
    string strArray1[];
    string strArray2[] = {"hello", "there"};
    sint32 dwArray[] = {1,2,3};
    EmbedClass objArray[];
};

instance of ArrayDataClass
{
    s = "keyStuff";
    strArray1 = { "1.2.3.4", "1.2.3.5", "1.2.3.7"};
    strArray2 =
        {
            "select * from RegistryKeyChangeEvent",
            "select * from RegistryValueChangeEvent",
            "select * from RegistryTreeChangeEvent"
        };
    dwArray  = { 1,2,3,5,6};
    objArray = {
                     instance of EmbedClass{PropOfClass=3;},
                   instance of EmbedClass{PropOfClass=4;}
                 };
};

Arrays of references are simply arrays of object path strings.

instance of ClassWithRefArray
{
    s = 23;
    refArray = {"Disk.Name=\"C:\"", "Disk.Name=\"E:\"";};
};

Note that no white space occurs between the elements in the preceding object path. Object paths cannot include space between elements.

Arrays can be used only as parameters for methods in class declarations. They cannot function as return values for input parameters or input-output parameters.


MOF Boolean Data Type

The Boolean data type takes on the value of logical TRUE or logical FALSE. You can access this data type programmatically using the Automation type VT_BOOL, which takes values of VARIANT_TRUE (–1) or VARIANT_FALSE (0). Note the difference between the programmatic representations of logical TRUE in C/C++ and the Automation type:

  • C/C++: TRUE (1)
  • Automation: VARIANT_TRUE (-1)

Both types are nonzero and therefore not FALSE, but they have different representations for TRUE.


MOF DATETIME Data Type

The DATETIME data type is a fixed-length string that conforms to the format specified by the Distributed Management Task Force (DMTF). The string is made up of several fields. The Automation type for the DATETIME data type is VT_BSTR. A DATETIME property can represent a specific date and time or an interval. For information about the syntax of a DATETIME formatted string, see the following topics:

  • Date and Time Format
  • Interval Format


MOF Embedded Objects

MOF supports the use of objects fully embedded in class or class instance declarations. Objects in this context refer to instances of another class.

These objects can be declared as strongly or weakly typed, depending on whether a class name or the keyword object is used in the declaration. A weakly typed object points to an object of an unspecified class and uses the object keyword. A strongly typed object points to an object of a specific class and uses the class name. Both types map to the VT_UNKNOWN type. The following class declaration illustrates how to declare strongly and weakly typed embedded objects.

class MyClass
{
    EmbedClass    Object1;          // Strongly typed
    object            Object2;          // Weakly typed
};

The following examples show how to declare embedded objects within a class declaration. Note that no white space occurs between the elements in the embedded object paths.

class Class1
{
     [key] sint32 Class1Index;
};

class Class2
{
    [key] sint32 Class2Index;
    Class1 EmbedObject1 = instance of Class1{Class1Index=3;};
};

class Class3
{
    [key] sint32 Class3Index;
    Class2 EmbedObject2 = instance of Class2 {Class2Index=4;};
};

The following example shows the initialization of one property that is a strongly typed object and another property that is an array of weakly typed objects.

class EmbedClass1
{
    [key] sint32 intval;
};

class EmbedClass2
{
    [key] string sval;
};

class ContainerClass
{
    [key] sint32 intval;
    EmbedClass1 SingleObject;
    Object ArrayObject[];
};

Instance of ContainerClass
{
    intval = 33;
    SingleObject = instance of EmbedClass1 {intval=99;};
    ArrayObject = {instance of EmbedClass2 {sval="something";},
                   instance of EmbedClass1 {intval=100;}};
};

You can use NULL for the default value of embedded objects and paths in both initializations and declarations.

Note The MOF syntax does not currently support embedded objects within embedded objects.


MOF Value Maps

Integer properties can be defined in MOF syntax using the Values standard qualifier. The Values standard qualifier provides an array of string values used for interpreting the property's integer values. Permissible values are defined by using the ValueMap qualifier. The following code example demonstrates this principle:

[ValueMap {"1", "3", "99", "0"}, Values {"OK", "Error", "Degraded", "Unknown"}, Read]
sint32 Status;

In this example, the Status property must be set to an integer in the set: 1, 3, 99, or 0. Each integer is mapped to an ordinal position in the ValueMap string array and a corresponding position in the Values array. A property value of zero maps to the fourth entry in the ValueMap array and therefore, to the fourth value, "Unknown". If Status is set to 1, this maps to the first ordinal position and to the Value string, "OK."

Note Status takes on integer values, in spite of the fact that the ValueMap elements are quoted strings.

The ValueMap qualifier can be used with string or integer properties - defining their permissible values. The Values qualifier can be used with integer or string properties, but with the string property, you must specify ValueMap. This provides the translation of the property value into a string. If ValueMap is not specified, Values can only be used with integer properties, as shown in the following example:

[Values {"OK", "Error", "Degraded", "Unknown"}, Read]
sint32 Status;

In this example, the Status property value is used as the index into the string array defined by Values. Therefore, the value of Status must be set to an integer in the range from 0 through 3. The property can only take on values that correspond to the ordinal positions in the Values array minus 1. A property value of zero maps to the first entry in the array ("OK"). If Status is set to 1, its value maps to the string "Error." If Status is set to 3, its value maps to the string "Unknown."

Note To participate, an integer property can only take on values that correspond to positions in the Values array. If the array has 10 entries, the integer property can have values 0 through 9, not 30 or 117. It is up to the application to take advantage of mappings in a useful way. It is up to the provider to enforce a legal range of values.

With a string property, the actual allowable values of the property are the entries in the ValueMap array. For example, Status can be set to "OK" or "Unknown", as in the following code.

[ValueMap {"OK", "Error", "Degraded", "Unknown"},
 Values {"OK", "Error", "Degraded", "Unknown"}, Read]
string Status;


MOF Numeric Data Types

The MOF supports the following types of numeric values.

Data type | Automation type | Description
Sint8 | VT_I2 | Signed 8-bit integer.
Sint16 | VT_I2 | Signed 16-bit integer.
Sint32 | VT_I4 | Signed 32-bit integer.
Sint64 | VT_BSTR | Signed 64-bit integer in string form. This type follows hexadecimal or decimal format according to the American National Standards Institute (ANSI) C rules.
Real32 | VT_R4 | Four-byte floating point that follows the Institute of Electrical and Electronics Engineers, Inc. (IEEE) standard.
Real64 | VT_R8 | Eight-byte floating point that follows the IEEE standard.
Uint8 | VT_UI1 | Unsigned 8-bit integer.
Uint16 | VT_I4 | Unsigned 16-bit integer.
Uint32 | VT_I4 | Unsigned 32-bit integer.
Uint64 | VT_BSTR | Unsigned 64-bit integer in string form. This type follows hexadecimal or decimal format according to ANSI C rules.

Note Integers in 64-bit format must be encoded as strings because Automation does not support a 64-bit integral type.

Automation types do not always correspond in bit size to MOF data types. For example, VT_I4 is used to return an Uint16 value. This discrepancy is because of sign-extension problems. If VT_I2 were used instead of VT_I4, 65,536 would appear to be the value –1, causing a number of type and range problems.

Because Automation does support an unsigned 8-bit type, VT_UI1, no change in representation is required for 8-bit numerals. The Uint32 type is represented as VT_I4 because there is no larger integer type to contain it.

Long constants are supported and are declared using a simple series of digits with an optional negative sign. A long constant cannot exceed the size of the variable that is declared to hold it. Some examples of long constants are 1000 and –12310.

Hexadecimal, binary, and octal constants are also supported; the following code sample demonstrates their syntax.

val = 65;                      // Decimal
val = 0x41;                    // Hexadecimal (0x prefix)
val = 0101;                    // Octal (leading zero)
val = 1000001B;                // Binary (trailing B)

Binary constants have a "b" or "B" suffix to indicate that the value is binary.

Floating-point constants can be used to represent scientific notation as well as fractions.

3.14
-3.14
-1.2778E+02

The following class and class instance declarations illustrate how to use each of the numeric data types to set properties.

class NumericDataClass
{
    [key] uint8      Duint8;
    SInt8            Dchar;
    UInt16           Dtword;
    Sint16           Dinst16;
    UInt32           DDword;
    Sint32           Dinst1;
    Sint32           Dinst2;
    Sint32           Dinst3;
    Sint32           Dinst4;
    Sint32           Dinst5;
    Real32           Dfloat;
    Real64           Ddouble1;
    Real64           Ddouble2;
};

instance of NumericDataClass
{
    Duint8   =  122;
    Dchar    = -128;
    Dtword   =  30;
    Dinst16  = -1445;
    Ddword   =  6987777;
    Dinst1   = -455589;
    Dinst2   =  23;
    Dinst3   =  03;                // Base 8
    Dinst4   =  0xFe;              // Base 16
    Dinst5   =  11b;               // Base 2
    Dfloat   =  3.1478;
    Ddouble1 =  99987.3654;
    Ddouble2 =  2.3e-2;
};


MOF Object Data Type

The OBJECT data type is used to declare weakly typed associations and embedded objects. The specific class for weakly typed objects is not defined until you create an instance of the class. Embedded objects defined with the OBJECT data type can contain instances of any WMI class.

The following example defines and creates instances of two classes, one of which contains an embedded object of type OBJECT.

#pragma namespace("\\\\.\\root")

instance of __Namespace
{
    Name = "WMI" ;
} ;

#pragma namespace("\\\\.\\root\\WMI")

class CompositeClass
{
    [key] string aKey;
    object EmbObj;       // Weakly typed
};

class EmbClass

{
  [key] string aKey;
};

instance of CompositeClass
{
    aKey = "CompositeClass Key";
    EmbObj =
        instance of EmbClass
        {
           aKey = "key for embedded object";
        };
};

For more information, see MOF Embedded Objects and MOF ref Data Type.


MOF ref Data Type

The MOF ref data type is used to describe an object path. The object path can be either a full path to a server and namespace, or a relative path to another object in the same namespace. Object paths can be used as properties or parameters to methods. The ref data type is commonly used to create an association between two classes. See Declaring an Association Class.

WMI implements object paths programmatically as strings. Using object paths and the ref data type reduces transport time and encoding if the object to which the path refers already exists entirely within the CIM repository.

MOF supports the concept of a weakly typed and strongly typed object path. Both data types map to the VT_BSTR Automation type. A weakly typed object path points to an object of an unspecified class and uses the REF data type with the OBJECT keyword. A strongly typed object points to an object of a specific class and uses REF with the class name.

class MyClass
{
    object ref RefToAnyClass;       // Weakly typed
    ClassX ref RefToClassX;         // Strongly typed
};

In the preceding example, RefToAnyClass validly can be set to point to any class or class instance, but RefToClassX can only be set to point to a ClassX class or instances of ClassX.

The following example creates two instances and an association object that has references to both instances.

#pragma namespace("\\\\.\\root")

instance of __Namespace
{
    Name = "WMI" ;
} ;

#pragma namespace("\\\\.\\root\\WMI")

Class A{
    [key] string aKey;
};

Class C{
    [key] string cKey;
};

// The following class creates an association
// between the "A" class and the "C" class
    [Association] Class B{
    [key] A ref aRef;
    [Key, Min(1)] C ref cRef;
};

instance of a
{
    aKey = "This is the key for the A class";
};

instance of c
{
    cKey = "This is the key for the c class";
};

If the item to be referenced is located within the same MOF file, an alias can be used to initialize the value. For more information, see Using Aliases.

Note When object references are also key properties, object references are distinguished by their string value instead of by their dereferenced value.


MOF String Data Types

The MOF language supports the following string data types.

Data type | Automation type | Description
Char16 | VT_I2 | Single 16-bit Unicode character in Universal Character Set–2 (UCS-2) format
String | VT_BSTR | Unicode character string

Single-character constants are surrounded by single quotes. Otherwise, the integer representation of the Unicode character value can be used directly.

char16  TestChar1 = '\x4133';
char16  Testchar2 = 'A';

Note that characters can be specified literally or with the \x escape sequence as in the American National Standards Institute (ANSI) C standard. Because the characters are Unicode, 16-bit values can also be specified.

Character strings are surrounded by double quotes. Note that single-character constants in ANSI C format are surrounded by double quotes.

Successive quoted strings are concatenated with one or more white spaces placed between them as delimiters. The following example illustrates how to represent a long character string using two character strings.

"This" "becomes a long string"

Embedded quotes require the use of an escape sequence beginning with a backslash.

"This is \"embedded quote example\" "

The following class and class instance declarations show how to initialize several string properties and a string parameter.

class  StringDataClass
{
    [key]  String    Dstring;
    DateTime         DTime;
    char16           CharVal1;
    char16           CharVal2;
    sint32 DiskMethod ([in, Id(0)] string Description = "Disk 1");
};

instance of StringDataClass
{
    Dstring = "this can go on for " " some time"
       " before we are done";
    DTime    = "19940107140332.000000-300";
    CharVal1 = '\x16';
    CharVal2 = '\x32';
};


MOF Void Data Type

The VOID data type is only used in the MOF syntax to indicate a method that has no return value.


Specifying Comments

The Managed Object Format (MOF) compiler supports two styles of comment using two different styles of delimiter.

Comment delimiter | Use
// | To mark the start of a comment
/* and */ | To mark the start and end of a comment respectively

As in the C and C++ programming languages, the // style must be used with single-line comments, but the /* and */ style can be used with either single-line or multiple-line comments.

The following code illustrates a comment using the first style.

int32 MyProp = 2; // This is a comment until the line ends.

The following code uses the second style.

int32 /* This is a comment. */ MyProp = 2;


Specifying Namespaces

Because Managed Object Format (MOF) files are compiled in the context of a namespace, it is necessary to identify the namespace where the classes and class instances defined in the MOF file will be placed. A namespace can be specified by using either the following preprocessor command or the -n switch on the MOF compiler command line. In either case, a full namespace path or a path that is relative to the current namespace must be specified. The name of a namespace cannot contain either a leading or a trailing underscore.

The following statements show how to specify the SMIR namespace using first a full path and then a relative path.

// Full path to the SMIR namespace
#pragma namespace("\\\\.\\root\\smir\\SMIR")

// Relative path to the SMIR namespace
#pragma namespace ("SMIR")


Pragma Preprocessor Commands

Pragma preprocessor commands simplify the process of compiling MOF files by controlling the way a MOF file will be compiled without the use of command-line switches.

Pragma commands are usually placed at the beginning of a MOF file. However, some pragma commands, such as the namespace command, can appear in the body of a MOF file.

The following code sample illustrates pragma commands syntax.

#Pragma [command]

The following table shows the available pragma commands.

Pragma command | Description
amendment (namespace) | The amendment pragma command directs the MOF compiler to separate a MOF file into language neutral and language specific versions.
autorecover | Adds this MOF file to the list of files compiled during repository recovery. The list of autorecover MOF files is stored in this registry key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WBEM\CIMOM\autorecover mofs
classflags (flags) | Controls the way classes are created or updated depending on the flag or flags specified.
deleteclass | Deletes an existing class and its instances from the repository.
Include (moffile) | Includes a file in the current MOF file.
instanceflags (flags) | Controls the way instances are created or updated depending on the flag or flags specified.
namespace (namespacepath) | Requests that the compiler load the MOF file into the namespace specified as namespacepath. If both the MOF compiler -N: namespace switch and the #pragma namespace are used, the #pragma namespace takes priority.

The following example shows pragma commands that tell the MOF compiler to place classes and instances in the Root\Cimv2 namespace and to compile the file in which the commands are included during repository recovery.

#pragma autorecover
#pragma namespace ("\\\\.\\root\\cimv2")


Amendment Pragma Command

The amendment pragma command directs the MOF compiler to separate a MOF file into language neutral and language specific versions. The language specific MOF file will move amended qualifiers to a namespace for a specific locale. You then need to compile the language specific and language neutral MOF files to store class information in the CIM repository.

For example, You could create the following MOF file that contains amended qualifiers.

#pragma amendment ("MS_409")

[Description("Localized version of MyClass for American English") : Amended, AMENDMENT, LOCALE(0x409)]

class myclass
{
    [DisplayName("User Name") : Amended,
    Description("The Name property contains the name of the user") :
    Amended, key]
     string Name;

    uint64 Value; // non-localized value field

      [DisplayName("Time Stamp") : Amended,
    Description("This property shows when the object was created") :
    Amended]
     uint64 Timestamp;
};

You can compile this MOF file with the following command.

mofcomp -MOF:LnMOF.mof -MFL:LsMOF.mfl Mastermof.mof

This command tells the MOF compiler to produce two MOF files from the original MOF file called MasterMOF.MOF. The MOF compiler produces a language neutral version of the MOF file, called lnMOF.mof, with all language specific items removed. A second, language specific, MOF file will be created called LsMOF.MOF that contains only items that need to be localized.

Note When you are splitting a MOF file with the -amendment compiler switch or the amendment pragma command, you must specify the -MOF and -MFL options or no output files will be generated. You must compile the two output files that the first compilation produced before any class information will be available to WMI.

See WMI Localization for more information about localization.


Autorecover Pragma Command

WMI checks the integrity of the CIM repository when the Windows Management Service is started. If the repository is damaged, WMI automatically rebuilds it and recompiles any MOF files listed in the autorecover key in the registry.

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WBEM\CIMOM\
autorecover mofs. The MOF files listed in this registry entry must reside on the local computer because autorecover Mofs cannot recover MOF files located on a remote machine.

You can make a MOF file autorecover by inserting an autorecover pragma command in the MOF file.

#pragma autorecover

Note You cannot specify the command-line switches that the MOF compiler will use when autorecover MOF files are compiled. Therefore, you should include pragma commands in your MOF file that make command-line switches unnecessary. For example, the following code demonstrates the command-line switches needed to specify a namespace when compiling a MOF file.

mofcomp -N:Root\Test mymof.mof

However, if the MOF file Mymof.mof is automatically recovered, its classes are not placed in the Root\Test namespace. To avoid this problem, you should specify the namespace using a pragma command in the MOF file.

#pragma namespace ("\\\\.\\Root\\test")


Classflags Pragma Command

The Classflags command controls the way classes are created or updated based on the flags you specify. The possible flags are as follows.

Flag | Description
createonly | Requests that the compiler not make any changes to existing classes. When this flag is used, the compilation terminates if a class specified in the MOF file already exists.
forceupdate | Forces updates of classes when conflicting child classes exist. For example, suppose a class qualifier is defined in a child class, and the base class tries to add the same qualifier. In forceupdate mode, this conflict is resolved by deleting the conflicting qualifier in the child class. If the child class has instances, the update fails.
safeupdate | Allows updates of classes even if there are child classes, as long as the change does not cause conflicts with child classes. For example, this flag allows adding a new property to the base class that was not previously mentioned in child classes. If the child classes have instances, the update fails.
updateonly | Requests that the compiler not create any new classes. When this flag is used, the compilation terminates if a class specified in the MOF file does not exist.

You can combine any of these flags that do not contradict each other. For example, you can combine the updateonly and the forceupdate flags with the following pragma command.

#pragma classflags ("updateonly", "forceupdate")

You should not combine flags that contradict each other. For example, It makes no sense to combine the updateonly and the createonly flags.


Deleteclass Pragma Command

The deleteclass command directs the compiler to delete an existing class from the repository, along with any instances of the class. The syntax of the command is as follows:

#pragma deleteclass("ClassName",<FailFlag>)

ClassName is the name of the class to be deleted from the current namespace.

FailFlag must be one of the following:

  • FAIL, which directs the MOF compiler to quit with an error message if the class does not already exist in the repository
  • NOFAIL, which directs the MOF compiler to continue whether or not the class already exists.


Instanceflags Pragma Command

The Instanceflags command controls the way instances are created or updated based on the flags you specify.

Flag | Description
createonly | Requests that the compiler not make any changes to existing instances. When this flag is used, the compilation terminates if an instance specified in the MOF file already exists.
updateonly | Requests that the compiler not create any new instances. When this flag is used, the compilation terminates if an instance specified in the MOF file does not exist.


Include Command

The include command includes the contents of one MOF file into another MOF file.

Note The syntax for this command is different than the other preprocessor commands because it does not have the #Pragma prefix. To use the include command use the syntax: #include ("Moffile.mof") where Moffile.MOF is the name of the MOF file you want to include.

The following example shows two MOF files. When you compile the first MOF file, the second MOF file MyMof2.MOF is automatically compiled in the location you place the include statement.

/*   Title: MyMof.Mof                           */
/*                                              */
/*   This MOF file demonstrates how to include  */
/*   a MOF file in another MOF file             */

#pragma namespace("\\\\.\\root")

#include ("mymof2.mof")

class myclass1
{
    [key] string Description;
};

instance of myclass1
{
    Description = "Description of myclass1";
};
/*   End of MyMof.Mof                           */

The following MOF file is included in the previous example.

/*   Title: MyMof2.Mof                               */
/*                                                   */
/*   This MOF is included when MyMof.MOF is compiled */

class myclass2
{
    [key] string Description;
};

instance of myclass2
{
    Description = "Description of myclass2";

};


Namespace Pragma Command

The Namespace command causes the MOF compiler to save classes and instances in the specified namespace. If you do not specify this command or the equivalent command-line switch, the MOF compiler uses the Root\Default namespace by default. The following example causes classes or instances to be placed in the Root\Test.

#pragma namespace ("\\\\.\\Root\\test")


WMI Query Language

The Windows Management Instrumentation (WMI) Query Language (WQL) is a subset of standard American National Standards Institute Structured Query Language (ANSI SQL) with minor semantic changes to support WMI. Unlike SQL, in this release WQL is a retrieval-only language. It cannot be used for operations involving the modification, insertion, or deletion of information. For a complete list of supported WQL keywords see SQL for WMI.

WQL supports three types of queries:

  • Data queries
  • Event queries
  • Schema queries

Data queries are used to retrieve instances of a class and data associations. For more information on associations, see Association Classes.

Consumers use event queries to register to receive notification of events. Event providers use event queries to register to support one or more events.

Schema queries are used to retrieve class definitions and schema associations. Class providers use schema queries to specify the classes that they support when they register. Schema queries are placed in the ResultSetQueries, ReferencedSetQueries, and/or UnsupportedQueries properties of the class provider's instance of the __ClassProviderRegistration class. Schema queries return class definitions rather than instances of classes.

All queries use the WHERE clause for extension and customization. The WHERE clause is made up of a property or keyword, an operator, and a constant. All WHERE clauses must specify one of the predefined operators that are included in WQL. For detailed information on WHERE clause syntax, see WHERE Clause. For information about valid WQL operators, see WQL Operators.

Note WQL does not support cross-namespace queries or associations. You cannot query for all instances of a specified class residing in all the namespaces on the target computer. Furthermore, you cannot associate two objects across a namespace boundary and retrieve or query for the associations.

To view the Backus-Naur Form definition for WQL, see BNF Syntax for Structured Query Language Version 1 (SQL1)


SQL for WMI

[This is preliminary documentation and subject to change.]

The Windows Management Instrumentation (WMI) Query Language (WQL) is a subset of standard American National Standards Institute Structured Query Language (ANSI SQL) with minor semantic changes. The following table lists the supported WMI WQL keywords and describes their use.

WQL Key word | Meaning
AND | Combines two Boolean expressions and returns TRUE when both of the expressions are TRUE.
ASSOCIATORS OF | Retrieves all instances that are associated with a source instance. Use this statement with schema queries and data queries.
BY | Indicates which properties to use when grouping. Use this clause with the GROUP clause.
FROM | Specifies the classes that contain the properties listed in a SELECT statement.
GROUP | Causes WMI to generate a single notification to represent a group of events. Use this clause with event queries.
HAVING | Filters the events that are received during the grouping interval specified in the WITHIN clause
IS | Comparison operator used with NOT and NULL. The syntax for this statement is IS [NOT] NULL where NOT is optional.
ISA | Requests notification of events for all classes within a class hierarchy rather than a specific event class when the ISA operator is included with the WHERE clause of an event query.
NOT | Comparison operator used with NULL.
NULL | Indicates that an object has no explicitly assigned value. NULL is not equivalent to zero or blank.
OR | Combines two conditions. When more than one logical operator is used in a statement, OR operators are evaluated after AND operators.
REFERENCES OF | Retrieves all association instances that refer to a particular source instance. Use this statement with schema and data queries. The REFERENCES OF statement is similar to the ASSOCIATORS OF statement. However, rather than retrieving endpoint instances, it retrieves the intervening association instances.
SELECT | Specifies the properties that will be used in a query. See SELECT Statement for Data Queries SELECT Statement for Event Queries SELECT Statement for Schema Queries
TRUE | Boolean operator that evaluates to -1.
WHERE | Narrows the scope of a data, event, or schema query.
WITHIN | Specifies either a polling interval or a grouping interval. Use this clause with event queries.
FALSE | Boolean operator that evaluates to 0.

See also: BNF Syntax for Managed Object Format (MOF)


WHERE Clause

Use the WHERE clause to narrow the scope of a data, event, or schema query. The WHERE clause is made up of a property or keyword, an operator, and a constant. All WHERE clauses must specify one of the predefined operators that are included in the Windows Management Instrumentation (WMI) Query Language (WQL). You can append the WHERE clause to the SELECT statement using one of the following forms:

SELECT * FROM class WHERE property operator constant

or

SELECT * FROM class WHERE constant operator property

where * is the item queried about, class is the class in which to query, and constant, operator, and property are the constant, operator, and property or keyword to use. For information on the SELECT statement, see SELECT Statement for Data Queries, SELECT Statement for Event Queries, or SELECT Statement for Schema Queries.

The value of the constant must be of the correct type for the property. Moreover, the operator must be among the list of valid WQL operators. Either a property name or a constant must appear on either side of the operator in the WHERE clause. Arbitrary arithmetic expressions cannot be used. For example, the following query returns only instances of the Win32_LogicalDisk class that represent NTFS drives:

SELECT * FROM Win32_LogicalDisk WHERE FileSystem = "NTFS"

Property names cannot appear on both sides of the operator. The following query is an example of an invalid query:

SELECT * FROM PhysicalDisk WHERE Partitions < (4 + 7 - 2)
    OR   (Partitions = SectorsPerTrack / 7)

For most uses of class descriptors in a WHERE clause, WMI flags the query as invalid and returns an error. However, you can use the dot (.) operator for properties of type object in WMI. For example, the following query is valid if Prop is a valid property of MyClass and is type object:

SELECT * from MyClass where Prop.embedprop = 5

Comparison tests are always case-insensitive. That is, the following three statements all evaluate to TRUE:

SELECT * FROM MyClass WHERE Prop1 = "cat"
SELECT * FROM MyClass WHERE Prop1 = "CAT"
SELECT * FROM MyClass WHERE Prop1 = "cAt"

You can construct a query that includes Boolean data types, but the only valid Boolean operand types are the = and != types. The value TRUE is equivalent to the number 1, and the value FALSE is equivalent to the number 0. The following examples are of queries that compare a Boolean value against the values TRUE or FALSE.

SELECT * from MyClass WHERE BoolProp = 1
select * FROM MyClass WHERE BoolProp = TRUE
SELECT * FROM MyClass WHERE BoolProp = 0
SELECT * FROM MyClass WHERE BoolProp = FALSE
SELECT * FROM MyClass WHERE BoolProp != 1
SELECT * FROM MyClass WHERE BoolProp != FALSE

The following examples are of invalid queries that attempt to use invalid operands.

SELECT * FROM MyClass WHERE BoolProp <= TRUE
SELECT * FROM MyClass WHERE BoolProp >= 0
SELECT * FROM MyClass WHERE BoolProp > FALSE
SELECT * FROM win32_computersystem WHERE infraredsupported >= null

Multiple groups of properties, operators, and constants can be combined in a WHERE clause using logical operators and parenthetical subexpressions. Each group must be joined with the AND, OR, or NOT operators as is shown in the following queries. The first query retrieves all instances of the Win32_LogicalDisk class with the Name property set to either C or D:

SELECT * FROM Win32_LogicalDisk WHERE Name = "C:" OR Name = "D:"

The second query retrieves disks named "C:" or "D:" only if they have a certain amount of free space remaining and have NTFS file systems:

SELECT * FROM Win32_LogicalDisk WHERE (Name = "C:" OR Name = "D:")
    AND  FreeSpace > 2000000  AND   FileSystem = "NTFS"

This example demonstrates a schema query using the WHERE clause.

Select * from meta_class where __this isa "myClassName"

The class meta_class identifies this as a schema query, the property called __this identifies the target class of the query and the ISA operator requests definitions for the subclasses of the target class. Therefore, the preceding query returns the definition for the "myClassName" class and definitions for all of its subclasses.

The following example is a data query using the ASSOCIATORS OF statement with WHERE:

Associators of {myClass.keyVal="Value1"} WHERE ClassDefsOnly

The next example demonstrates a schema query using ASSOCIATORS OF and WHERE:

Associators of {myClass} WHERE SchemaOnly

The following example is a data query using the REFERENCES OF statement and WHERE:

References of {myClass.keyVal="Value1"} WHERE RequiredQualifier = "myQual"

This last example is a schema query using REFERENCES OF and WHERE:

References of {myClass} WHERE SchemaOnly


WQL Operators

The Windows Management Instrumentation (WMI) Query Language (WQL) supports a set of standard operators that are used in the WHERE clause of a SELECT statement, as follows.

Operator | Description
= | Equal to
< | Less than
> | Greater than
<= | Less than or equal to
>= | Greater than or equal to
!= or <> | Not equal to

There are a few additional WQL-specific operators: IS, IS NOT, and ISA. The IS and IS NOT operators are valid in the WHERE clause only if the constant is NULL. For example, the following queries are valid:

SELECT * FROM Win32_LogicalDisk WHERE FileSystem IS NULL
SELECT * FROM Win32_LogicalDisk WHERE FileSystem IS NOT NULL

The following queries show invalid uses of IS and IS NOT:

SELECT * FROM Win32_LogicalDisk WHERE DriveType IS 5
SELECT * FROM Win32_LogicalDisk WHERE FileSystem IS NOT "NTFS"

The ISA operator is used in the WHERE clause of data and event queries to test embedded objects for a class hierarchy. The ISA operator eliminates the need for keeping track of new derived classes when requesting a hierarchy of classes. When you use ISA, newly created and existing subclasses of the requested class are automatically included in the result set. For more information about the syntax and use of this operator, see the following topics:

  • ISA Operator for Data Queries
  • ISA Operator for Event Queries


Data Queries

Data queries are Windows Management Instrumentation (WMI) Query Language (WQL) statements that request instances of classes. To issue a data query, applications call the IWbemServices::ExecQuery or IWbemServices::ExecQueryAsync method.

There are three statements that are used to make data queries:

  • SELECT
  • ASSOCIATORS OF
  • REFERENCES OF

The WQL SELECT statement is the standard Structured Query Language (SQL) statement for retrieving information, with a few restrictions and extensions specific to WQL. Although the SQL SELECT statement is typically used in the database environment to retrieve particular columns from tables, the WQL SELECT statement is used in WMI to retrieve instances of a single class. WQL does not support queries across multiple classes.

The ASSOCIATORS OF and REFERENCES OF statements are specific to WQL and not part of standard SQL. ASSOCIATORS OF retrieves all class instances that are associated with a particular source class instance, and REFERENCES OF retrieves all instances that refer to a particular source instance. Associations are represented by instances of an association class. For a complete description of the ASSOCIATORS OF and REFERENCES OF statements, see ASSOCIATORS OF Statement and REFERENCES OF Statement.


SELECT Statement for Data Queries

The most basic SELECT statement for a data query uses the following syntax:

SELECT * FROM class

where class is the class about which to query. This statement returns instances of the specified class and any of its subclasses. All of the system and user-defined properties for the classes are included. If a system property is not relevant for a particular query, it contains NULL.

You can use several techniques to reduce the bandwidth required to retrieve the result set, if the execution of the query results in too much overhead and the user is only interested in a subset of the properties. First, queries can replace the asterisk with the desired properties:

SELECT property_1, property_2, property_3 FROM class

The result set includes all system properties and the specified nonsystem properties.

Another technique for narrowing the scope of a query's result set is to use the __CLASS system property. Queries by default return all instances of the specified class and its subclasses. You can use the __CLASS system property to request only instances of the specified class, excluding its subclasses. Use the __CLASS system property in a WHERE clause as follows:

SELECT * FROM Device WHERE __CLASS = "Device"

You can also use the __CLASS system property to restrict the result set to instances of particular subclasses:

SELECT * FROM Device WHERE __CLASS = "Modem" OR __CLASS = "Keyboard"

Note If you construct a query with an invalid path for an embedded object, your query does not return an error or any results.

The following query returns an instance of MainClass, assuming that an instance of MainClass exists containing the embedded object EmbedObj with a property called "P_Uint32" that is equal to "70011":

SELECT * FROM MainClass WHERE EmbedObj.P_Uint32 = 70011

The next query returns no results and does not return an error, assuming that the embedded object EmbedObj in the instance of MainClass does not have a property called "INVALID ":

SELECT * FROM MainClass WHERE StrongEmbedObj.INVALID = 70011


ISA Operator for Data Queries

Use the ISA operator in the WHERE clause of a data query to request embedded objects in a class hierarchy. The syntax is as follows:

SELECT * FROM Class WHERE EmbeddedProp ISA "SuperClass"

The result includes instances of Class having embedded objects derived from SuperClass in the EmbeddedProp property. The instances of Class do not need to be derived from SuperClass, but the embedded objects should be.

For example, in the query following, ClassA includes the weakly typed property EmbeddedObj. ClassA has ten instances. Five of those instances have embedded objects with a type derived from ClassZ. The other five have embedded objects of other types. The following query returns the five instances that include the objects derived from ClassZ:

SELECT * FROM ClassA WHERE EmbeddedObj ISA "ClassZ"


ASSOCIATORS OF Statement

[This is preliminary documentation and subject to change.]

The ASSOCIATORS OF statement retrieves all instances that are associated with a particular source instance. The instances that are retrieved are referred to as the endpoints. Each endpoint is returned as many times as there are associations between it and the source object. For example, assume there are instances A, B, X, and Y. Two association instances exist, one that links A and X and the other that links B and Y. The following query returns the single endpoint X:

ASSOCIATORS OF {A}

However, if there is another association linking A and X, the above query returns two X endpoints.

The basic syntax for the ASSOCIATORS OF statement is:

ASSOCIATORS OF {ObjectPath}

Note that the braces are part of the syntax. Any valid object path can be used for ObjectPath. The tokens within the object path cannot contain any white space. For example, the query in the following table returns instances that are associated with the specified logical disk:

Query:
Associators Of {Win32_LogicalDisk.DeviceID="C:"}
Results:
Win32_Directory.Name="C:\\"

Win32_ComputerSystem.Name="mycomputer"

As with the SELECT statement, an ASSOCIATORS OF statement can include a WHERE clause, but the WHERE clause for an ASSOCIATORS OF statement is very different from the SELECT statement WHERE clause.

The WHERE clause of the ASSOCIATORS OF statement can include one or more of the following predefined keywords and their values:

ASSOCIATORS OF {ObjectPath} WHERE
    AssocClass = AssocClassName
    ClassDefsOnly
    RequiredAssocQualifier = QualifierName
    RequiredQualifier = QualifierName
    ResultClass = ClassName
    ResultRole = PropertyName
    Role = PropertyName

Note that the optional subclauses are not separated by commas.

The AssocClass keyword indicates that the returned endpoints must be associated with the source through the specified class or one of its derived classes. For example, the query in the following table returns only endpoints that are associated with the source through the Win32_SystemDevices association class or any of its derived classes:

Query:
Associators Of {Win32_LogicalDisk.DeviceID="C:"}
   Where AssocClass = Win32_SystemDevices
Results:
Win32_ComputerSystem.Name="mycomputer"

The ClassDefsOnly keyword indicates that the clause returns a result set of class definition objects rather than actual instances of the classes. These objects are the definitions of classes to which the endpoint instances belong. For example, the query in the following table returns definitions for the Win32_Directory and Win32_ComputerSystem classes:

Query:
Associators Of {Win32_LogicalDisk.DeviceID="C:"}
   Where ClassDefOnly
Results:
Win32_Directory

Win32_ComputerSystem

The RequiredAssocQualifier keyword indicates that the returned endpoints must be associated with the source object through an association class that includes the specified qualifier. This type of filtering is used to eliminate broad ranges of endpoints unless the endpoints are associated with the target through a particular set of tagged association classes. For example, the query in the following table returns endpoint instances if the association class includes a qualifier called Association:

Query:
Associators Of {Win32_LogicalDisk.DeviceID="C:"}
   Where RequiredAssocQualifier = Association
Results:
Win32_Directory.Name="C:\\"

Win32_ComputerSystem.Name="mycomputer"

The RequiredQualifier keyword indicates that the returned endpoints associated with the source object must include the specified qualifier. The RequiredQualifier keyword can be used to include particular types of instances in the result set. For example, the query in the following table returns endpoint instances that include a qualifier called Locale:

Query:
Associators Of {Win32_LogicalDisk.DeviceID="C:"}
   Where RequiredQualifier = Locale
Results:
Win32_Directory.Name="C:\\"

Win32_ComputerSystem.Name="mycomputer"

The ResultClass keyword indicates that the returned endpoints associated with the source object must belong to or be derived from the specified class. For example, the query in the following table returns endpoint instances that are derived from the CIM_Directory class:

Query:
Associators Of {Win32_LogicalDisk.DeviceID="C:"}
   Where ResultClass = Cim_Directory
Results:
Win32_Directory.Name="C:\\"

The ResultRole keyword indicates that the returned endpoints must play a particular role in their association with the source object. The role is defined by the specified property, a reference property of type ref. For example, the ResultRole keyword can be used to retrieve all endpoints that have the GroupComponent property in their association with a source object, as the following query illustrates:

Query:
Associators Of {Win32_LogicalDisk.DeviceID="C:"}
   Where ResultRole = GroupComponent
Results:
Win32_ComputerSystem.Name="mycomputer"

The Role keyword indicates that the returned endpoints participate in an association with the source object where the source object plays a particular role. The role is defined by the specified property, a reference property of type ref. For example, the Role keyword can be used to retrieve all endpoints associated with a source object that have the GroupComponent property, as the following query illustrates:

Query:
Associators Of {Win32_LogicalDisk.DeviceID="C:"}
   Where Role = GroupComponent
Results:
Win32_Directory.Name="C:\\"


REFERENCES OF Statement

The REFERENCES OF statement retrieves all association instances that refer to a particular source instance. The REFERENCES OF statement is similar to the ASSOCIATORS OF statement in its syntax. However, rather than retrieving endpoint instances, it retrieves the intervening association instances.

The REFERENCES OF WHERE clause can include one or more of the following predefined keywords and their values:

REFERENCES OF {SourceObject} WHERE
    ClassDefsOnly
    RequiredQualifier = QualifierName
    ResultClass = ClassName
    Role = PropertyName

To specify a source object, use any valid object path for SourceObject. As with the SELECT statement, the WHERE clause is optional and is used to further define the query. That is, the following statement is perfectly valid:

REFERENCES OF {Adapter="AHA-294X"}

The ClassDefsOnly keyword indicates that the statement returns a result set of class definition objects rather than actual instances of the association classes. These objects contain definitions of classes to which the instances that reference the source object belong. For example, the following statement returns definitions for the AdapterDriver and AdapterProtocol classes:

REFERENCES OF {Adapter="AHA-294X"} WHERE ClassDefsOnly

The RequiredQualifier keyword indicates that the returned association objects must include the specified qualifier. The RequiredQualifier keyword can be used to include particular instances of associations in the result set. For example, the following statement returns association instances that include a qualifier called AdapterTag:

REFERENCES OF {Adapter="AHA-294X"}
  WHERE RequiredQualifier = AdapterTag

The ResultClass keyword indicates that the returned association objects must belong to or be derived from the specified class. For example, the following statement returns associations of the AdapterDriver class or subclasses of AdapterDriver:

REFERENCES OF {Adapter="AHA-294X"} WHERE ResultClass = AdapterDriver

The Role keyword indicates that the returned associations are only those in which the source object plays a particular role. The role is defined by the specified property, a reference property of type ref. The Role keyword is useful in associations where a certain object can play one role in some cases and another role in others, such as in hierarchical associations. The Role keyword can be used to retrieve all of the associations in which the source object plays the role of parent, for example. The following statement illustrates the syntax for retrieving associations that have a parent property referencing the source object as the parent:

REFERENCES OF {Adapter="AHA-294X"} WHERE Role = parent


Event Queries

Event queries are used by temporary event consumers, permanent event consumers, and event providers. Event consumers use event queries to specify the events they are interested in, and event providers use them to specify the events they provide.

Temporary consumers place their queries in calls to the IWbemServices::ExecNotificationQuery or IWbemServices::ExecNotificationQueryAsync method. Permanent event consumers place their queries in the Query property of an instance of the __EventFilter system class.

Event providers use event queries to register to support one or more types of events. They place their queries in the EventQueryList property of an instance of the __EventProviderRegistration system class. All event providers create an __EventProviderRegistration instance to register with Windows Management Instrumentation (WMI). For information about registering event providers, see Registering an Event Provider.

Event consumers and providers use the SELECT statement and a related WHERE clause for event queries, plus a variety of extensions specific to the WMI Query Language (WQL). The extensions are used to protect consumers from being flooded with notifications that occur too frequently to be useful. Consumers that do not require notification each time an event occurs can specify the following clauses in their queries:

  • WITHIN clause
  • GROUP clause
  • HAVING clause

The WITHIN and HAVING clauses affect the timing of events, and the GROUP clause causes a representative event to be sent in place of a frequently occurring event.


SELECT Statement for Event Queries

The most basic syntax of a SELECT statement for an event query is:

SELECT * FROM EventClass

When a consumer submits the query, it is a request to be notified of all occurrences of the event represented by EventClass. This request includes a request for notification on all of the event's system and nonsystem properties. When an event provider submits the query, it registers support for generating notifications whenever an event represented by EventClass occurs.

Consumers can specify individual properties instead of the asterisk (*) in the SELECT statement, but individual properties are ignored by WMI. That is, the following two queries result in the same registration:

SELECT property_1, property_2, property_3 FROM MyEventClass

SELECT * FROM MyEventClass

If a system property is not relevant for a particular query, it contains NULL. For example, the value of the __RELPATH system property is NULL for all event queries. For more information about system properties, see WMI System Property Reference.

Although all event queries can include an optional WHERE clause, WHERE clauses are primarily used by consumers to specify additional filtering. It is strongly recommended that consumers always specify a WHERE clause. The cost of a complex query is minimal compared to the cost of delivering and processing unneeded notifications. For example, this query requests notifications of all instance modification events affecting the hypothetical class EmailEvent:

SELECT * FROM EmailEvent

If events associated with EmailEvent occur frequently, the consumer is flooded with events. A better query requests these events only under certain conditions using properties of the class specified, such as when the importance level is high. For example, assuming that EmailImportance is a property of the class EmailEvent, you can write the query as:

SELECT * FROM EmailEvent WHERE EmailImportance > 3

Note that WMI can reject a query for a number of reasons. For example, the query can be too complex or resource-intensive for evaluation. When this occurs, WMI returns specific error codes, such as WBEM_E_INVALID_QUERY.

Properties of embedded objects can be used in the WHERE clause. In the example following, the TargetInstance property of the __InstanceModificationEvent system class is an embedded Win32_LogicalDisk object and FreeSpace is a property of Win32_LogicalDisk:

SELECT * FROM __InstanceModificationEvent WITHIN 600
    WHERE TargetInstance ISA "Win32_LogicalDisk"
    AND   TargetInstance.FreeSpace < 1000000


ISA Operator for Event Queries

The ISA operator is a Windows Management Instrumentation Query Language (WQL)-specific operator that can be used in event queries. When ISA is included in the WHERE clause of an event query, it requests notification of events for all classes within a class hierarchy rather than a specific event class. For example, the following statement requests notification every 10 minutes of instance modification events for all instances that are members of any class deriving from the Win32_LogicalDisk class:

SELECT * FROM __InstanceModificationEvent WITHIN 600
WHERE TargetInstance ISA "Win32_LogicalDisk"


WITHIN Clause

Consumers use the WITHIN clause in their event queries to specify two time:

  • A polling interval
  • A grouping interval

A polling interval is the interval that WMI uses to poll the data provider responsible for the class for intrinsic events of which the event queried is a member. This interval is the maximum amount of time that can pass before notification of an event must be delivered. A consumer uses a polling interval in a WITHIN clause when the consumer requires notifications of changes to a class and an event provider is unavailable. The consumer registers for an intrinsic event and includes the polling interval.

To specify a polling interval, place the WITHIN clause immediately before the WHERE clause, as shown following:

SELECT * FROM IntrinsicEventClass WITHIN interval
  WHERE property = value

where IntrinsicEventClass is the intrinsic event class of which the event is a member, interval is the polling interval, and value is the value for the property property on which the consumer requires notification.

The polling interval is a floating-point number and can be fractional to deal with values smaller than 1 second. However, the interval should represent a number of seconds rather than an extremely small value such as 0.001, because specifying too small a value can cause WMI to reject the statement as invalid due to the resource-intensive nature of polling. Because most consumers do not require immediate notification, it is recommended they use an interval greater than 5 minutes.

For example, the following query requests that WMI check every 10 seconds for changes that occur to instances of the Win32_LogicalDisk class. If an instance of the class has been modified within the specified polling interval, a notification event is sent for each modification.

SELECT * FROM __InstanceModificationEvent WITHIN 10
    WHERE TargetInstance ISA "Win32_LogicalDisk"

Depending on the query, an event provider and WMI can share the job of providing events. For example, consider an event provider that supports events of the __InstanceCreationEvent and __InstanceModificationEvent system classes and not events of the __InstanceDeletionEvent system class. The following query enables the event provider to generate the creation and modification events as they occur and have them delivered when they are created. The query also allows WMI to generate __InstanceDeletionEvent events every 10 seconds using the polling mechanism:

SELECT * FROM __InstanceOperationEvent WITHIN 10
    WHERE TargetInstance ISA "MyOwnClass"

The other use of the WITHIN clause is to specify a grouping interval. A grouping interval is an unsigned 32-bit integer that specifies the time period, after receiving an initial event, during which WMI should collect similar events. When this time period expires, WMI delivers the aggregate event, made up of all the similar events. For more information about grouping and aggregate events, see GROUP Clause.

Consumers that register for frequently occurring events use a grouping interval with the WITHIN clause. Adding GROUP WITHIN to the WHERE clause in an event query results in WMI sending one aggregate event rather than many events. The aggregate event is represented by the __AggregateEvent system class.

To specify a grouping interval, place the WITHIN clause immediately after the GROUP clause:

SELECT * FROM EventClass WHERE property = value GROUP WITHIN Interval

where EventClass is the event class of which the event is a member, value is the value for the property property on which the consumer requires notification, and Interval is the grouping interval.

For more information on intrinsic events and polling, see Intrinsic and Extrinsic Events.


GROUP Clause

The GROUP clause causes WMI to generate a single notification to represent a group of events. The representative notification is an instance of the __AggregateEvent system class. The __AggregateEvent system class contains two properties: Representative and NumberOfEvents. The Representative property is an embedded object that contains one of the instances received during the grouping interval specified in the WITHIN clause. For example, if an aggregate event is generated to notify of instance modification events, Representative contains one instance of the __InstanceModificationEvent class. The NumberOfEvents property contains the number of events received during the grouping interval. The grouping interval specifies the time period, after receiving an initial event, during which WMI should collect similar events.

The GROUP clause must contain a WITHIN clause to specify the grouping interval and can contain the BY or HAVING keyword, or both. The GROUP clause is placed after the WHERE clause, as shown following:

SELECT * FROM EventClass [WHERE property = value]
    GROUP WITHIN interval [BY property_list]
    [HAVING NumberOfEvents operator integer]

In the preceding, EventClass is the event class of which the event is a member, and value is the value for the property property on which notification is required. The interval is an unsigned integer that represents the grouping interval after receiving the first event. The unsigned integer is a number of seconds. The property_list is a comma-delimited list of one or more properties that are included in the event class. The operator is any relational operator. The integer is an unsigned 32-bit integer indicating a number of events.

When using the GROUP clause, the WHERE, BY, and HAVING clauses are optional.

A basic use of the GROUP clause might request a grouping of events within a time interval that starts when the first event is received. For example, the following query groups all of the e-mail events sent within 5 minutes. Instead of paging a user every time a piece of new e-mail is received, the permanent consumer might use this query to inform the user only if new e-mail has been received within the last 5 minutes.

SELECT * FROM EmailEvent GROUP WITHIN 300

If more detailed information is required, events can be grouped by one or more properties of the event class. The following query requests that e-mail events be combined with other events that have the same value in the Sender property:

SELECT * FROM EmailEvent GROUP WITHIN 300 BY Sender

A still greater level of detail can be achieved by adding a WHERE clause. For example, the following query notifies a user of new e-mail from a particular sender that has arrived within the last 10 minutes, combined with other events that have the same value in the Importance property:

SELECT * FROM EventClass WHERE Sender = "MyBoss"
  GROUP WITHIN 300 BY Importance


HAVING Clause

The HAVING clause is used to filter the events that are received during the grouping interval specified in the WITHIN clause. The WITHIN clause follows immediately in the SELECT statement after the GROUP clause. The HAVING clause operates on the NumberOfEvents property of the __AggregateEvent system class, of which the group created by the GROUP clause is a member. The HAVING clause can use all of the standard relational operators.

The syntax is as follows:

SELECT * FROM EventClass [WHERE property = value]
  GROUP WITHIN interval [BY property_list]
  HAVING NumberOfEvents operator constant

EventClass is the event class of which the event is a member, and value is the value for the property property on which notification is required. The interval is an unsigned integer that represents the grouping interval after receiving the first event. The unsigned integer is a number of seconds. The property_list is a comma-delimited list of one or more properties that are included in the event class. The operator is any relational operator. The constant value is any unsigned 32-bit integer indicating the number of events used for filtering.

When using the HAVING clause, the WHERE and BY clauses are optional.

The following event query requests that notifications of the EmailEvent class be grouped into one event 300 seconds after the first event that WMI receives. Also, the query requests the __AggregateEvent instance should be delivered only if WMI receives more than five e-mail events in that 300 seconds.

SELECT * FROM EmailEvent GROUP WITHIN 300 HAVING NumberOfEvents > 5

The following example groups all events received in 600 seconds (that is, 10 minutes) by the TargetInstance.SourceName property. In this example, aggregate events are delivered only if the number of Win32_NTLogEvent events received from the same source exceeds 25. Keep in mind that the ISA operator causes the TargetInstance property of the __InstanceCreationEvent system class to represent an instance of the Win32_NTLogEvent class.

SELECT * FROM __InstanceCreationEvent
  WHERE TargetInstance ISA "Win32_NTLogEvent"
  GROUP WITHIN 600 BY TargetInstance.SourceName
  HAVING NumberOfEvents > 25

For more information on TargetInstance.SourceName, see Using the Event Log Provider as an Event Provider.


Schema Queries

Schema queries are Windows Management Instrumentation (WMI) Query Language (WQL) statements that request class definitions and information about schema associations. Class providers use schema queries in their instances of the __ClassProviderRegistration class to specify the classes that they support when they register with WMI.

Schema queries are similar to data queries in that they support the following three WQL statements:

  • SELECT
  • ASSOCIATORS OF
  • REFERENCES OF

A schema query is similar to a REFERENCES OF data query that specifies the ClassDefsOnly keyword, in other words that returns a result set of class definition objects rather than actual instances of association classes. However, REFERENCES OF returns class definitions only if there are instances present. A schema query returns class definitions whether or not instances are present.


SELECT Statement for Schema Queries

Schema data queries use the SELECT statement with a syntax similar to that for data queries:

SELECT * FROM meta_class

The difference is the use of a special class called meta_class, which identifies the query as a schema query. The example preceding requests all class definitions that are within the current namespace. To narrow the scope of the definitions returned, a provider can add a WHERE clause that specifies a particular class as follows:

SELECT * FROM meta_class WHERE __this ISA "Win32_LogicalDisk"

The special property called __this identifies the target class for a schema query. Note that the ISA operator must be used with the __this property to request definitions for the subclasses of the target class. The preceding query returns the definition for the Win32_LogicalDisk class and definitions for all of its subclasses.

To request a class definition for a single class, use the __Class system property as follows:

SELECT * FROM meta_class WHERE __Class = "Win32_LogicalDisk"

This query is equivalent to calling the IWbemServices::GetObject or IWbemServices::GetObjectAsync method with the object path parameter set to "Win32_LogicalDisk".


Schema Associations

Schema association queries use the same statements as are used in data association queries: ASSOCIATORS OF and REFERENCES OF. However, with data association queries, class instances are returned, and with schema association queries, names of classes that can participate in association relationships are returned. For example, you can use a schema query to find all of the association classes defined in the schema that reference a source class.

The syntax for the ASSOCIATORS OF and REFERENCES OF statements is the same for schema association queries as it is for data association queries with three exceptions:

  • The source object is a class rather than an instance.
  • There is an additional keyword, SchemaOnly, which identifies the query as applying to a schema rather than to data.
  • The ClassDefsOnly keyword is not valid.

The complete syntax of the ASSOCIATORS OF statement for a schema query is:

ASSOCIATORS OF {SourceClass} WHERE
    AssocClass = AssocClassName
    RequiredAssocQualifier = QualifierName
    RequiredQualifier = QualifierName
    ResultClass = ClassName
    ResultRole = PropertyName
    Role = PropertyName
    SchemaOnly

For detailed syntax on ASSOCIATORS OF, see ASSOCIATORS OF Statement.

For example, the following query returns the Protocol and Driver classes, the two classes that refer to the source class:

ASSOCIATORS OF {Adapter} WHERE SchemaOnly

This next query returns only the Driver class because of the restriction placed by the AssocClass keyword:

ASSOCIATORS OF {Adapter} WHERE AssocClass = AdapterDriver SchemaOnly

The complete syntax of the REFERENCES OF statement for a schema query is:

REFERENCES OF {SourceClass} WHERE
    ResultClass = ClassName
    Role = PropertyName
    RequiredQualifier = QualifierName
    SchemaOnly

For detailed syntax on REFERENCES OF, see REFERENCES OF Statement.

Note Schema association queries may return duplicate objects. For example, the following query will return the class CIM_ComputerSystem several times when enumerating classes in the cimv2 namespace.

ASSOCIATORS OF {Win32_ComputerSystem} WHERE SchemaOnly


Programmatic Access

The easiest way to create classes, instances, properties, and methods is by using the Managed Object Format (MOF) Language compiler. However, it is possible to create and manipulate all of these programmatically by using the Windows Management Instrumentation (WMI) COM API.

  • Programmatic Access to Methods

    It is also possible to set namespace security programmatically.

  • Programmatic Access to Per Namespace Security


Programmatic Access to Methods

You can create, execute, and reconstruct methods programmatically.

  • Creating a Method Programmatically
  • Executing a Method Programmatically
  • Reconstructing a Method Definition Programmatically


Creating a Method Programmatically

To create a method on a class, first a new class itself must be created.

Whenever you work with CIM class methods, remember that parameters are nothing more than properties on a normal IWbemClassObject instance. All rules and observations that apply to normal instances also apply to objects acting as parameters to methods. The only special case is that the class of such objects is always __PARAMETERS.

To create a CIM class method programmatically, you must retrieve the system class, __PARAMETERS, by using IWbemServices::GetObject or IWbemServices::GetObjectAsync. Two copies of the class are required, one for the in-parameters and one for the out-parameters. You can make a single retrieval followed by an IWbemClassObject::Clone call.

After the properties that represent the parameters are written into the objects, write the objects into the class definition object by using IWbemClassObject::PutMethod, which accepts both the in-parameters class and the out-parameters class.

Note Remember that you will have to use programmatic access to manually perform some of the tasks that the MOF compiler performs automatically.

  • Treat the [in,out] parameters as separate entries, one in the object containing the in-parameters and one in the object containing the out-parameters.

    Also, remember that other than the [in,out] qualifiers, the remaining qualifiers must be exactly the same.

  • Specify the id qualifiers, starting at zero, one for each property (parameter); make sure that there are no gaps in the id qualifier sequence.
  • Place the return value in the out-parameters class as a property tagged with a Boolean qualifier RetVal.

    This marks a specific parameter as the return value of the method. If the method has a return type of void, then there are no properties in the out-parameters class with a RetVal qualifier. Make sure that return values are marked with the RetVal qualifier . Users cannot invent ad hoc qualifiers for designating return types.

  • If the parameters have default values, be sure to express them as default values for the property in the class.

    Note that in the class definition that contains methods:

  • There is one unique in-parameters class and one output-parameters class for each method.
  • These objects are considered classes and not instances, even though they all have the same class name, __PARAMETERS.


Executing a Method Programmatically

These are the steps for executing a CIM class method programmatically:

  1. You must first retrieve the class containing the definition by calling IWbemServices::GetObject.
  2. Retrieve the class definitions for the in-parameter list and the out-parameter list by using IWbemClassObject::GetMethod.
  3. Because in-parameter classes and out-parameter classes are both classes, the user must call IWbemClassObject::SpawnInstance on each class to prepare instances to actually contain the in- and out-parameters.

    Typically, the out-parameters class is not required for the client side of an invocation, because the out-parameters instance is constructed by the provider and sent back to the client. For similar reasons, when you construct a provider, the in-parameters class is usually not required. WMI will deliver a pre-constructed instance containing the in-parameters to the provider during method execution. The IWbemClassObject::GetMethod method allows the caller to only retrieve the in- or out-parameter objects individually and does not require the caller to retrieve both.

  4. After calling IWbemClassObject::SpawnInstance on the in-parameters class, the client then calls IWbemClassObject::Put to write the parameters (as if they were properties) into the in-parameters-instance. Note that if the parameters contain default values, these are automatically filled in at SpawnInstance time. If required, the user must override those particular values by using IWbemClassObject::Put.
  5. To actually execute the method, the client:
    • Takes the IN-Parameters-Instance;
    • Determines which object to execute the method against;
    • Constructs the path to the object;
    • Calls IWbemServices::ExecMethod or IWbemServices::ExecMethodAsync.

      The out-parameters to the call are supplied as return values to these functions.


Reconstructing a Method Definition Programmatically

To get the method definition, you must call IWbemClassObject::GetMethod on the class definition. The two out-parameters, ppInSignature and ppOutSignature, contain the in-parameters class and the out-parameters class, respectively. The return value is bundled into the out-parameters class as the only property that has a RetVal qualifier.


Programmatic Access to Per Namespace Security

Each namespace has its own security descriptor, which allows the namespace to have its own settings. The namespace security descriptor is wrapped in a singleton class, named __SystemSecurity:

Class __SystemSecurity
{
  UINT32 GetSD([out]UINT8 sd[]);  // Windows NT only
  UINT32 SetSD([in]UINT8 sd[]);   // Windows NT only
  UINT32 GetCallerAccessRights([out]sint32 rights);
  UINT32 Get9XuserList
    ([out] __ntlmuser9x users[]); // Windows 9X only
  UINT32 Set9XuserList
    ([in] __ntlmuser9x users[]);  // Windows 9X only

};

The GetCallerAccessRights method returns a mask with each bit corresponding to an access right.

Access Right | Bit mask | Description
WBEM_ENABLE | 0X1 | Enables the account.
WBEM_METHOD_EXECUTE | 0X2 | Allows the execution of methods. Note that providers may perform additional access checks.
WBEM_FULL_WRITE_REP | 0X4 | Allows many types of write operations to the repository, and to providers.
WBEM_PARTIAL_WRITE_REP | 0X8 | Allows writing of non-system instances to the repository.
WBEM_WRITE_PROVIDER | 0X10 | Allows writing classes and instance to providers. Note that impersonating providers may do additional access checks.
WBEM_REMOTE_ACCESS | 0X20 | Allows remote access.
WRITE_DAC | 0X40000 | Allows writing the DACL
READ_CONTROL | 0X20000 | Allows reading the SD

Any enabled client has the right to call GetCallerAccessRights , even if that client doesn't have general method execution rights.

For more information on per namespace security, see Per Namespace Security.

For more information on Windows security, see the "Security" topic in the Platform SDK documentation


Using DCOM Security from WMI

[This is preliminary documentation and subject to change.]

Windows Management Instrumentation (WMI) is implemented using the Distributed Component Object Model (DCOM). To use and write WMI applications, it is important to understand how to use the DCOM security settings. It is assumed that the reader is familiar with C++, Windows programming, WMI, and COM.

DCOM security settings fall into two categories: authentication and impersonation. Authentication is the means by which one process identifies itself to another. Impersonation indicates how much authority a client grants a server to call other processes on its behalf. For more information on authentication, see Authentication.

DCOM authentication levels range from no authentication to per-packet encrypted authentication. For more information on DCOM authentication levels, see the COM reference documentation in the Platform SDK.

DCOM impersonation levels range from no identification to full-blown delegation of authority. For more information on DCOM impersonation levels, see the COM reference documentation in the Platform SDK.

DCOM provides default security levels, which it reads from the system registry. Unfortunately, unless specifically modified, these registry settings set the impersonation level too low for WMI to function. The default impersonation level is typically RPC_C_IMP_LEVEL_IDENTIFY, while WMI needs at least RPC_C_IMP_LEVEL_IMPERSONATE to function with most providers. This impersonation level, or higher, must be explicitly set before calling into WMI.

Clients that are executables can set their impersonation level by calling CoInitializeSecurity. The following arguments work in most cases:

CoInitializeSecurity(
  NULL,         // security descriptor
  -1,           // use this simple setting
  NULL,         // use this simple setting
  NULL,         // reserved
  RPC_C_AUTHN_LEVEL_CONNECT,     // NT 4, NT 5 authentication level
  RPC_C_IMP_LEVEL_IMPERSONATE,   // impersonation level
  NULL,         // use this simple setting
  EOAC_NONE,    // no special capabilities
  0);           // reserved

Note When connecting to Windows 95/98 machines that are set for share-level security, the required authentication level is RPC_C_AUTHN_LEVEL_NONE.

You may choose instead to use InitializeSecurity, the WMI wrapper to this function. InitializeSecurity checks for the presence of DCOM. You must load DCOM explicitly on Windows 95/98 systems that don't have Microsoft® Internet Explorer installed. InitializeSecurity takes exactly the same arguments as CoInitializeSecurity.

Client software that runs as DLLs is generally not allowed to call CoIntializeSecurity, because this changes security settings for the entire executable. In this case, the client can set the impersonation level on individual interface pointers by calling CoSetProxyBlanket. It is important to note that you must set the impersonation level on every out-of-process pointer. For example, if you call pIWbemServices-> CreateInstanceEnum(… &pEnum), then you must also set the proxy blanket on the enumerator pointer pEnum, even if you have previously set it on the pIWbemServices pointer.

CoSetProxyBlanket(
  pEnum,
  RPC_C_AUTHN_WINNT,    // NTLM authentication service
  RPC_C_AUTHZ_NONE,     // default authorization service...
  NULL,                 // no mutual authentication
  RPC_C_AUTHN_LEVEL_CONNECT,      // authentication level
  RPC_C_IMP_LEVEL_IMPERSONATE,    // impersonation level
  NULL,                // use current token
  EOAC_NONE);          // no special capabilities

When connecting to WMI and performing operations, DCOM provides an application with what is known as a proxy. This proxy is used to perform various operations as if they were in-process to your application. Each proxy is assigned an identity that corresponds to either a current thread's impersonation token, a process token, or an identity explicitly assigned to the proxy. This identity is used for authentication purposes (verification that the client and server are who they say they are) as well as for access control.

Several of the WMI COM interfaces use proxies. You should call CoSetProxyBlanket to adjust the security level on pointers to the following interfaces before calling their member functions:

  • IWbemServices
  • IEnumWbemClassObject
  • IWbemCallResult
  • The WMI Refresher

The WMI Refresher is a special case because it is passed an IWbemServices pointer, whose security settings must be properly set.

In Summary A simple client application can use CoInitializeSecurity to specify process-wide default security settings. CoSetProxyBlanket is used instead to specify settings on an individual proxy.


Simple Security Strategy for Applications

The strategy presented above in the introduction to Using DCOM Security from WMI works for most simple applications. When a client application retrieves dynamic objects, WMI calls the appropriate provider, which may be located on a remote machine. If this provider calls yet another provider, which resides on yet another machine, this simple strategy fails, and WMI returns an Access Denied error.

The problem is that retaining the original client access rights while crossing two machine boundaries is only possible on Windows 2000 machines, running in a Windows 2000 domain, and then only if the impersonation level is set to RPC_C_IMP_LEVEL_DELEGATE. On the other hand, setting the impersonation level to RPC_C_IMP_LEVEL_DELEGATE keeps an application from running on Windows 95/98 or Windows NT 4 machines, or on Windows 2000 machines running in a Windows NT 4 domain.

The client application writer must therefore make an early decision and follow one of three strategies:

  1. To write for the simplest case, in which providers are assumed to be at most one machine boundary away from their clients. In this case, the impersonation level should be set to RPC_C_IMP_LEVEL_IMPERSONATE. Applications written this way will run under almost all Windows operating systems, but should expect and gracefully handle any Access Denied error codes.
  2. To write only for Windows 2000 machines running in a Windows 2000 domain. In this case, the impersonation level should be set to RPC_C_IMP_LEVEL_DELEGATE.
  3. To write for the general case, testing the Windows operating system environment, and choosing RPC_C_IMP_LEVEL_IMPERSONATE or RPC_C_IMP_LEVEL_DELEGATE accordingly.

Whichever strategy is chosen, writing client applications is simpler if only synchronous or semi-synchronous calls are made into WMI. For asynchronous calls, since the client supplies an implementation of IWbemObjectSink, the client switches roles with WMI, and WMI becomes the client, while the client becomes the server. If asynchronous calls are to be used, the client application writer must again choose an implementation strategy:

  1. To write only for Windows 2000 machines running in a Windows 2000 domain. In this case, there are no special coding details.
  2. To write for the general case, using the IUnsecuredApartment interface. For more information, see Security Considerations with Asynchronous Calls. This is the recommended strategy for the general case, whether or not the client owns its process.
  3. To write for the general case when the client owns its process, using CoInitializeSecurity to set the implementation level to RPC_C_IMP_LEVEL_ANONYMOUS. CoInitializeSecurity sets the default security levels on both incoming and outgoing calls. Once set, you must use CoSetProxyBlanket to override and restore security levels on every call into WMI.


DCOM Security Advanced Details

It may sometimes be necessary to use DCOM security parameters to specify an authentication service, or to change identity to a different user. The following section covers these and other advanced topics.

Special Case: IUnknown

Specifying Authentication Services

Selecting the Authentication Level

Specifying the Server Principal

Changing the Authentication Credentials


Special Case: IUnknown

In some cases securing the proxy is not enough. It is also necessary to secure the proxy's IUnknown. When the proxy is on a remote machine, calls to the proxy's IUnknown methods (AddRef/Release/QueryInterface) are delegated to an interface called IRemUnknown. For example if QueryInterface is called on a proxy and the requested interface is not the proxy's, the call is sent to the server in order to see if the server supports the interface, in which case a new proxy is marshaled back to the client.

If the user logged onto the client does not have access to the remote server, and is using authentication credentials of a user that does, calls to the proxy's QueryInterface will fail. The final release on the proxy will also fail, since the logged on user does not have access to the remote machine. A symptom of this is when the final release on the proxy is called, a short 1-2 second lag occurs when the operation fails.

Setting security on the proxy's IUnknown is not difficult; one simply requests the IUnknown from the proxy and calls CoSetProxyBlanket on the IUnknown pointer.

SEC_WINNT_AUTH_IDENTITY_W*        pAuthIdentity = new SEC_WINNT_AUTH_IDENTITY_W;
ZeroMemory(pAuthIdentity, sizeof(SEC_WINNT_AUTH_IDENTITY_W) );

pAuthIdentity->User = new WCHAR[32];
wcscpy(pAuthIdentity->User , L"MyUser" );
pAuthIdentity->UserLength = wcslen(pAuthIdentity->User );

pAuthIdentity-> Domain = new WCHAR[32];
wcscpy(pAuthIdentity-> Domain, L"MyDomain" );
pAuthIdentity-> Domain Length = wcslen( pAuthIdentity-> Domain);

pAuthIdentity-> Password = new WCHAR[32];
pAuthIdentity->Password[0] = NULL;
pAuthIdentity->PasswordLength = wcslen( pAuthIdentity->Password );

pAuthIdentity->Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;

// Set proxy security
CoSetProxyBlanket( pWbemServices, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, pAuthIdentity, EOAC_NONE );

// Set IUnknown security
IUnknown*    pUnk = NULL;
pWbemServices->QueryInterface( IID_IUnknown, (void**) &pUnk );

CoSetProxyBlanket( pUnk, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, pAuthIdentity, EOAC_NONE );

// cleanup IUnknown
pUnk->Release();

//
// Perform a bunch of operations
//

// Cleanup
pWbemServices0->Release();

delete [] pAuthIdentity->User;
delete [] pAuthIdentity->Domain;
delete [] pAuthIdentity->Password;

delete pAuthIdentity;

However, be aware that when you set security on a proxy's IUnknown, DCOM will make a copy of the proxy that may not be released until you call CoUninitialize.


Specifying Authentication Services

[This is preliminary documentation and subject to change.]

The authentication service is used to verify the identity of clients and servers. DCOM negotiates the authentication service when it first makes a connection. The authentication service negotiated by DCOM is almost always the right service for WMI connections. There are some circumstances, however, when it is necessary to specify the authentication service, for example:

  • To specify Kerberos security to use delegation
  • To specify NTLM security on a Windows 2000 machine running in an NT 4 domain.
  • To connect to a share-level Windows 95/98 machine

The authentication service can be specified in a call to CoSetProxyBlanket.

CoSetProxyBlanket(
  pProxy,
  RPC_C_AUTHN_GSS_KERBEROS,     // Kerberos authentication service
  RPC_C_AUTHZ_DEFAULT,          // default authorization service
  COLE_DEFAULT_PRINCIPAL,       // default server principal
  RPC_C_AUTHN_LEVEL_CONNECT,    // authentication level
  RPC_C_IMP_LEVEL_DELEGATE,     // impersonation level
  NULL,                         // use current token
  EOAC_NONE);                   // no special capabilities

The authentication service identifiers are:

Service | Identifier
NTLM | RPC_C_AUTHN_WINNT
Kerberos | RPC_C_AUTHN_GSS_KERBEROS
Negotiate | RPC_C_AUTHN_GSS_NEGOTIATE

Note With Windows 2000, if you are connecting to a local WMI process, you cannot use RPC_C_AUTHN_GSS_KERBEROS. For this reason, use RPC_C_AUTHN_GSS_NEGOTIATE instead of RPC_C_AUTHN_GSS_KERBEROS. You will get Kerberos if it is available. If not, RPC_C_AUTHN_GSS_KERBEROS would fail anyway.

There is no simple way to specify an authentication service in a call to CoInitializeSecurity. Instead, when CoInitializeSecurity is used with the default arguments suggested in the introduction to Using DCOM Security from WMI, the authentication service is negotiated by DCOM. To specify an authentication service in a client application that owns its own process, follow these steps:

  1. Create a thread.
  2. Use the thread to obtain an IWbemServices proxy pointer.
  3. Use CoSetProxyBlanket on the IWbemServices proxy pointer to specify the authentication service.
  4. Use CoSetProxyBlanket with every subsequent call into WMI to specify and maintain the authentication service.

Note DCOM allow for an authorization service to be specified, in addition to authentication service. However, neither NTLM nor Kerberos use an authorization service, so this service should always be specified as RPC_C_AUTHZ_NONE.


Selecting the Authentication Level

The authentication level used by DCOM indicates the amount of authentication used when making calls over the proxies. In general, when using WMI, you will probably want the default authentication level of your process be no lower than RPC_C_AUTHN_LEVEL_CONNECT. Making calls over proxies or performing enumerations may fail if the authentication level is not at least RPC_C_AUTHN_LEVEL_CONNECT.

When IWbemObjectSink methods are called by WMI on Windows NT4, WMI uses an authentication level of RPC_C_AUTHN_LEVEL_NONE. Otherwise, WMI propagates the security context of the call that passed in the sink. In other words, if you set the proxy blanket on an enumerator to RPC_C_AUTHN_LEVEL_PKT_PRIVACY, then on a Windows 2000 machine, IWbemObjectSink::Indicate and IWbemObjectSink::SetStatus calls will be made with an authentication level of RPC_C_AUTHN_LEVEL_PKT_PRIVACY.

When calling a remote Windows 95/98 machine, authentication levels above RPC_C_AUTHN_LEVEL_CONNECT are not allowed. The Windows 95/98 machine can, however, make outgoing calls with higher authentication levels.


Specifying the Server Principal

The principal is the server principal name used by the authentication service to ensure the server's identity. You cannot set this value when calling CoInitializeSecurity. You can, however, set this value by calling IWbemLocator::ConnectServer or CoSetProxyBlanket. In IWbemLocator::ConnectServer, use the bstrAuthority parameter (see below for the appropriate format). In CoSetProxyBlanket, this is the pServerPrincName parameter.

On Windows 95/98 and NT 4 platforms, simply specify NULL for this value when making these calls.

On Windows 2000, you can specify values, but using defaults is generally the best way to go. The principal name is really only useful when using Kerberos and Negotiate. In fact, when calling CoSetProxyBlanket, if you specify RPC_C_AUTHN_GSS_KERBEROS, you must specify a value for the principal name. Your best bet, is to just use COLE_DEFAULT_PRINCIPAL since if you manually specify the wrong name, you will get an error when you call a method on the proxy. If you do specify it, the name must identify the machine account of the remote machine (remember Kerberos is only used in remote scenarios). For example, if the domain is MyDomain, and the machine name is MyMachine, then the machine account is: "MyDomain\MyMachine".

Note This is the case if WMI is running as a service, which should be most of the time. If it is being run as an executable file, the principl name is the name of the currently logged on user.

Best bet:

CoSetProxyBlanket( pWbemServices, RPC_C_AUTHN_GSS_DEFAULT, RPC_C_AUTHZ_DEFAULT,  COLE_DEFAULT_PRINCIPAL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_DEFAULT, COLE_DEFAULT_AUTHINFO, EOAC_DEFAULT );

Manually specifying:

CoSetProxyBlanket( pWbemServices, RPC_C_AUTHN_GSS_KERBEROS, RPC_C_AUTHZ_NONE,  L"MyDomain\\MyMachine", RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_DEFAULT, COLE_DEFAULT_AUTHINFO, EOAC_DEFAULT );

When calling IWbemLocator::ConnectServer(), the value for bstrAuthority is the machine account name, prepended by "kerberos:". Using the above example, "kerberos: MyDomain\MyMachine".

For example:

  IWbemServices* g_pNameSpace = NULL;

  // Name space to connect to
  BSTR  bstrNameSpace =
    SysAllocString( L"\\\\MyMachine\\root\default" );

  // NT Authority
  BSTR  bstrNAuthority =
    SysAllocString( L"kerberos: MyDomain\\MyMachine"  );

  hr = pWbemLocator->ConnectServer(
          bstrNameSpace,  // NameSpace Name
          NULL,           // UserName
          NULL,           // Password
          NULL,           // Locale
          0L,             // Security Flags
          bstrAuthority,  // Authority
          NULL,           // Wbem Context
          &g_pNameSpace   // Namespace
          );

You can specify NULL for bstrAuthority, since DCOM will negotiate the authentication service, and will choose the proper default principal.

In Summary In general, with Windows 2000, your best bet is to let DCOM choose the default service and principal.


Changing the Authentication Credentials

Using DCOM, it is also possible to set authentication credentials on a proxy to be a user other than the owner of the thread or process token.. This is only possible when the client is remote to WMI.

For Kerberos and NTLM, the authentication credentials are specified in a SEC_WINNT_AUTH_IDENTITY_W structure.

Default authentication credentials can be specified in the call to CoInitializeSecurity only on Windows 2000 or greater. This is done by specifying a value in the SOLE_AUTHENTICATION_LIST parameter. On Windows NT4 and Windows 95/98, this MUST be NULL.

// Auth Identity structure
SEC_WINNT_AUTH_IDENTITY_W        authidentity;
ZeroMemory( &authidentity, sizeof(authidentity) );

authidentity.User = L"MyUser";
authidentity.UserLength = wcslen( authidentity.User );
authidentity.Domain = L"MyDomain ";
authidentity.DomainLength = wcslen( authidentity.Domain );
authidentity.Password = L"";
authidentity.PasswordLength = wcslen( authidentity.Password );
authidentity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;

SOLE_AUTHENTICATION_INFO    authninfo[2];

ZeroMemory( authninfo, sizeof( authninfo ) );

// NTLM Settings
authninfo[0].dwAuthnSvc = RPC_C_AUTHN_WINNT;
authninfo[0].dwAuthzSvc = RPC_C_AUTHZ_NONE;
authninfo[0].pAuthInfo = &authidentity;

// Kerberos Settings
authninfo[1].dwAuthnSvc = RPC_C_AUTHN_GSS_KERBEROS ;
authninfo[1].dwAuthzSvc = RPC_C_AUTHZ_NONE;
authninfo[1].pAuthInfo = &authidentity;

SOLE_AUTHENTICATION_LIST    authentlist;

authentlist.cAuthInfo = 2;
authentlist.aAuthInfo = authninfo;

CoInitializeSecurity(
  NULL, -1, NULL, NULL,
  RPC_C_AUTHN_LEVEL_CALL,
  RPC_C_IMP_LEVEL_IMPERSONATE,
  &authentlist,
  EOAC_NONE,
  NULL );

When you set authentication credentials using CoSetProxyBlanket, the structure containing the credentials MUST be valid for the life of the proxy. DCOM maintains a pointer to this structure which it will return in calls to CoQueryProxyBlanket, so the structure must not be deleted until either the value is replaced or the proxy is freed.

SEC_WINNT_AUTH_IDENTITY_W*        pAuthIdentity = new SEC_WINNT_AUTH_IDENTITY_W;
ZeroMemory(pAuthIdentity, sizeof(SEC_WINNT_AUTH_IDENTITY_W) );

pAuthIdentity->User = new WCHAR[32];
wcscpy(pAuthIdentity->User , L"MyUser" );
pAuthIdentity->UserLength = wcslen(pAuthIdentity->User );

pAuthIdentity-> Domain = new WCHAR[32];
wcscpy(pAuthIdentity-> Domain, L"MyDomain" );
pAuthIdentity-> Domain Length = wcslen( pAuthIdentity-> Domain);

pAuthIdentity-> Password = new WCHAR[32];
pAuthIdentity->Password[0] = NULL;
pAuthIdentity->PasswordLength = wcslen( pAuthIdentity->Password );

pAuthIdentity->Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE;

CoSetProxyBlanket(
  pWbemServices,
  RPC_C_AUTHN_WINNT,
  RPC_C_AUTHZ_NONE,
  NULL,
  RPC_C_AUTHN_LEVEL_DEFAULT,
  RPC_C_IMP_LEVEL_IMPERSONATE,
  pAuthIdentity,
  EOAC_NONE );

//
// Perform a bunch of operations
//

// Cleanup
pWbemServices0->Release();

delete [] pAuthIdentity->User;
delete [] pAuthIdentity->Domain;
delete [] pAuthIdentity->Password;

delete pAuthIdentity;

The WMI Refresher calls CoQueryProxyBlanket on the IWbemServices pointer passed into the AddObjectByPath, AddObjectByTemplate and AddEnum methods. This is so that the refresher can propagate those settings during its own calls. Hence, the structure must be available during the life of the IWbemServices pointer, as well as during the life of the WMI Refresher.


Executing Privileged Operations

Special client applications may need to invoke privileged operations. For example, an application might need to be written to allow a manager to reboot an unresponsive office computer. With WMI, this would normally be accomplished by calling the provider of the reboot method on the machine.

Rebooting a machine is a privileged operation. Permission to execute a privileged operation must be granted to a process by the system, and must be specifically enabled by the process itself. To execute the reboot of a remote computer through DCOM, several conditions must be met:

  • Permission to execute a reboot operation must be granted to the client process. This is normally done with system administrative tools prior to running the processes.
  • Permission to reboot must be enabled by the provider process. This is normally done by calling the Win32 function AdjustTokenPrivileges.
  • If the machine to be rebooted is a remote machine, the client process needs no further coding. If the machine to be rebooted is local, both the client and the provider must enable the reboot, using AdjustTokenPrivileges. The following AdjustTokenPrivileges wrapper function illustrates this call:
// First, get the LUID for the privilege from the local system
ZeroMemory(&m_luid, sizeof(m_luid));

LookupPrivilegeValue(NULL, privName, &m_luid);
EnablePriv(service, true);

// Wrapper function for AdjustTokenPrivileges
DWORD WBEMPageHelper::EnablePriv(
  IWbemServices *service, bool fEnable )
{
  DWORD dwError = ERROR_SUCCESS;
  TOKEN_PRIVILEGES tokenPrivileges;

  tokenPrivileges.PrivilegeCount = 1;
  tokenPrivileges.Privileges[0].Luid = m_luid;
  tokenPrivileges.Privileges[0].Attributes =
    ( fEnable ? SE_PRIVILEGE_ENABLED : 0 );

  if (AdjustTokenPrivileges(
      m_hAccessToken,   // handle to privilege token
      FALSE,            // don't disable all privileges
      &tokenPrivileges, // new privilege settings
      0,                // don't save previous settings
      NULL,             // don't save previous settings
      NULL              // don't save previous settings
    ) != 0)
  {
    long lRes = GetLastError();
    m_WbemServices.SetBlanket(service);
  }
  else
  {
    dwError = ::GetLastError();
  }

  return dwError;
}

In the client and provider are on the same machine, the client must specifically enable the privileged operation, using one of the following methods:

  • If the client owns its process, it can use AdjustTokenPrivileges to adjust its own process token before calling into WMI. In this case, no further coding is necessary.
  • If a client cannot use its process token, it can create a thread token and use AdjustTokenPrivileges on that token.
    • If the client uses a thread token, and if the operating system is not Windows 2000, then the privileged operation cannot be executed.
    • If the client uses a thread token, and if the operating system is Windows 2000, then the privileged operation can be executed with the following additional steps:
    1. Use ImpersonateSelf to create a copy of the process token.
    2. Use GetThreadToken to get the newly created thread token.
    3. Use AdjustTokenPrivileges on this token to enable the privileged operation.
    4. Obtain an IWbemServices interface pointer.
    5. Use CoSetProxyBlanket with the default arguments given in the introduction to Using DCOM Security from WMI. Change the last argument from EOAC_NONE to EOA_STATIC_CLOAKING. This step is called "cloaking".
    6. Because DCOM incorrectly caches tokens, you must repeat these five steps prior to any call into WMI.


Delegation and Cloaking Details

Cloaking is an extension to impersonation that allows for better control over how DCOM impersonates a client when communicating over proxies. Cloaking is only available on Windows 2000, and is specified in the dwCapabilities parameter of CoInitializeSecurity and CoSetProxyBlanket.

There are two types of cloaking:

  1. EOAC_STATIC_CLOAKING – When this is specified, the token identity is established by the thread or process token (whichever is available) on the first call into the proxy. If you set this using CoSetProxyBlanket, you fix the identity of the proxy.
  2. EOAC_DYNAMIC_CLOAKING – When this is specified, the token identity is reestablished from the thread or process token (whichever is available) on each call into the proxy. Because this is checked on every call, it allows for more control over client identity; however, it will be less efficient than EOAC_STATIC_CLOAKING.

When cloaking is used in conjunction with RPC_C_IMP_LEVEL_DELEGATE, a server can propagate the client's identity to other servers, even if they are remote. If cloaking is not enabled, then the call from the server to the remote server is made under the context of the actual server process.

Cloaking lets WMI impersonate a client to access both local and network resources across multiple machine boundaries. WMI can pass the client's identity to local and remote servers (e.g. other remote instances of WMI) so those servers perform operations under the initial client context.

In order to delegate the client's identity across multiple machine boundaries, you must use the Kerberos authentication service. Also, for delegation to work, the server's login account must be marked as "Trusted for delegation" in the Active Directory, and the client's account must not be marked as "Account is sensitive and cannot be delegated".

Note You cannot specify cloaking and user credentials at the same time. In other words, if you are using cloaking, the pAuthInfo parameter MUST be NULL.

For example, a call to the Win32 Provider requires full impersonation as follows:

CoSetProxyBlanket(
  pWbemServices,
  RPC_C_AUTHN_WINNT,
  RPC_C_AUTHZ_DEFAULT,
  NULL,
  RPC_C_AUTHN_LEVEL_DEFAULT,
  RPC_C_IMP_LEVEL_IMPERSONATE,
  COLE_DEFAULT_AUTHINFO,
  EOAC_NONE );

BSTR    bstrClass = SysAllocString( L"Win32_Process" );

pWbemServices->CreateInstanceEnum( bstrClass, 0L, NULL, &pEnum );

On the other hand, to call to the View Provider, which may return objects from multiple instances of WMI on multiple machines, you will need to set delegation as follows:

CoSetProxyBlanket(
  pWbemServices,
  RPC_C_AUTHN_GSS_KERBEROS,
  RPC_C_AUTHZ_DEFAULT,
  NULL,
  RPC_C_AUTHN_LEVEL_DEFAULT,
  RPC_C_IMP_LEVEL_DELEGATE,
  COLE_DEFAULT_AUTHINFO,
  EOAC_DYNAMIC_CLOAKING );

BSTR    bstrClass = SysAllocString( L"Union_OS" );

pWbemServices->CreateInstanceEnum( bstrClass, 0L, NULL, &pEnum );

Note On Windows 95/98, DCOM servers cannot impersonate clients, that is, CoImpersonateClient is unavailable.


Utility Classes

[This is preliminary documentation and subject to change.]

WMI provides several utility classes to assist the C++ programmer. The following topics cover information about the utility classes provided with WMI:

  • About Utility Classes
  • Using Utility Classes
  • Utility Class Reference


About Utility Classes

[This is preliminary documentation and subject to change.]

Utility classes assist C++ programming in manipulating strings and arrays of objects. This section covers the following topics:

  • CHString
  • CHStringArray
  • TRefPointerCollection


CHString

[This is preliminary documentation and subject to change.]

WMI has copied the CString class library from the Microsoft Foundation Class (MFC) Library, version 4.0 and renamed it CHString. The CHString class provides the same string functionality as CString but eliminates the overhead associated with including MFC libraries.

The following lists the differences between CHString and CString.

  • CHString has also been limited to handling Unicode strings — it does not provide ANSI support. However, the constructor will accept and convert an ANSI string to Unicode, but there is no way to convert a Unicode string to ANSI.
  • The member function prototypes also reflect the fact that CHString only supports Unicode strings. References to TCHAR have been replaced with WCHAR and references to LPCTSTR have been replaced with LPCWSTR.
  • If you do not include the framework common header file, Fwcommon.h, be sure to include the following lines in your code:
    #ifndef USE_POLARITY
#define USE_POLARITY
#endif
  • All member functions that allocate memory throw CHeap_Exception exceptions. If you include Try blocks, be sure to include Provexce.h.
  • CHString includes a new member function, GetAllocLength.

For information on how to use CHString, see Using CHString Methods. For a list of the CHString member functions, see CHString Reference.


CHStringArray

[This is preliminary documentation and subject to change.]

WMI has copied the CStringArray class library from the Microsoft Foundation Class (MFC) Library, version 4.0 and renamed it CHStringArray. The CHStringArray class supports arrays of CHString objects but eliminates the overhead associated with including the MFC libraries.

The following list describes the differences between CHStringArray and CStringArray.

  • CHStringArray has been limited to handling arrays of Unicode strings — it does not provide ANSI support.
  • The member function prototypes reflect the fact that CHStringArray only supports Unicode strings. References to LPCTSTR have been replaced with LPCWSTR and references to CString have been replaced with CHString.
  • If you do not include the framework common header file, Fwcommon.h, it is necessary to include the following lines in your code:
    #ifndef USE_POLARITY
#define USE_POLARITY
#endif
  • All member functions that allocate memory throw CHeap_Exception exceptions. If you include try blocks, be sure to include Provexce.h.
  • You must include chstring.h before you include chstrarr.h.

For a list of CHStringArray member functions, see CHStringArray Reference.


TRefPointerCollection

[This is preliminary documentation and subject to change.]

The TRefPointerCollection class is a template for creating thread safe collections (lists) of items that support reference counting. The generated list is not intended to be a complete general purpose list, but rather it exclusively serves the purpose of returning a complete result set from a query.

The TRefPointerCollection class is used as arguments when creating a Provider that uses CWbemProviderGlue methods.

For information on how to use TRefPointerCollection, see Using TRefPointerCollection methods. For a list of the TRefPointerCollection member functions, see TRefPointerCollection Reference.


Using Utility Classes

[This is preliminary documentation and subject to change.]

This section covers the following topics:

  • Using CHString Methods
  • Using TRefPointerCollection Methods


Using CHString Methods

[This is preliminary documentation and subject to change.]

The Framework Provider methods make use of a string data type called a CHString. The CHString class was originally modeled on the Microsoft MFC CString class. As time has passed, these two classes have drifted apart. Specifically, the CHString class lacks some of the Unicode support of the CString class.

Internally, CHString instances (strings) store their information as wide character strings, that is, two bytes per character. The default value of a CHString is the starting address of its first character. CHStrings end with a two-byte null.

Because CHStrings use wide character strings, they can store Unicode strings without conversion. Like CStrings, the constructors will accept either wide character strings, Unicode strings, or ANSI strings. In the case of ANSI strings, the string is converted to a wide character string by the constructor.

CHString sTarget = "abc"; // ANSI string is ok
CHString sTarget = L"abc"; // Unicode string is ok

However, CStrings can be implicitly cast to either ANSI or Unicode strings. CHStrings cannot be implicitly cast to ANSI strings. Assuming you are compiling for a multibyte environment, such as Windows 98, there are many standard functions that require ANSI strings.

CString sTarget = "abc";
openfile(sTarget, ...); // succeeds
CHString sTarget = "abc";
openfile(sTarget, ...); // fails

CHStrings can be explicitly cast to ANSI strings by using the _bstr_t class, one of the Microsoft COM support classes declared in COMDEF.H. A _bstr_t string constructor takes either an ANSI string, a wide-character string, or even a BSTR as an argument. The _bstr_t class includes conversion operators for both ANSI and wide-character strings.

CHString sTarget = "abc";
openfile(_bstr_t(sTarget), ...); // succeeds

If you can't include COMDEF.H, you must provide storage for the conversion and convert the string yourself, using WideCharToMultibyte or an equivalent conversion.

Also, be careful when using printf to avoid the following unsupported construction:

printf("%s", sTarget);

Arguments which follow the format string "%s" push the start of their data storage on the stack, and not necessarily the address where the expected data begins. Use this format instead:

printf("%s", (LPCSTR) sTarget);

For background information on CHString, see CHString. For a list of the CHString member functions, see CHString Reference.


Using TRefPointerCollection Methods

[This is preliminary documentation and subject to change.]

The following example shows how to use the TRefPointerCollection class with CWbemProviderGlue::GetAllInstances.

TRefPointerCollection<CInstance> theList;    //create the container for CInstance instances

//Call the CWBemProviderGlue function. strClassName is the class name whose instances are to be obtained
//strNamespace is the namespace that contains the class name
HRESULT hres = CWbemProviderGlue::GetAllInstances(strClassName, &theList,
         strNamespace, pMethodContext);

//Gets the number of CInstance objects in the TRefPointerCollection
int nElements = theList.GetSize();

//Iterate the collection
REFPTRCOLLECTION_POSITION itr;        //declare an iterator
int loopctr;                //declare a loop control
CInstance*  pInstance;            //declare pointer to CInstance
itr = REFPTRCOLLECTION_START;        //You must always start here
theList.BeginEnum(itr);            //You must always call BeginEnum first!
for (loopctr = 0; loopctr < nElements; loopctr++)
{
    pInstance = theList.GetNext(itr);    //Gets a pointer to the next instance in the container
    .....do something with the instance....
    pInstance->Commit();        //provide instance to consumer
                    //Commit() releases the instance
                    //NOTE! if you don't Commit() you must Release() or you
                    //have a memory leak!
}
theList.EndEnum();                //You must always call EndEnum last!

For background information on TRefPointerCollection, see TRefPointerCollection. For a list of the TRefPointer member functions, see TRefPointerCollection Reference.


Utility Class Reference

[This is preliminary documentation and subject to change.]

WMI provides several utility classes to assist the C++ programmer. The following topics cover information about the utility classes provided with WMI:

  • CHString Reference
  • CHStringArray Reference
  • TRefPointerCollection Reference


CHString Reference

[This is preliminary documentation and subject to change.]

For background information on CHString, see CHString. For a code example that uses CHString, see Using CHString Methods.

The following table lists the member functions and operators available in CHString.

Member Function | Description
Construction |
CHString | Constructs CHString objects in various ways.

The String as an Array |
GetLength | Returns the number of Unicode characters in a CHString object.
IsEmpty | Tests whether a CHString object contains no characters.
Empty | Forces a string to have 0 length.
GetAt | Returns the character at a given position.
Operator [] | Returns the character at a given position — operator substitution for GetAt.
SetAt | Sets a character at a given position.
Operator LPCWSTR | Directly accesses characters stored in a CHString object as a C-style string.

Assignment/Concatenation |
Operator = | Assigns a new value to a CHString object.
Operator + | Concatenates two strings and returns a new string.
Operator += | Concatenates a new string to the end of an existing string.
 | Comparison
Operator == <, etc. | Comparison operators (case sensitive).
Compare | Compares two strings (case sensitive).
CompareNoCase | Compares two strings (case insensitive).
Collate | Compares two strings (case sensitive, uses locale-specific information).

Extraction |
Mid | Extracts the middle part of a string (like the Basic MID$ function).
Left | Extracts the left part of a string (like the Basic LEFT$ function).
Right | Extracts the right part of a string (like the Basic RIGHT$ function).
SpanIncluding | Extracts a substring that contains only the characters in a set.
SpanExcluding | Extracts a substring that contains only the characters not in a set.

Other Conversions |
MakeUpper | Converts all the characters in this string to uppercase characters.
MakeLower | Converts all the characters in this string to lowercase characters.
MakeReverse | Reverses the characters in this string.
Format | Formats the string as sprintf does.
FormatMessageW | Formats a message string.
FormatV | Formats the string as vsprintf does.
TrimLeft | Trim leading whitespace characters from the string.
TrimRight | Trim trailing whitespace characters from the string.

Searching |
Find | Finds a character or substring inside a larger string.
FindOneOf | Finds the first matching character from a set.
ReverseFind | Finds a character inside a larger string; starts from the end.

Buffer Access |
GetBuffer | Returns a pointer to the characters in the CHString.
GetAllocLength | Returns the size of the string buffer.
GetBufferSetLength | Returns a pointer to the characters in the CHString, truncating to the specified length.
ReleaseBuffer | Releases control of the buffer returned by GetBuffer.
FreeExtra | Removes any overhead of this string object by freeing any extra memory previously allocated to the string.
LockBuffer | Disables reference counting and protects the string in the buffer.
UnlockBuffer | Enables reference counting and releases the string in the buffer.
Windows-Specific |
AllocSysString | Allocates a BSTR from CHString data.
LoadStringW | Loads an existing CHString object from a resource file.


CHStringArray Reference

[This is preliminary documentation and subject to change.]

For background information on CHStringArray, see CHStringArray.

The following table lists the member functions and operators available in CHStringArray.

Member Function | Description
Construction |
CHStringArray | Constructs an empty array for CHString objects.
Bounds |
GetSize | Gets the number of elements in the array.
GetUpperBound | Returns the largest valid index.
Operations |
FreeExtra | Frees all unused memory above the current upper bound.
RemoveAll | Removes all the elements from this array.
Element Access |
GetAt | Returns the value at a given index.
SetAt | Sets the value for a given index; the array is not allowed to grow.
ElementAt | Returns a temporary reference to the element pointer within the array.
GetData | Allows access to elements in the array. The value can be NULL.
Growing the array |
SetAtGrow | Sets the value for a given index; the array grows if necessary.
Add | Adds an element to the end of the array; the array grows if necessary.
Append | Appends another array to the array; the array grows if necessary.
Copy | Copies another array to the array; the array grows if necessary.
Insertion/Removal |
InsertAt | Inserts an element (or all the elements in another array) at a specified index.
RemoveAt | Removes an element at a specific index.
Operators |
Operator [] | Sets or gets the element at the specified index.


TRefPointerCollection Reference

[This is preliminary documentation and subject to change.]

For background information on TRefPointerCollection, see TRefPointerCollection. For a code example that uses TRefPointerCollection, see Using TRefPointerCollection methods.

The following table lists the TRefPointerCollection Class methods available to TRefPointerCollection.

TRefPointerCollection Methods | Description
Add | Adds an item to the list (addrefs it)
BeginEnum | Call before you enumerate (traverse) the list, pass in a cursor to be initialized (REFPTRCOLLECTION_POSITION)
GetNext | Gets next item from the list, addrefs it - user must release when done, pass in same cursor each time.
EndEnum | Call when finished enumerating.
Empty | Empties out the list, releasing all held pointers
GetSize | Returns how many items are in the list.


Association Support

[This is preliminary documentation and subject to change.]

Although the Common Information Model (CIM) and WMI in general permits arbitrary associations between objects, there are limitations in association support within WMI itself due to reference typing, association subclassing, and the interactions between statically defined and dynamically provided objects. This section describes the supported scenarios and limitations and states in precise terms the meanings of queries relating to references and associations. The reader is presumed to be familiar with WMI and CIM documents.


Association Syntax

[This is preliminary documentation and subject to change.]

An association is a CIM object which binds two other objects in a relationship. Association classes must have an [association] qualifier and two object paths, which perform the bindings. Objects which do not have the [association] qualifier or which have only a single reference or more than two references are not officially supported.

[Association]
class MyAssoc
{
    [key] EpClass1 ref ep1;
    [key] EpClass2 ref ep2;
}

As illustrated, it is typical for the association reference properties to be the keys which particularize instances of the association class itself. Obviously, there is no requirement that ep1 and ep2 be the keys. Other properties acting as the keys could have been declared instead.

Associations are normal CIM classes and follow the same rules as all other classes. Thus, an association relationship is a triple, two endpoint objects and an association object which binds them together. The endpoint objects are not aware of the binding, and the association object describes the entire relationship by pointing to the endpoints:

Endpoint A <— Association –> Endpoint B

It is important to note that the decoupling of the relationship from the endpoint objects allows new relationships to be built without altering the endpoints.


Association Notation

[This is preliminary documentation and subject to change.]

Due to the complexities of many scenarios, a form of terse notation is in order.

The notation used in this document for classes will use the following symbols:

A = an association class

E = an endpoint class

I = an instance

D = dynamic

If an object is not marked with D, then it is presumed static. When it is necessary to particularize individual class definitions or instances, they will be designed through subscripted integers. A missing subscript denotes an undifferentiated instance of a class. Instances of a class must be prefixed by their class identifier.

Here are some examples of this notation:

A1 = a static association class

A1I = an instance of association class

E2 = static endpoint class number 2

A1I1 , A1I2 are instances 1 and 2 of the class defined in (a) above.

DE2 = dynamic endpoint class 2

E3DI1= dynamic instance of static endpoint class 3

DA4DI5 = dynamic instance 5 of dynamic association class 4

Note WMI does not support static instances of dynamic classes, so DE1I1 is not possible.

A set of classes for a scenario is simply grouped in brackets, with derivation expressed with a colon: {A1,A2:A1, A3:A1 , E1, E2, E3: E2, E4: E1}, which expressed the forest of classes:

Association bindings are designated with arrows.

E1 <— A1 ® E2

This example represents a schema-only association associating two classes. This means that instances of A1 are used to associate instances of E1 and E2.

E1DI <— A1DI ® E2DI

This example represents an actual occurrence of an association: all static classes, dynamic instances of endpoints and associations.

Note The relationship E1DI <— A1I ® E2I is the same scenario as E1I <— A1I ® E2DI, since the endpoints are commutative in the abstract sense, and both are described as "all static classes; dynamic instance at one endpoint", as the actual classes are anonymous.


Subclass Notation

[This is preliminary documentation and subject to change.]

The use of Î: means "derives from" or "is a subclass of". For example E4 Î:E1 means that E4 is a subclass of E1.

The term dynasty is used to refer specifically to a class hierarchy beginning from a particular root class which has no superclass. Given {A,B:A,C:B} the A dynasty refers to all three classes. There is no B dynasty, since it is not a root class.

The term hierarchy is not so specific, it refers somewhat vaguely to a chain of subclasses but with no specifics as to where the hierarchy starts.


Reference Semantics

[This is preliminary documentation and subject to change.]

In the default semantics of a reference property, the typing applies when the association class is instantiated. That is, for any given instance of association class, a strongly typed reference points to instances of the specified property class or one of its subclasses.

[Association]
class MyAssoc
{
    [key] EpClass1 ref ep1;
    [key] EpClass2 ref ep2;
}

In this example, for all instances of MyAssoc, ep1 will point to instances of EpClass1 or any of its subclasses, and ep2 will point to instances of EpClass2 or any of its subclasses.

Such references may not point to class definitions; there are other mechanisms for this.

A reference to a class is a reference to any instance of that class or its subclasses. A reference cannot be typed to point to a class and any of its superclasses.

Thus, an association binding E1 <— A1 ® E2 implies that E1 <— A1 ® E3 is also possible where E3 Î:E2. The inverse is not true( E1 <— A1 ® E3 does not imply E1 <— A1 ® E2 where E3 Î:E2). In essence, this means that associations which bind superclasses may bind any of their subclasses, but an association defined between two subclasses is not valid to bind their superclasses.


Weakly Typed References

[This is preliminary documentation and subject to change.]

There is a weakly typed reference called an object ref . In theory, this reference may point to anything. However, such references will not take part in queries, as there is not enough type information to know what to access when evaluating a query. There is one special supported case of object ref that concerns class reference support.

In WMI, there is no support for an ambiguous reference (a reference that is loosely defined to point to a class or an instance using the object ref type).


Association Class Details

[This is preliminary documentation and subject to change.]

Association classes may be abstract or real (instantiable), as well as have subclasses or superclasses, as any other CIM class.

Rule

An association class must have the Association qualifier and two reference properties.

Note Even though a class with a single reference property acting as a subclass to another class with another single reference property in fact has two references.

[Association]
class MyAssoc
{
  B ref ep1;
};

class MyAssoc2 : MyAssoc
{
  OtherClass ref ep2;
}

WMI does not support this splitting the references between classes in a hierarchy. Both references must be declared local to the same class.


Creating Reference Properties using IWbemClassObject

[This is preliminary documentation and subject to change.]

When you create a reference property programmatically by using IWbemClassObject->Put, the reference properties become typed as CIM_REFERENCE. These properties will have CIMTYPE qualifiers, which contain values of the following format.

"REF:classname"

where classname is the class type of the reference property.

If the object reference is weakly typed, (an object ref), then the string is simply "REF" without the colon and class name.


Retyped and Half-Retyped Subclassed Associations

[This is preliminary documentation and subject to change.]

An association may be retyped in a subclass, as long as the typing is stronger than in the subclass. Retyping the reference to point to a class in a different dynasty or one which is weaker is not permitted. Start with {A,B:A,C:B,D,E:D, F, G, H} and the following association class.

[Association]
class MyAssoc
{
  D ref ep1;
  B ref ep2;
};

Given this information, the following is not legal.

class MyAssoc2 : MyAssoc
{
   F ref ep1;        // cannot change dynasties
   A ref ep2;        // subclass cannot be weaker than superclass
}

However, the following is legal:

class MyAssoc2 : MyAssoc
{
   E ref ep1;        // E is a subclass of D
   C ref ep2;        // C is a subclass of B
}

These are fully retyped associations. Half-retyped associations occur when only one of the references is overridden and are legal:

class MyAssoc2 : MyAssoc
{
    // ep1 is still the same
   C ref ep2;        // C is a subclass of B
}

So, in any given subclass S of association class A where references point to endpoint classes E1 and E2, one or both references may be retyped to Ex and EY such that Ex Î: E1 and EY Î: E2.

Retyping both references is called a retyped association. If only one of the reference properties is retyped, it is called a half-retyped association. Both of these are supported. Note that there is no supported scenario where the subclass may have references of an unrelated type or references which are more weakly typed than the superclass.


Same-Dynasty Associations

[This is preliminary documentation and subject to change.]

Associations which point to objects in the same class family (dynasty) are legal. Given the dynasty {A,B:A,C:B}, the following are legal.

[Association]
class MyAssoc
{
  A ref ep1;
  A ref ep2;
};

[Association]
class MyAssoc2 : MyAssoc
{
  A ref ep1;
  C ref ep2;    // Retyped
};


Class References

[This is preliminary documentation and subject to change.]

In WMI, a class may have instances which actually have references, which point to class definitions rather than instances. The association class must be specially tagged if its reference properties must be tagged with the class dynasties that the reference can point to at runtime, using the qualifier array, CLASSREF.

The reference types must be object ref (weak references), since normal strongly typed references are actually designed to point to instances of the class in question.

[HasClassRefs, Association]
class MyAssoc
{
    [key, classref{ "MyEndpoint"}]
     object ref ep1;
[key, classref{ "MyContainer", "OtherContainer" }]
     object ref ep2;
};

Note that using the above class definition, instances of MyAssoc can have ep1 pointing to the class MyEndpoint or any of its subclasses. Similarly, ep2 can point to MyContainer (or any of its subclasses) or OtherContainer and any of its subclasses.

Weak typing of the classref qualifier is not allowed (you cannot use "*" or some other indication that the reference may point to any class.) This would make the WMI query engine unviable in terms of efficiency, as there would be no way to avoid enumerating classes from all providers.

The classref qualifier may be legally applied to only one of the references, implying an association which binds instances to classes.

In all cases, the HasClassRefs qualifier must still be present on the class definition, and its flavor must be set to propagate to all instances and subclasses.

Note While the repository, due to its design, supports references of classes by association instances without the HasClassRefs qualifier, this is not recommended or supported. (SNMP SMIR uses this and should be updated).


Cross-Namespace Support

[This is preliminary documentation and subject to change.]

While references may be fully qualified or namespace relative, cross-namespace references are themselves problematic.

There is limited support for cross-namespace bindings in that all statically defined (repository-based) objects may reference each other across namespace boundaries. However, when providers become involved, there is no such support. Queries are always executed with reference to a particular namespace; if the objects which reference the query endpoint reside dynamically in another namespace, they will not be included in the result set.

There are ways to imaginatively construct providers to partially et around this problem, such as constructing proxy objects in one namespace which actually refer to instances in another namespace, for example. However, this is not officially supported.


Unary, Ternary and N-Ary Associations

[This is preliminary documentation and subject to change.]

There is no official support for non-binary associations (classes with one reference or three or more references instead of exactly two).

Many references of operations will probably work, but there is no official support.

Classes marked with the [association] qualifier must in fact have two references, whether defined locally or inherited from a superclass.


Queries Relating to Associations

[This is preliminary documentation and subject to change.]

There are two types of queries in WMI that specifically relate to associations, references queries and associators queries. Start with the following association relationship of three instances.

E1I <— A1I ® E2I

The user knows one endpoint and wishes to either locate the association object itself or the other endpoint instance.

The term query endpoint refers to the starting object, which is known. A references of query will determine the association objects, and an associators of query will transitively locate the other endpoint by traversing the association.

For associators of queries, the endpoints in the result set are called the unknown endpoints in this document.

In the above case, references of { E1I } yields A1I as the result set, and associators of { E1I } yields E2I as the result set.


Association Query Syntax

[This is preliminary documentation and subject to change.]

The query syntax is essentially one of the two following combinations:

references of {queryendpoint} [where filters]

associators of {queryendpoint} [where filters]

The queryndpoint is an object path enclosed in curly braces and is the starting point of the query; it can be any object, a class or an instance, depending on the intent.

The WHERE clause followed by filters is optional. If there are filters, WHERE is required. If there are no filters, WHERE cannot be used. The available filter types vary between the two types of queries. These queries cannot be followed by arbitrary WHERE clauses as in SQL. Only filters from the following list may be used.

Filter name | Applicability | Meaning
ResultClass=<class name> | references -and associators | All objects in the the result set must be of the specified class or one of its subclasses.
Role=<property name> | References and associators | The endpoint must be referenced via the property specified in the association.
ResultRole=<prop name> | Associators | The unknown endpoints must be referenced by a property in the association, whose name is <prop name>.
AssocClass=<class name> | Associators | The result set must associate to the endpoint with the specified association class or one of its subclasses.
RequiredQualifier=<qual name> | References & associators | Objects in the result set must have the specified qualifier in their class definition (it can have any value).
RequiredAssocQualifier=<qual name> | Associators | The association object which is being traversed must have the qualifier in their class definition or the unknown endpoint is not included in the result set.
ClassDefsOnly | References & associators | See notes on Query Types.
SchemaOnly | References & associators | See notes on Query Types.
KeysOnly | References & associators | The objects returned are only required to have keys.

All of the filter types may be used simultaneously within the type of query they apply to, except that ClassDefsOnly and SchemaOnly are mutually exclusive.


Association Query Types

[This is preliminary documentation and subject to change.]

There are several basic query types; the one you use depends on whether instances, classes, or a mix of both are required. Normally, the user will want to work with instances. In this case, the query endpoint object is an instance, and the query has no filters:

References of {endpoint_instance}

In this case, only instances which point to the query endpoint will be returned. Conversely, the following statement may return a mix of classes and instances,

Associators of {endpoint_instance}

This can occur because the relationships may look like this.

E1I <— A1I ® E2I

E1I <— A2I ® E3

In this case, one of the the association instances binds an instance to a class.

Additionally, there are cases where the user may want to avoid instantiating associations and merely wish to query the schema to find out what types of relationships are possible purely at the abstract level:

E1 <— A1 ® E2

In this case, associators of {E1} would return { E2 } because instances of E1 can associate to instances of E2, although there is no guarantee such instances actually exist in the namespace.

The three general types of queries are normal queries, SchemaOnly queries, and ClassDefsOnly queries.

Query Type | Query Endpoint Type | Associations & Unknown endpoints
Normal | An instance or a class | Associations analyzed are only instances; the result set contains instances or classes.
ClassDefsOnly | An instance | Associations analyzed are only instances; the result set must be class definitions
SchemaOnly | Class | Associations analyzed are only classes; the result set must be classes.

Normal Queries

Normal queries are limited to working in situations where at least one instance is involved in the relationship. Since WMI doesn't support classes which associate instances (meaningless), this means that the association object itself must be an instance, where the other endpoint can be an instance or a class.

In the following set of associations, the query references of E1 will not return A1 because it is a class definition.

E1<—A1®E2

E1<—A2I1®E3I

E1<—A3I1®E4

Likewise, the query associators of E1 will return both E3I and E4 because there are two association instances involved. The fact that the other endpoints are a mix of classes and instances is not relevant.

A normal query answers the question, "Given this instance or class, what "real" relationships (via real association instances) are actually present in the namespace?"

Schema-Only Queries

Schema-only queries operate entirely from the classes in the schema. They do not under any circumstances involve instances. A schema-only query answers, "What relationships are possible with instances of the endpoint class?". Given the following relationships, a references of { E1 } where schemaonly will return A1 , and associators of { E1 } where schemaonly will return E2.

E1<—A1®E2

E1<—A2I1®E3I

E1<—A3I1®E4

The other relationships are excluded because instances are involved.

ClassDefsOnly Queries

ClassDefsOnly queries answer the question, "Given an instance, what real classes are involved in relationships to it?". This is similar to a SchemaOnly query in that we are asking for a set of classes in the result set but only classes which really have instances which bind the endpoint in a relationship. Schema-only queries tell of potential relationships which may exist, but ClassDefsOnly queries tell of actual known relationships. Both types of queries return class definitions. Given references of {E1I} where classdefsonly, the result set is { A2, A3 } because both of these classes have instances which point to the query endpoint.

E1<—A1®E2

E1I<—A2I1®E3I1
E1I<—A2I2®E3I2

E1I<—A3I1®E4

Note there are no instances of A1 actually forming relationships to the query endpoint, even though the first schema-only relationship states that it is possible.

The query associators of {E1I} where classdefsonly will return { E3 }, because only E3 has instances on the unknown endpoint. Note that associators of {E1I} without the classdefsonly will return { E3I1, E3I2, E4 }.

A special cases exists when instances of a class hierarchy are returned. For example, given {A,B:A,C:B}, if instances of each of A, B, and C are returned, only A will be the result set. It's necessary to select the highest class in the hierarchy that is not itself abstract. Thus, if only instances of B and C are returned, A will be the result only if it is non-abstract. If A is abstract, then B will be the returned class. In other words, the farthest non-abstract parent is selected as the return type for a set of instances in a dynasty.


ClassDefsOnly IN/OUT Tagging

[This is preliminary documentation and subject to change.]

When executing references of ClassDefsOnly queries, the returned class definitions are tagged with special qualifiers on the reference properties (roles).

If the reference property can point to the query endpoint, the Boolean qualifier IN will be attached to that reference property. If the property can only point to the unknown endpoint, OUT will be attached. Because of the same-dynasty semantics of some associations, one or both properties may be tagged as IN and OUT.

The following example shows the query references of {MyEndpointA=1} where ClassDefsOnly.

Instance of MyEndpointA { k = 1;};
Instance of MyEndpointB { keystr = "AAA"; };

Instance of MyAssoc { ep1="MyEndpointA=1";
ep2="MyEndpointB='AAA'"; };

The query will return the instance of MyAsso.as follows.

Instance of MyAssoc
{
  [in] ep1="MyEndpointA=1";         // Points to query endpoint
  [out] ep2="MyEndpointB='AAA'";    // Points away from query endpoint
};

The IN and OUT tagging is based on cursory analysis of the schema and some instances. Due to internal short-circuiting, when mixes of [in,out] occur on the same property, both are not guaranteed to actually exist in any given relationships. Only one of the two is guaranteed to exist. The reason for this is that the query engine has to actually instantiate associations to discover the IN and OUT tags. To discover with 100 percent accuracy all IN and OUT mappings would require full enumerations, whereas by only guaranteeing one to be accurate and the other one merely possible, the query engine only needs to examine a single association instance. In no way does this optimization lessen the usefulness of this type of query. However, its purpose is to indicate to the user which types of associations are backed by real instances in the namespace, as opposed to being purely hypothetical.


ResultClass Semantics

[This is preliminary documentation and subject to change.]

If the ResultClass filter is used, objects in the result set must be of the specified class or must be a subclass of the specified class. This applies to both classes and instances, and to all queries.


Role Semantics

[This is preliminary documentation and subject to change.]

A 'role' is simply a reference property name in the association object. In all types of queries, the association is only returned if it referenced the query endpoint via the specified property name.


Result Role Semantics

[This is preliminary documentation and subject to change.]

A 'role' is simply a reference property name in the association object. In all associators of queries, the unknown endpoint is only returned if the association references it via the specified property name.


AssocClass Semantics

[This is preliminary documentation and subject to change.]

For associators queries, the unknown endpoints are returned in the result set only if they are linked to the query endpoint by instances of the class specified by AssocClass or one of its subclasses.

This applies to all associators of query types.


RequiredQualifier Semantics

[This is preliminary documentation and subject to change.]

For all types queries, the class definition for each object in the result set must have the specified qualifier, regardless of its value (except that it may not be CIM_BOOLEAN == FALSE).

The qualifier is required on individual instances as well and so must be declared on the class definition with ToInstance propagation flavor.

Note If the qualifier is present on the instance and not the class, the object will not be included in the result set. This filter is used to deselect certain classes from participating in queries before the instances are obtained for analysis.


RequiredAssocQualifier Semantics

[This is preliminary documentation and subject to change.]

For associators of queries, the unknown endpoints are returned only if they are bound to the query endpoint by association objects whose classes contain the specified qualifier name, regardless of its value (except that it may not be CIM_BOOLEAN == FALSE).

Note that if the qualifier is present on the association instance and not the class, the unknown endpoint object will not be included in the result set. This filter is used to deselect certain classes from participating in queries before the instances are obtained for analysis.

The qualifier is required on individual instances as well and so must be declared on the class definition with ToInstance propagation flavor.


KeysOnly Semantics

[This is preliminary documentation and subject to change.]

The entire query is executed by simply retrieving all participating objects with just their key values. Since other properties are often expensive to obtain, working entirely with the keys provides a lot of information as to which objects are in which relationships at a very low cost.

However, the client application will have to retrieve the objects separately in order to obtain the full information, if required.


Duplicate Objects in "Associators Of" Queries

Windows Management Instrumentation

Duplicate Objects in Associators Of Queries

[This is preliminary documentation and subject to change.]

Given a pair of endpoints being bound by different associations, a plain associators of query will return duplicate results:

E1I<—A2I1®E3I

E1I<—A3I1®E3I

Associators of { E1I } returns { E3I,  E3I }.

This is not an error. To track all objects in the result set to eliminate duplicates would represent an unbounded caching problem.


Special Cases in SchemaOnly Queries

[This is preliminary documentation and subject to change.]

When executing a schema-only query, there are certain problems relating to whether or not an association class can reference an endpoint: class.

Given {A,B:A,C:B,D:C} and {MyAssoc,MyAssoc2:MyAssoc}, the following association class references each of the classes in the {A} dynasty:

class MyAssoc
{
  [key] sint32 p;
  B ref ep1;
  OtherClassRef ep2;
};
class MyAssoc2 : MyAssoc { ... }

Since all instances of B are also instances of A, then a references of A where schemaonly query might be able to yield in its result set both this association class MyAssoc and its subclass MyAssoc2.

Similarly, any given instance of MyAssoc or MyAssoc2 may be able to reference an instance of B,C, or D, since in theory instances of C and D are also B objects. Therefore references of D where schemaonly might also include MyAssoc and MyAssoc2 in its result set.

Important This loose interpretation can lead to tremendous confusion because of the flood of classes in the result set, many of which have no meaning and which may never actually occur once the classes have been instantiated.

For these queries to be useful, stricter interpretation is required.

An association class is only considered a candidate for a result set if it locally references the endpoint. This means that both superclasses and subclasses are not considered references if they do not contain the reference properties:

class MyAssocBase { [key] sint32 keyval; }    // Has no references

[Association]
class MyAssoc
{
  A ref ep1;
  Z ref ep2;
};

class MyAssoc2 : MyAssoc { ... }

On MyAssoc is considered a referencing class and a candidate for a result set. MyAssoc2 adds nothing, because all instances of MyAssoc2 are in fact MyAssoc objects. Likewise, no instance of MyAssocBase can ever reference anything, as it is not strictly speaking an association object.

Thus, given a forest of simple root classes with no subclasses { A, …, Z }, as implied in the above association, the following query will only return MyAssoc and will not include either the superclass nor the subclass.

references of A where schemaonly

Only association classes where the references are declared local to that class are candidates. This is to prevent a flood of classes in the result set. Consider what would happen if MyAssoc2 was the parent of a dynasty of classes several hundred deep. All those classes would be returned, conveying no more information that if MyAssoc alone had been returned, as the subclasses do not modify the association relationship; they differ in the addition of other properties specific to their instances.

As a result, WMI specifically disallows subclassed endpoints in the queries. The original scenario uses the original class hierarchy {A, B:A, C:B, D:C}, and the following association class.

class AssocBase {};
class MyAssoc : AssocBase
{
  [key] sint32 p;
  B ref ep1;
  OtherClassRef ep2;
};
class MyAssoc2 : MyAssoc {}

The queries and their result sets are as follows:

references of A where schemaonly = { Æ}

references of B where schemaonly = { MyAssoc }

references of C where schemaonly = { Æ}

references of D where schemaonly = { Æ}

Continuing the previous example, the association is slightly modified.

class MyAssoc
{
  [key] sint32 p;
  A ref ep1;
  B ref ep2;
};

Consider the following query.

associators of B where schemaonly role=ep1

In this case, the query designated that all endpoints be referenced by ep2. Again, A, cannot be included since the association designer explicitly states that B and its subclasses are the ones referenced by ep2. However, all subclasses of B are included, again there is a result set explosion. If there are hundreds of classes subclassing from B, then all of them are conceivably part of the result set, because they could be referenced by ep2. Again, as any given instance may never be of any of those subclasses (they may all in fact be plain vanilla instances of B), it is not useful to return subclasses of B in the result set.

Thus, using the above association

references of A where schemaonly = { MyAssoc } // via ep1 only filter

references of B where schemaonly = { MyAssoc } // via ep2 only filter

references of C where schemaonly = { Æ}

references of D where schemaonly = { Æ}

and

references of A where role=ep2 schemaonly = { Æ}

references of B where role=ep2 schemaonly = { MyAssoc }

references of C where role=ep2 schemaonly = { Æ}

references of D where role=ep2 schemaonly = { Æ}


ClassRefs in Queries

[This is preliminary documentation and subject to change.]

Classes marked with HasClassRefs cannot participate in SchemaOnly or ClassDefsOnly queries. These classes may only participate in normal queries. In all cases, the query endpoint must be an instance or a class, the evaluated associations must always be instances, and the unknown endpoints can be classes or instances.


Cardinality Rule

[This is preliminary documentation and subject to change.]

Since associations always bind two endpoints, for any given endpoint, the number of references to the endpoint equals the number of unknown endpoints via associations.

Thus, cardinality of references of {E} equals cardinality of associators of {E}.


Extent of Dynamic and Static Association Support

[This is preliminary documentation and subject to change.]

There are exactly 125 combinations of associations and endpoints, depending on whether the various parts are dynamic or static or whether the association is instance to instance, instance to class, or class to class. Because the endpoint scenarios are commutative (E1DI <— A1I ® E2I is the same scenario as E1I <— A1I ® E2DI), there are actually only 75 unique cases.

WMI will not support the following general cases:

  • Associations where classes point to instances (classrefs referencing instances).
  • Cases where dangling references are intentionally introduced. A dangling reference is a reference pointing to an object which will never be introduced.

Thus, cases marked No are usually one of these two situations.

Scenario | Semantics | Supported
S1 | E1<—A1®E2 | Yes
S2 | E1<—A1®E2I | No
S3 | E1<—A1®E2DI | No
S4 | E1<—A1®DE2 | Yes; via classref in A1 definition
S5 | E1<—A1®DE2DI | No
S6 | E1<—A1I®E2 | Yes
S7 | E1<—A1I®E2I | Yes
S8 | E1<—A1I® E2DI | No; requires a dangling ref
S9 | E1<—A1I® DE2 | No; requires a dangling ref
S10 | E1<—A1I® DE2DI | No; requires a dangling ref
S11 | E1<—A1DI®E2 | Yes
S12 | E1<—A1DI®E2I | Yes
S13 | E1<—A1DI®E2DI | Yes
S14 | E1<—A1DI® DE2 | Yes (via classref) in A1 definition
S15 | E1<—A1DI® DE2DI | Yes
S16 | E1<—DA1®E2 | Yes
S17 | E1<—DA1®E2I | No
S18 | E1<—DA1®E2DI | No
S19 | E1<—DA1®DE2 | Yes
S20 | E1<—DA1®DE2DI | No
S21 | E1<—DA1DI ®E2 | Yes
S22 | E1<—DA1DI ®E2I | Yes
S23 | E1<—DA1DI ®E2DI | Yes
S24 | E1<—DA1DI ®DE2 | Yes
S25 | E1<—DA1DI ®DE2DI | Yes
S26 | E1I<—A1® E2I | No
S27 | E1I<—A1® E2DI | No
S28 | E1I<—A1® DE2 | No
S29 | E1I<—A1® DE2DI | No
S30 | E1I<—A1I®E2I | Yes
S31 | E1I<—A1I®E2DI | No; requires dangling ref
S32 | E1I<—A1I®DE2 | No; requires dangling ref
S33 | E1I<—A1I®DE2DI | No; requires dangling ref
S34 | E1I<—A1DI® E2I | Yes
S35 | E1I<—A1DI® E2DI | Yes
S36 | E1I<—A1DI® DE2 | Yes; requires classref in A1 definition
S37 | E1I<—A1DI® DE2DI | Yes
S38 | E1I<—DA1® E2I | No
S39 | E1I<—DA1® E2DI | No
S40 | E1I<—DA1® DE2 | No
S41 | E1I<—DA1® DE2DI | No
S42 | E1I<—DA1DI ®E2I | Yes
S43 | E1I<—DA1DI ®E2DI | Yes
S44 | E1I<—DA1DI ®DE2 | Yes
S45 | E1I<—DA1DI ®DE2DI | Yes
S46 | E1DI<—A1® E2DI | No
S47 | E1DI<—A1® DE2 | No
S48 | E1DI<—A1® DE2DI | No
S49 | E1DI<—A1I® E2DI | No; requires dangling refs
S50 | E1DI<—A1I® DE2 | No; requires dangling refs
S51 | E1DI<—A1I® DE2DI | No; requires dangling refs
S52 | E1DI<—A1DI® E2DI | Yes
S53 | E1DI<—A1DI® DE2 | Yes; requires classref
S54 | E1DI<—A1DI® DE2DI | Yes
S55 | E1DI<—DA1® E2DI | No
S56 | E1DI<—DA1® DE2 | No
S57 | E1DI<—DA1® DE2DI | No
S58 | E1DI<—DA1DI® E2DI | Yes
S59 | E1DI<—DA1DI® DE2 | Yes
S60 | E1DI<—DA1DI® DE2DI | Yes
S61 | DE1<—A1® DE2 | No
S62 | DE1<—A1® DE2DI | No
S63 | DE1<—A1I® DE2 | No; requires dangling refs
S64 | DE1<—A1I® DE2DI | No; requires dangling refs
S65 | DE1<—A1DI® DE2 | Yes; Required by DS provider.
S66 | DE1<—A1DI® DE2DI | Yes
S67 | DE1<—DA1® DE2 | Yes
S68 | DE1<—DA1® DE2DI | No
S69 | DE1<—DA1DI® DE2 | Yes
S70 | DE1<—DA1DI® DE2 DI | Yes
S71 | DE1DI<—A1® DE2 DI | No
S72 | DE1DI<—A1I® DE2 DI | No; requires dangling ref
S73 | DE1DI<—A1DI® DE2 DI | Yes
S74 | DE1DI<—DA1® DE2 DI | No; no point in having classes point to instances
S75 | DE1DI<—DA1DI® DE2 DI | Yes


Log Files

[This is preliminary documentation and subject to change.]

Windows Management Instrumentation (WMI) and the WMI providers create log files that contain trace information and error messages. This information can be useful for resolving problems with WMI, a provider, or your client application. The log files are located in the %windir%\system32\wbem\logs directory. The log files do not contain a consistent format that is suitable for reading programmatically.

When you install WMI, the logging level for the WMI core components is set to Errors only. You can disable the logging or increase the amount of trace information that is captured by changing the logging level. You can set the logging level to Disabled or Verbose on the Logging property sheet. For more information on setting the log file properties, see the online Help for the WMI Control application.

Note You can start the WMI Control application from the Start menu by clicking Run and typing wbemcntl (in Microsoft® Windows® 95/98 and Microsoft® Windows NT® version 4.0). In Microsoft® Windows® 2000, type wmimgmt.msc.

Four of the WMI providers (Event Log Provider, SNMP Provider, View Provider, and the Directory Services Provider) use registry entries to control logging. You activate logging for these providers by setting the Logging named value to 1. The following registry key contains the Logging named value:

\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WBEM\Providers\Logging

In addition, you can modify the following named values for each provider.

Value name | Description
File | Specifies the full path and file name of the log file. The Type named value must be set to File. The default value for File is %windir%\system32\wbem\logs.
Level | Specifies a 32-bit logical mask that defines the type of debugging output generated by the provider. This value is provider dependent. The default value for Level is zero.
MaxFileSize | Specifies the maximum file size (in bytes) of the log file. This integer value must be in the range 1024 to 2^32-1. When the file size exceeds this value, the file is renamed to ~filename and a new, empty log file is created. The disk space required for the log file is twice the value of MaxFileSize. The default value for MaxFileSize is 65,535.
Type | Set to File or Debugger. If set to File, the trace information is written to the log file specified in the File named value. The default value for Type is File.

These named values are located under each provider's key. For example, the named values for the SNMP Provider are located under:

\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WBEM\Providers\Logging\WBEMSNMP

The provider keys and their named values are added to the registry when the provider is first loaded. This means you must run the provider at least once before you can modify the named values.

Note that the log files for the WMI core components and WMI providers are for WMI use only — do not write to these log files. However, you can create your own log files and keep them in the WMI log directory.

For more detail, see WMI log files.


WMI Log Files

The following table lists those log files created by WMI and the WMI providers.

Log file | Description
Dsprovider.log | The Dsprovider.log file contains trace information and error messages for the Directory Services Provider.
Framework.log | The Framework.log file contains trace information and error messages for the provider framework and the Win32 Provider.
Mofcomp.log | The Mofcomp.log file contains compilation details from the MOF compiler.
Ntevt.log | The Ntevt.log file contains trace messages from the Event Log Provider. This provider requires that you set any bit value for the mask level in the system registry.
Setup.log | The Setup.log file reports those MOF files that failed to load during the setup process. However, it does not report the error that caused the failure. You must review the Mofcomp.log file to determine the reason for the failure. After the error has been corrected, you can recompile the MOF file using the -autorecover switch.
Viewprovider.log | The Viewprovider.log file contains trace information from the View Provider based on the mask level you set in the registry.
Wbemcore.log | The Wbemcore.log file contains a wide spectrum of trace messages. For example, Wbemcore.log records login attempts as well as capturing why WMI failed to instantiate a class for a provider.
Wbemess.log | The Wbemess.log file contains log entries related to events.
Wbemprox.log | The Wbemprox.log file contains trace information for the WMI proxy server. The trace information in this file deals primarily with connectivity issues.
Wbemsnmp.log | The Wbemsnmp.log file contains trace information from the Simple Network Management Protocol (SNMP) providers.
Winmgmt.log | The Winmgmt.log file contains trace information that is typically not used for diagnostics.
Wmiadap.log | The Wmiadap.log file contains error messages related to the AutoDiscovery/AutoPurge (ADAP) process. ADAP only runs on Windows 2000 computers and is used to maintain the performance counter classes.


Dsprovider.log

[This is preliminary documentation and subject to change.]

The Dsprovider.log file contains trace information and error messages for the Directory Services Provider. This provider does not require a value for the mask level in the system registry. For details on the registry named values, see Log Files.

The following table presents some common problems that can occur and offers possible causes and solutions.

Message | Explanation and possible solution
CLDAPClassProvider::InitializeLDAPProvider ADsGetObject on RootDSE FAILED : <hresult> | The ADSI call failed while trying to get the root of your Directory Services. Ensure that your computer is part of a Windows 2000 domain.
CDSClassProvider::GetObjectAsync() GetClassFromCacheOrADSI FAILED for <class name> with <hresult> | The class you are trying to fetch is not a valid class in the directory. Ensure the class name is correct.
CLDAPInstanceProvider::PutInstanceAsync() ModifyExistingInstance FAILED for LDAP://CN=foo1,CN=Users,DC=dsprovider,DC=nttest,DC=Microsoft,DC=com with <hresult> | Unable to write a modified instance to Directory Services. Ensure that you are using the IWbemContext interface to specify the set of properties that you are modifying. For more information on how to use the IWbemContext interface with PutInstance, see Updating an Instance.
CLDAPHelper::GetADSIInstance ADsOpenObject() FAILED on <class name> with <hresult> CLDAPInstanceProvider::GetObjectAsync : GetADSIInstance() FAILED with <hresult> CLDAPInstanceProvider::GetObjectAsync() FAILED for ds_user.ADSIPath="<class name>" | These three messages indicate that the instance you are trying to get does not exist in the directory service. Ensure the ADSIPath and class name are correct.

For more information on the WMI HRESULT contained in the log entry, see WMI Error Constants. You can use the error lookup feature in Microsoft® Visual C++® to determine the error messages for other HRESULT values, such as ADSI errors.


Framework.log

[This is preliminary documentation and subject to change.]

The framework.log file contains trace information and error messages for the provider framework and the Win32 Provider.

Set the logging level to verbose to receive detailed logging. This also helps you verify that your framework provider is being called by the provider framework. If the log file does not contain entries for your provider, then your provider is not registered correctly.

The following table presents some common problems that can occur and offers possible causes and solutions.

Message | Explanation and possible solution
Impersonation failed | The client must connect with an authentication level of Impersonate or Delegate.
Failed: Invalid class name | The namespace specified in the static constructor for your class is incorrect. See the declaration of MyReindeerProvSet in the FrameworkProv sample. The sample is located in the Wmi\Samples directory.
ERROR CInstance(<class name>)::SetCHString(<property name>) FAILED!error# <hresult> | This is the most common log entry. For example, the following message tells you that the provider framework was unable to set the AdapterCompatibility property. The HRESULT indicates that the AdapterCompatibility property was not found in the Win32_DesktopMonitor class. ERROR CInstance(Win32_DesktopMonitor)::SetCHString(AdapterCompatibility) FAILED!error# 80041002

For more information on the HRESULT contained in the log entry, see WMI Error Constants.


Mofcomp.log

[This is preliminary documentation and subject to change.]

The Mofcomp.log file contains compilation details from the MOF compiler. The compiler writes two messages to the log when it compiles your MOF file. The first entry identifies the MOF file that is being compiled. The second entry shows that the compiler successfully parsed and committed your MOF entries in CIMOM, or that a syntax or WMI error occurred.

Note that the compiler returns on the first error it encounters.

The log entries for syntax errors identify the line number where the error occurred and provide a brief description of the error. For example, the following log entry shows that an illegal constant value was specified on line 15 of the MOF file:

carpool.mof (15) : error SYNTAX 0X006c: Illegal constant value. (Numeric value out of range or strings without quotes)

For more information on a particular syntax issue, see Managed Object Format (MOF) Language.

When the MOF file is syntactically correct, the compiler attempts to commit your MOF entries in CIMOM. If an error occurs, the compiler logs an entry that contains the WMI HRESULT value and a brief description of the error. The description also contains the line number of the object that failed. For example, the following log entry shows that object 2 of the MOF file contains a type mismatch:

An error occurred while creating object 2 defined on lines 9 - 15: 0X80041005: The value specfied for property 'parentnodekey' conflicts with the declaration of the property.

For more information on the WMI HRESULT contained in the log entry, see WMI Error Constants.


Viewprovider.log

[This is preliminary documentation and subject to change.]

The Viewprovider.log file contains trace information from the View Provider based on the mask level you set in the system registry. For details on the registry named values, see Log Files.

The following table lists the four logging levels that you can set for the View Provider.

Bit | Type of logging
0 (rightmost bit) | Logs Winmgmt.exe calls.
1 | Logs query and get instance calls.
2 | Logs put instance calls.
3 | Logs method calls.


Wbemcore.log

[This is preliminary documentation and subject to change.]

The Wbemcore.log file contains a wide spectrum of trace messages. For example, it records login attempts as well as capturing why WMI failed to instantiate a class for a provider.

The following table presents some common problems that can occur and offers possible causes and solutions.

Message | Explanation and possible solution
DCOM connection from <client name> at authentication level %s, Authnsvc = %d, Authzsvc = %d, Capabilities = %d | You must have the logging level set to verbose to receive this log message. This message indicates which credentials and RPC values were used to connect to WMI. This can be useful when Wbemprox.log contains a connection failure message that was due to bad credentials.
Error <wmi hresult> occurred executing queued request | This log entry is followed by additional details that provide specific trace information for the related WMI HRESULT.
Failed to CoGetClassObject for provider <provider name> error code 0x<COM error number> (<a short explanation>) | There are many reasons why WMI may not be able to instantiate the class. The short explanation appended to the message provides information to help identify the error. This message is also logged in the NT Event log and contains additional information that may be useful.

For more information on the WMI HRESULT contained in the log entry, see WMI Error Constants. You can use the error lookup feature in Visual C++ to determine the error messages for other HRESULT values, such as COM or RPC errors.


Wbemess.log

[This is preliminary documentation and subject to change.]

The Wbemess.log file contains all warning and error messages related to the WMI event subsystem. Those errors that require administrator attention are also logged in the NT Event log.

Note that warning messages are only logged in the Wbemess.log file when the logging level has been set to verbose.

The following table presents some common problems that can occur and offers possible causes and solutions.

Message | Explanation and possible solution
Skipping provider <provider name> invalid registration query <query>. | The query cannot be parsed. Run the query in CIM Studio to determine why the query cannot be parsed.
Consumer provider <provider name> does not support <interface name> interface. | This warning message is only logged when the logging level has been set to verbose.
Attempting to register for events (<query>) from an incompletely registered provider '<provider name'>. | A provider registration error occurred or one of the event registration pieces is missing. Ensure that all event registration components are in place.


Wbemprox.log

[This is preliminary documentation and subject to change.]

The Wbemprox.log file contains trace information for the WMI proxy server. The trace information in this file primarily pertains to connectivity issues.

The following table presents some common problems that can occur and offers possible causes and solutions.

Message | Explanation and possible solution
ConnectViaDCOM, CoCreateInstanceEx resulted in hr = 0x800706ba This is a WMI connection error that you receive for one of the following reasons:
  • Incorrect server is specified
  • Incorrect credentials
  • Environment error, such as the RPC server is unavailable
  • Connecting to a Windows 95/98 computer that does not have Winmgmt.exe running.
NTLMLogin resulted in hr = 0x8004103 : Access denied was returned, giving up! | The most common HRESULT from this message indicates that you do not have permission to perform the action. The second-most common HRESULT indicates that an incorrect namespace was specified or that the namespace does not exist. It is also possible to get various RPC errors returned with this message.

For more information on the WMI HRESULT contained in the log entry, see WMI Error Constants. You can use the error lookup feature in Visual C++ to determine the error messages for other HRESULT values.


Winmgmt.log

[This is preliminary documentation and subject to change.]

The Winmgmt.log file contains trace information that is typically not used for diagnostics. The two most common entries are shown next. The first example shows that the core was successfully shut down and a WMI HRESULT of 0 was returned. The second example returns a non-zero WMI HRESULT, which indicates that the program was unable to shut down the core because the program was still in use.

  • Core is being shut down by WinMgmt.exe; it returned 0x0
  • Core is being shut down by WinMgmt.exe; it returned 0x80041001

For more information on the WMI HRESULT contained in the log entry, see WMI Error Constants.


Wmiadap.log

[This is preliminary documentation and subject to change.]

The Wmiadap.log file contains error messages related to the AutoDiscovery/AutoPurge (ADAP) process. The ADAP process maintains the WMI performance counter classes on Windows 2000 computers.

ADAP also writes error messages to the Nt Event log to alert the system administrator that the performance library has failed to load. The error messages contained in the NT Event log are generic messages that indicate a problem occurred, while the Wmiadap.log file contains trace information that indicates why the problem occurred. For example, the NT Event log might contain the following message:

WMI ADAP was unable to process the performance libraries: 0xXXX

The corresponding trace information, found in the Wmiadap.log file, would be:

CAdapRegPer::EnumPerfDlls() failed: 0xXXX

The following table presents some common problems that can occur and offers possible causes and solutions.

Message | Explanation and possible solution
CAdapRegPer::EnumPerfDlls() failed: 0xXXX | This message can occur when the name's database does not exist or is corrupted. The name's database must exist for language identifier 409 (English) in the system registry (HKEY_LOCAL_MACHINE\SOFTWARE\MICROSOFT\WindowsNT\CurrentVersion\Perflib). In addition, the CIMV2 namespace must exist and contain the CIM_StatisticalInformation class. Note that if the PerfOS performance library has been deactivated, the name's database will appear to be corrupted.
Performance library status is corrupt. | This message can occur when a performance library throws an exception, corrupts memory, has three consecutive time-outs, or some other unexpected behavior that prevents ADAP from collecting the performance data. When these errors occur, ADAP sets the WbemAdapStatus value in the Performance subkey to 0xFFFFFFFF (-1). ADAP does not process the library until the library is upgraded.
All other trace information. | These messages indicate a problem with the performance library. The NT Event log message associated with this trace information, identifies the performance library and describes the fault. Typically, you will receive these messages before you receive a Performance library status is corrupt message.


WMI Add-Ons

[This is preliminary documentation and subject to change.]

The Windows Management Instrumentation (WMI) SDK is designed for those who create software that uses WMI to automate management tasks, such as extracting management information or acting upon such information. In an on going committment to make WMI easier to use and integrate into the customer's environment and applicaitons, additional components will be included in the Add-Ons in the future.

The following sections cover the areas of functionality for the WMI Add-Ons.

  • Standard Consumers
  • XML Adapter
  • Event Correlator


Standard Consumers

[This is preliminary documentation and subject to change.]

The standard consumers of Windows Management Instrumentation (WMI) makes available a series of standard consumer classes.

The standard consumers permit the user to specify an action to take when a specific condition (a subscribed to WMI event) occurs. These actions include sending an e-mail, running a script, adding information to the Event Log file, and executing a command. Currently, the actions currently supported are executing a script and sending an e-mail.

The standard consumers include the following classes:

  • ActiveScriptEventConsumer
  • SMTPEventConsumer


Using the Standard Consumers

[This is preliminary documentation and subject to change.]

The following list describes the steps necessary to use the standard event consumers provided by the WMI add-on collection:

  1. The customer creates a named instance of __EventFilter to specify which events should trigger the action to be taken.
  2. The customer creates a named instance of the logical consumer class for the desired action (For example, SMTPEventConsumer) to specify the parameters of the action to be taken.
  3. The customer creates an instance of __FilterToConsumerBinding association that binds the previously mentioned instances together indicating that when events matching the specified filter occur, the specified action must be taken.
  4. The customer may bind one filter to several consumers, indicating that when matching events occur, several actions must be taken.
  5. The customer may bind one consumer to several filters, indicating that the action must be taken whenever events matching any one of the filters occur.

For detailed information on how to use permanent event consumers in WMI see Permanent Event Consumers.


Standard Templates

[This is preliminary documentation and subject to change.]

Standard templates are useful for use with many of the standard consumers. You can use a template to construct a string that is partially configured in the consumer instance and partially derived from the event in question. The template language is similar to the Windows NT environment variable specification.

The following list shows some examples of the template language:

  • The string "Some text here" always produces the string "Some text here".
  • "%CPUUtilization%" always produces the value of the CPUUtilizaiton property of the event being delivered. If the property is not a string, it is converted to a string; for example, "90" or "TRUE".
  • "The CPU utilization of my processor is %CPUUtilization% at this time" embeds the value of the CPUUtilization property of the event into the string, producing something like, "The CPU utilization of my processor is 90 at this time."
  • "%TargetInstance.CPUUtilization%" retrieves the value of the CPUUtilization property in the embedded instance of the TargetInstance property.
  • "%%" produces a single % sign.
  • If the property being retrieved is an array, the entire array is produced in the following format: "(1,5,10,1024)". If there is only one element in the array, the parentheses are omitted. If there are no elements in the array, "()" is produced.
  • If a property is an embedded object, the MOF representation of the object is produced (similar to the IWbemClassObject::GetObjectText method).
  • If a property of an embedded array of objects is requested, it is treated as a property with an array value. For example: %MyEvents.TargetInstance.DriverLetter% could produce '("C:","D:")' if MyEvents is an array of embedded instance modification events.

Whenever a property of a consumer class is interpreted to be a template in accordance with the above rules, it is marked with a [template] qualifier.


Security and Availability

[This is preliminary documentation and subject to change.]

Most of the standard event consumers are implemented as DLLs. Due to its inherent dangers, the scripting consumer will always run out-of-process.

All of the standard consumers run in the Local System security context.

Instances of these consumers can be created or modified only by the members of the local Administrators group.

Both ActiveScriptConsumer and SMTPEventConsumer are available on Microsoft® Windows® 95, Microsoft® Windows® 98, Microsoft® Windows® 2000, and Microsoft® Windows NT®.


Error Reporting

[This is preliminary documentation and subject to change.]

Whenever the action designated by a consumer fails to execute, WMI generates a __ConsumerFailureEvent event. Clients that require this information can register to receive these events or can perform specific actions upon receipt of the event. The meaning of failure is specified in the documentation of each consumer type. No events are raised when __ConsumerFailureEvent is not delivered.


Standard Consumer Reference

[This is preliminary documentation and subject to change.]

The following lists the reference topics for standard consumers:

  • ActiveScriptEventConsumer
  • SMTPEventConsumer


ActiveScriptEventConsumer

[This is preliminary documentation and subject to change.]

The ActiveScriptEventConsumer class executes a predefined script in an arbitrary scripting language whenever an event is delivered to it.

class ActiveScriptEventConsumer : __EventConsumer
{
  [key] string Name;
  [not_null] string ScriptingEngine;
  [template] string ScriptText;
  string ScriptFileName;
  [units("seconds")] uint32 KillTimeout;
};

Properties

The following table lists the properties for ActiveScriptEventConsumer.

Property | Data type | Description
Name | string | Key property. A unique identifier of the event consumer.
ScriptingEngine | string | Name of the scripting engine to use. For example: "VBScript" or "JScript". This property may not be NULL.
ScriptText | string | Template containing the text of the script to execute. If NULL the ScriptFileName is used.
ScriptFileName | string | The name of the file from which the script text is read. This property is ignored unless ScriptText is NULL.
KillTimeout | uint32 | The number of seconds after which the script will be terminated if it isn't already finished. If zero the script will not be terminated. Applies only to scripts specified in the ScriptText property.

Remarks

The ActiveScriptEventConsumer class is derived from the abstract __EventConsumer class.

While the text of the script is specified in the event consumer instance, the script has access to the event instance in the script environment variable TargetEvent.

The scripts execute in the security context of LocalSystem. As a security measure to prevent abuse, only a local system administrator or a domain administrator may configure the Scripting Consumer. Access rights are not checked until runtime. Once the consumer is configured, any user may trigger the event that causes the script to execute.

Failure to load the scripting engine or parse and validate the script is considered a failure. Error return codes from the script, and terminating the script via a timeout are also considered failures.

Note Exactly one of the two properties, ScriptText and ScriiptFileName, must be non-NULL. If both properties are NULL or both properties are non-NULL an error is generated.

Example Code

The following VBScript example brings up a message box with the drive letter of the event:

MsgBox TargetEvent.TargetInstance.DriveLetter

See Also

Permanent Event Consumers, Permanent Consumer Architecture, Creating a New Consumer Class, Creating a Logical Consumer, __EventConsumer


SMTPEventConsumer

[This is preliminary documentation and subject to change.]

The SMTPEventConsumer sends an e-mail message via SMTP each time an event is delivered to it. An SMTP server must exist on the network. SMTPEventConsumer does not support attachments.

Receiving an error return code from the SMTP service is considered a failure.

class SMTPEventConsumer : __EventConsumer
{
  [key] string Name;
  [template] string Subject;
  [template] string Message;
  [template] string ToLine;
  [not_null] string SMTPServer;
  string CcLine;
  string BccLine;
};

Properties

The following table lists the properties for SMTPEventConsumer.

Property | Data type | Description
Name | string | Key property. A unique identifier of the event consumer.
Subject | string | Template containing the subject of the e-mail message.
Message | string | Template containing the body of the e-mail message.
ToLine | string | A comma or semi-colon separated list of addresses where the message is to be sent. See note below.
SMTPServer | string | The name of the SMTP server through which the e-mail is to be sent. Permissible names are an IP address, or a DNS or NetBIOS name. This property may not be NULL.
CcLine | string | A semi-colon separated list of addresses to Cc. See note below.
BccLine | string | A semi-colon separated list of addresses to Bcc. See note below.

Note Any of the toLine, ccLine or bccLine properties may be NULL, but they may not all be NULL.

Remarks

The SMTPEventConsumer class is derived from the abstract __EventConsumer class.

See Also

Permanent Event Consumers, Permanent Consumer Architecture, Creating a New Consumer Class, Creating a Logical Consumer


XML Adapter

[This is preliminary documentation and subject to change.]

The XML Adapter allows WMI users to acces XML representations of WMI objects based upon version 2.0 of the Desktop Management Task Force (DMTF) XML DTD for CIM.

The XMLAdapter is currently in beta version and available through the Resource Kit and by download from http://someUrlGoesHere.


Event Correlator

[This is preliminary documentation and subject to change.]

Event filters run sophisticated queries on events, but they do not carry any state. An event correlator and aggregator can look for the presence or absence of events within a time window for more sophisticated evaluation of the state of affairs. This provides greater effieiency because it can filter out many events and trigger an event consumer only when a sequance or sequences of events have occurred.

The Event Correlator is currently in beta version and available through the Resource Kit and by download from http://someUrlGoesHere.


WMI Reference

Windows Management Instrumentation (WMI) provides access to information about objects in a managed environment. Through WMI and the WMI application programming interface (API), applications can query for and make changes to static information in the Common Information Model (CIM) repository and dynamic information maintained by the various types of providers.

The WMI Reference contains the following sections discussing core features of WMI.

Section | Description
WMI System Classes | Complete listing of the classes defined by WMI.
WMI System Properties | Complete listing of the properties supported by WMI.
WMI Standard Qualifiers | Complete listing of the qualifiers supported by WMI.
Provider Framework Classes | Includes CInstance Class Methods, Provider Class Methods, CFrameworkQuery Class Methods, and CWbemProviderGlue Class Methods.
Provider Framework Utility Classes | Includes WBEMTime Class Methods, and WBEMTimeSpan Class Methods.
COM API for WMI | Complete listing of the COM interfaces that are used by C and C++ management applications and providers to access WMI.
Scripting API for WMI | Complete listing of the components of the WMI scripting API. This reference provides information for developers who are writing applications using the Microsoft Visual Basic development system, Microsoft Visual Basic for Applications, Microsoft Visual Basic Scripting Edition (VBScript), and Microsoft JScript development software.
ActiveX Controls for WMI | Includes WMI Class Navigator, WMI Provider Wizard, WMI EventList, WMI Event Registration, WMI MOF Compiler Wizard, WMI MOF Generator Wizard, WMI Multiple Instances Viewer, WMI Namespace Picker, WMI Instance Navigator, WMI Login, WMI Object Viewer, and WMI Object Viewer Container.
WMI Utility Classes | Reference material for CHString, CHStringArray, and TRefPointerCollection.
SQL for the WMI ODBC Adapter | Alphabetical listing of the supported WMI ODBC functions.
MOF Compiler | Description of the command-line syntax used by the Managed Object Format (MOF) compiler.
Backus Naur Form Syntax | Description of the BNF syntax for MOF, Structured Query Language version 1 (SQL1), and object paths.
SNMP Compiler Error Messages | Description of the various error conditions that can result when the SNMP information module compiler parses a MIB module.
WMI Symbolic Constants | Descriptions and values for the WMI error and non-error constants.
WMI Glossary | Contains definitions to be read carefully so you understand what is meant when these terms occur in the WMI SDK documentation.
WMI Command-Line Syntax | Description of the syntax used by the WMI executable file, Winmgmt.exe.
Wbemdump | WMI application that can show CIM classes and instances, execute the methods of a CIM object, or run queries.


WMI System Classes

The Windows Management Instrumentation (WMI) system classes are a collection of predefined classes based on the Common Information Model (CIM) and included in every namespace in the WMI Core. Objects spawned from the system classes are used to support activities of WMI, such as event and provider registration, security, and event notification. Some of these objects are temporary; others are stored in the repository as instances of the system classes. System classes, such as event registration and notification, provider registration, and security, are used to support the activities of WMI.

System classes follow a naming convention that consists of a double-underscore (__) followed by the class name. Because the double-underscore is a sequence reserved for system use, developers cannot create their own classes that begin with this sequence.

All system classes derive from the abstract base class __SystemClass. Although only the system classes can derive directly from __SystemClass, developers can create classes that derive from the system classes.

Note You can derive classes from some, but not all system classes.

The documentation for each of the system classes includes only the non-system local properties. Links are available with each class definition to allow the reader to quickly and easily navigate the class hierarchy.

System Classes You Can Use as Base Classes

Only the following system classes can serve as base classes for your derived classes.

System class | Description
__EventConsumer | Creates new consumer types.
__ExtendedStatus | Creates new error object types.
__ExtrinsicEvent | Creates new event types.
__Namespace | Used by the SNMP provider to create its namespaces.
__Win32Provider | Registers information about a provider's physical implementation with WMI.

System Classes You Cannot Use as Base Classes

The following system classes must not be used as base classes for your derived classes.

System class | Description
__AbsoluteTimerInstruction | Causes an event to be generated on a specific date at a specific time.
__ADAPStatus | Reports the current status of the AutoDiscovery/AutoPurge (ADAP) process. This process collects and maintains performance counter objects in WMI.
__AggregateEvent | Represents an aggregate event, which is an event that summarizes several individual intrinsic or extrinsic events.
__CacheControl | Base class for classes used to determine when WMI should release a Component Object Model (COM) object.
__CIMOMIdentification | Describes the particular installation of WMI.
__ClassCreationEvent | Represents a class creation event.
__ClassDeletionEvent | Represents a class deletion event.
__ClassModificationEvent | Represents a class modification event.
__ClassOperationEvent | Base class for all intrinsic events that relate to a class.
__ClassProviderRegistration | Registers class providers with WMI.
__ConsumerFailureEvent | Represents the occurrence of some other event being dropped due to a failure on the part of an event consumer.
__Event | Abstract base class that serves as the superclass for all intrinsic and extrinsic events.
__EventConsumerProviderCacheControl | Used to determine when WMI should release an event consumer provider.
__EventConsumerProviderRegistration | Registers event consumer providers with WMI.
__EventDroppedEvent | Represents the occurrence of some other event being dropped (as opposed to being delivered to an event consumer).
__EventFilter | Used by event consumers to register for particular types of events.
__EventGenerator | Abstract base class that serves as a superclass for classes that generate events, such as timer events, that are not based on classes or instances.
__EventProviderCacheControl | Used to control when an event provider is unloaded.
__EventProviderRegistration | Registers event providers with WMI.
__EventQueueOverflowEvent | Represents an event raised when an event is dropped as a result of delivery queue overflow.
__EventSinkCacheControl | Used to determine when WMI should release an event consumer provider's IWbemUnboundObjectSink pointer.
__FilterToConsumerBinding | Association class that relates an instance of the __EventConsumer system class to an instance of the __EventFilter system class.
__IndicationRelated | Abstract base class that serves as a superclass for all event-related classes.
__InstanceCreationEvent | Represents an instance creation event.
__InstanceDeletionEvent | Represents an instance deletion event.
__InstanceModificationEvent | Represents an instance modification event.
__InstanceOperationEvent | Base class for all intrinsic events that relate to an instance.
__InstanceProviderRegistration | Registers instance providers with WMI.
__IntervalTimerInstruction | Used to generate events at intervals.
__MethodProviderRegistration | Registers method providers with WMI.
__NamespaceCreationEvent | Represents a namespace creation event.
__NamespaceDeletionEvent | Represents a namespace deletion event.
__NamespaceModificationEvent | Represents a namespace modification event.
__NamespaceOperationEvent | Base class for all intrinsic events that relate to a namespace.
__NotifyStatus | Abstract base class that can serve as the superclass for provider-defined error classes.
__ObjectProviderCacheControl | Used to control when a provider is unloaded.
__NTLMUser9X | Used to allow remote access to a Microsoft Windows 95/98 computer.
__ObjectProviderRegistration | Abstract base class that serves as the superclass for classes used to register class and instance providers with WMI.
__PARAMETERS | Abstract class used to define methods and to pass input and output arguments to a method provider.
__PropertyProviderCacheControl | Used to control the cache when a property provider is unloaded.
__PropertyProviderRegistration | Registers property providers with WMI.
__Provider | Abstract base class that serves as the superclass for the __Win32Provider system class.
__ProviderRegistration | Abstract base class that serves as the superclass for registration classes for various types of providers.
__SecurityRelatedClass | Abstract base class that serves as a superclass for all types of security classes.
__SystemClass | Abstract base class from which all system classes derive.
__SystemEvent | Represents a system event.
__SystemSecurity | Used to manage WMI security on Microsoft Windows NT and Windows 2000 systems.
__TimerEvent | Represents an event generated by WMI in response to a consumer's request for an interval timer event or an absolute timer event.
__TimerInstruction | Abstract base class for classes used to specify instructions on how timer events should be generated for consumers.
__TimerNextFiring | Reserved class.


__AbsoluteTimerInstruction

The __AbsoluteTimerInstruction system class causes an event to be generated on a specific date at a specific time. An event consumer registers to receive an absolute timer event by creating an instance of this class. The event is generated only once.

class __AbsoluteTimerInstruction : __TimerInstruction
{
  [not_null: DisableOverride ToInstance ToSubClass] datetime EventDateTime;
};

Properties

The following table lists the properties for __AbsoluteTimerInstruction.

Property | Data type | Description
EventDateTime | datetime | Fixed-length string in DMTF format that specifies when the timer should fire.
TimerId | string | Unique user-assigned string that identifies this particular timer event. To avoid naming conflicts with other timer identifiers, the string form of a distributed computer environment (DCE)-style GUID can be used. This property is inherited from class __TimerInstruction.
SkipIfPassed | boolean | Indicates whether the timer event occurs if WMI is unavailable to generate it at the appropriate time interval, or the consumer requesting to receive the event is unavailable. If TRUE, the event will not occur. The default is FALSE. Once WMI or the consumer becomes available again, a notification event will be generated and received. This property is inherited from __TimerInstruction.

Remarks

The __AbsoluteTimerInstruction class is derived from the __TimerInstruction class.

WMI generates the absolute timer event by creating an instance of the __TimerEvent class.

Consumers register for an absolute timer event by specifying an identifier for the event in the TimerId property and a date and time for the event to fire in the EventDateTime property.

See Also

Timer Events, System Classes You Cannot Use as Base Classes


__ADAPStatus

[This is preliminary documentation and subject to change.]

The __ADAPStatus system class reports the current state of the AutoDiscovery/AutoPurge (ADAP) process on Microsoft Windows 2000 computers.

[singleton]
class __ADAPStatus : __SystemClass
{
  uint32 Status;
  datetime LastStartTime;
  datetime LastStopTime;
};

Properties

The following table lists the properties for __ADAPStatus.

Property | Data type | Description
Status uint32 Defines the current state of the ADAP process.
  • Values are:
  • 0 = Process has never run on this computer.
  • 1 = Process is currently running.
  • 2 = Process is processing a performance library.
  • 3 = Process is updating and committing changes to WMI.
  • 4 = Process has finished.
LastStartTime | datetime | Last time the ADAP process started.
LastStopTime | datetime | Last time the ADAP process completed.

Remarks

The __ADAPStatus class is derived from __SystemClass, which has no properties.

You can use this class to see whether the ADAP process has run on the computer, the last time the ADAP ran, or if the ADAP process is currently running. This can help you determine the current state of the performance counters in WMI.

The __ADAPStatus system class is installed in the Root\Default namespace.

See Also

Performance Counters Provider


__AggregateEvent

The __AggregateEvent system class represents an aggregate event, which is an event that summarizes several individual intrinsic or extrinsic events. WMI generates one aggregate event __AggregateEvent when consumers register with the GROUP WITHIN clause in their event query.

class __AggregateEvent : __IndicationRelated
{
  uint32 NumberOfEvents;
  object Representative;
};

Properties

The following table lists the properties for __AggregateEvent.

Property | Data type | Description
NumberOfEvents | uint32 | Number of events combined to produce this single summary event.
Representative | object | Copy of one of the events delivered within the aggregation interval. For example, if a consumer has registered for registry key change events from the Registry Event Provider, Representative would hold an instance of the RegistryKeyChangeEvent class.

Remarks

The __AggregateEvent class is derived from __IndicationRelated, which has no properties.

Event providers never generate aggregate events. They must ignore the GROUP WITHIN clause in their processing of event queries.

See Also

Event Queries, System Classes You Cannot Use as Base Classes


__CacheControl

The __CacheControl system class is the base class for classes used to determine when WMI should release a Component Object Model (COM) object. Instances of this class are never created. The __CacheControl class is located only in the Root namespace. See Unloading a Provider for more information about using this class.

[abstract]
class __CacheControl : __SystemClass
{
};

Properties

None.

See Also

__EventConsumerProviderCacheControl, __EventProviderCacheControl, __EventSinkCacheControl, __ObjectProviderCacheControl, __PropertyProviderCacheControl, Unloading a Provider.


__CIMOMIdentification

The __CIMOMIdentification system class describes the particular installation of WMI. This is a singleton class; there is only one instance. The __CIMOMIdentification class is available only in the Root and Root\Default namespaces. Users query for the instance to obtain information about the WMI installation.

[singleton]
class __CIMOMIdentification : __SystemClass
{
  string SetupDate;
  string SetupTime;
  string VersionCurrentlyRunning;
  string VersionUsedToCreateDB;
};

Properties

The following table lists the properties for __CIMOMIdentification.

Property | Data type | Description
SetupDat e | string | A string in the Distributed Management Task Force (DMTF) format indicating the date of installation. See Date and Time Format for detailed information on the DMTF date and time format.
SetupTime | string | A string in DMTF format indicating the time the setup occurred on the date specified by SetupDate. See Date and Time Format for detailed information on the DMTF date and time format.
VersionCurrentlyRunning | string | Indicates the version of the actual WinMgmt.exe image that created the Common Information Model (CIM) repository. Because the repository format may change between versions of WMI, this property allows future WMI upgrades to determine whether the database needs to be upgraded. The format is: "1.00.183.0000".
VersionUsedToCreateDB | string | Indicates the version of the actual WinMgmt.exe image that created the Common Information Model (CIM) repository. Because the repository format may change between versions of WMI, this property allows future WMI upgrades to determine whether the database needs to be upgraded. The format is: "1.00.183.0000" where the first digit is the major version, the next two digits are minor versions, and the next three digits are the build number. The remaining digits are not used.

Remarks

The __CIMOMIdentification class is derived from __SystemClass, which has no properties.

See Also

System Classes You Cannot Use as Base Classes


__ClassCreationEvent

The __ClassCreationEvent system class represents a class creation event, which is a type of intrinsic event generated when a new class is added to the namespace.

class __ClassCreationEvent : __ClassOperationEvent
{
};

Properties

The following table lists the properties for __ClassCreationEvent.

Property | Data type | Description
TargetClass | object | Contains a copy of the newly-created class affected by the event. This property is inherited from __ClassOperationEvent.

Remarks

The __ClassCreationEvent class is derived from __ClassOperationEvent.

See Also

System Classes You Cannot Use as Base Classes


__ClassDeletionEvent

The __ClassDeletionEvent system class represents a class deletion event, which is a type of intrinsic event generated when a class is removed from the namespace.

class __ClassDeletionEvent : __ClassOperationEvent
{
};

Properties

The following table lists the property for __ClassDeletionEvent.

Property | Data type | Description
TargetClass | object | Contains a copy of the newly-created class affected by the event. This property is inherited from __ClassOperationEvent.

Remarks

The __ClassDeletionEvent class is derived from __ClassOperationEvent.

See Also

System Classes You Cannot Use as Base Classes


__ClassModificationEvent

The __ClassModificationEvent system class represents a class modification event, which is a type of intrinsic event generated when a class is changed in the namespace.

class __ClassModificationEvent : __ClassOperationEvent
{
  object PreviousClass;
};

Properties

The following table lists the properties for __ClassModificationEvent.

Property | Data type | Description
PreviousClass | object | Contains a copy of the original version of the class.
TargetClass | object | Contains a copy of the newly-created class affected by the event. This property is inherited from __ClassOperationEvent.

Remarks

The __ClassModificationEvent class is derived from __ClassOperationEvent.

The event reports both the new and old versions of the class definition.

See Also

System Classes You Cannot Use as Base Classes


__ClassOperationEvent

The __ClassOperationEvent system class is a base class for all intrinsic events that relate to a class.

class __ClassOperationEvent : __Event
{
  object TargetClass;
};

Properties

The following table lists the property for __ClassOperationEvent.

Property | Data type | Description
TargetClass | object | Class affected by the event. For creation events, this is the newly created class. For modification events, this is the new version of the changed class. For deletion events, this is the deleted class.

Remarks

The __ClassOperationEvent class is derived from __Event.

Instances of __ClassOperationEvent are not created; only instances of its subclasses are created. The following classes derive from __ClassOperationEvent:

__ClassCreationEvent

__ClassModificationEvent

__ClassDeletionEvent

See Also

Intrinsic and Extrinsic Events, System Classes You Cannot Use as Base Classes


__ClassProviderRegistration

The __ClassProviderRegistration system class registers class providers with WMI.

class __ClassProviderRegistration : __ObjectProviderRegistration
{
  [key] __Provider ref provider;
  string ResultSetQueries[];
  string ReferencedSetQueries[];
  string UnsupportedQueries[];
};

Properties

The following table lists the properties for __ClassProviderRegistration.

Property | Data type | Description
provider | __Provider ref | Key property. Specifies the the object path to the class provider. This property is inherited from __ProviderRegistration.
ReferencedSetQueries | string | One or more queries that describe the set of referenced classes that the class provider supports. Providers that can supply association classes must include at least one query in their ReferencedSetQueries property.
ResultSetQueries | string | One or more queries that describe either the set of all classes that can be supplied by the class provider or a superset of those classes. ResultSetQueries never specifies a subset of supported classes.
UnsupportedQueries | string | One or more queries that describe the set of classes that the class provider does not support. Use the UnsupportedQueries property to subtract from the set of classes implied by ResultSetQueries.

Remarks

The __ClassProviderRegistration class is derived and inherits several properties from its superclasses in the class hierarchy: __ObjectProviderRegistration, and__ProviderRegistration.

The __ObjectProviderRegistration properties indicate whether the class provider supports data retrieval, modification, deletion, enumeration and query processing. One property, InteractionType, specifies whether the class provider is designed as a pull or push provider. For more information about provider models, see Pull and Push Providers.

The __ProviderRegistration class defines the Provider property.

See Also

Registering Class and Instance Providers, System Classes You Cannot Use as Base Classes


__ConsumerFailureEvent

The __ConsumerFailureEvent system class represents the occurrence of some other event being dropped due to a failure on the part of an event consumer.

class __ConsumerFailureEvent: __EventDroppedEvent
{
  uint32 ErrorCode;
  string ErrorDescription;
};

Properties

Property | Data type | Description
ErrorCode | uint32 | Error code returned by the consumer.
ErrorDescription | string | Extended error code description (if available).

Remarks

The __ConsumerFailureEvent class is derived from __EventDroppedEvent.


__Event

The __Event system class is an abstract base class that serves as the superclass for all intrinsic and extrinsic events. All new event types must ultimately derive from __Event. Intrinsic events derive directly from this class. User-defined extrinsic events derive from a subclass of this class called __ExtrinsicEvent.

[abstract: DisableOverride ToInstance ToSubClass]
class __Event : __IndicationRelated
{
};

Properties

None.

Remarks

The __Event class is derived from __IndicationRelated, which has no properties.

See Also

Intrinsic and Extrinsic Events, Event Notification, __ClassOperationEvent, __InstanceOperationEvent, __NamespaceOperationEvent, System Classes You Cannot Use as Base Classes


__EventConsumer

The __EventConsumer system class is an abstract base class that serves as the superclass for new event consumer classes. An instance of a new event consumer class is known as a logical consumer.

[abstract]
class __EventConsumer : __IndicationRelated
{
  string MachineName;
  [units("bytes"): DisableOverride ToInstance ToSubClass] uint32 MaximumQueueSize;
  [read: DisableOverride ToInstance ToSubClass] uint8 CreatorSID[] = {1, 1, 0, 0, 0, 0, 0, 5, 18, 0, 0, 0};
};

Properties

The following table lists the properties for __EventConsumer.

Property | Data type | Description
MachineName | string | Name of the computer on which the event consumer class resides.
MaximumQueueSize | uint32 | Maximum queue in bytes) for this particular consumer.
CreatorSID | uint8[] | Security identifier that uniquely identifies the user who created this filter. This is a read-only property.

Remarks

The __EventConsumer class is derived from __IndicationRelated, which has no properties.

Permanent consumers define new consumer classes to describe an action to be taken and data to be processed when they receive event notifications.

See Also

Permanent Consumer Architecture, Creating a New Consumer Class, Creating a Logical Consumer, System Classes You Can Use as Base Classes


__EventConsumerProviderCacheControl

The __EventConsumerProviderCacheControl system class is used to determine when WMI should release an event consumer provider. The __EventConsumerProviderCacheControl class is a singleton class. It is located only in the Root namespace.

class __EventConsumerProviderCacheControl : CacheControl
{
  CIM_DATETIME ClearAfter;
};

Properties

The following table lists the property for __EventConsumerProviderCacheControl.

Property | Data type | Description
ClearAfter | CIM_DATETIME | Number of seconds after which WMI should release an event consumer provider. The time is in DMTF format. For detailed information on the DMTF date and time format, see Date and Time Format.

Remarks

The __EventConsumerProviderCacheControl class is derived from __CacheControl. See Unloading a Provider for more information about using this class.


__EventConsumerProviderRegistration

The __EventConsumerProviderRegistration system class registers event consumer providers with WMI.

class __EventConsumerProviderRegistration : __ProviderRegistration
{
  [key] __Provider ref provider;
  [key] string ConsumerClassNames[];
};

Properties

The following table lists the properties for __EventConsumerProviderRegistration.

Property | Data type | Description
ConsumerClassNames | string | Key property. Enumerated data type. Specifies the name of the logical consumer classes that the event consumer provider supports..
provider | __Provider ref | Key property. Specifies the object path to the provider. This property is inherited from __ProviderRegistration.

Remarks

The __EventConsumerProviderRegistration class is derived from __ProviderRegistration.

See Also

Registering an Event Consumer Provider, Implementing an Event Consumer Provider, System Classes You Cannot Use as Base Classes


__EventDroppedEvent

The __EventDroppedEvent system class represents the occurrence of some other event being dropped (as opposed to being delivered to an event consumer).

class __EventDroppedEvent: __SystemEvent
{
  __Event object Event;
  __EventConsumer ref IntendedConsumer;
};

Properties

The following table lists the properties for __EventDroppedEvent.

Property | Data type | Description
Event | object:__Event | Event that was dropped.
IntendedConsumer | ref:__EventConsumer | Consumer that was to have received the event.

Remarks

The __EventDroppedEvent class is derived from __SystemEvent.


__EventFilter

Event consumers use the __EventFilter system class to register for particular types of events.

class __EventFilter : __IndicationRelated
{
  [key] string Name;
  string Query;
  string QueryLanguage;
  [read: DisableOverride ToInstance ToSubClass] uint8 CreatorSID[];
};

Properties

The following table lists the properties for __EventFilter.

Property | Data type | Description
Name | string | Key property. Unique identifier of the event filter. Because an event filter is only used internally by WMI, WMI recommends that Name be set to a globally unique identifier (GUID) converted into a string. However, consumers can use any private scheme for filter naming as long as there is no chance for conflict with other filters.
Query | string | WQL event query that specifies the set of events about which the consumer wants to be notified and the conditions under which notification should occur.
QueryLanguage | string | Specifies the language used for the query. Because WMI currently supports only WMI Query Language (WQL) as a query language, QueryLanguage must be set to "WQL".
CreatorSID | uint8[] | Security identifier that uniquely identifies the user who created this filter. This is a read-only property.

Remarks

The __EventFilter class is derived from __IndicationRelated.

See Also

Creating an Event Filter, Permanent Event Consumers, System Classes You Cannot Use as Base Classes


__EventGenerator

The __EventGenerator system class is an abstract base class that serves as a superclass for classes that controls the generation of events, such as timer events.

[abstract]
class __EventGenerator : __IndicationRelated
{
};

Properties

None.

Remarks

The __EventGenerator class is derived from __IndicationRelated, which has no properties.

See Also

System Classes You Cannot Use as Base Classes


__EventProviderCacheControl

The __EventProviderCacheControl system class is used to control when an event provider is unloaded. It is located only in the Root namespace.

class __EventProviderCacheControl : CacheControl
{
  CIM_DATETIME ClearAfter;
};

Properties

The following table lists the property for __EventProviderCacheControl.

Property | Data type | Description
ClearAfter | CIM_DATETIME | Number of seconds after which WMI should release an event provider. The time is in DMTF format. See Date and Time Format for detailed information on the DMTF date and time format.

Remarks

The __EventProviderCacheControl class is derived from __CacheControl. See Unloading a Provider for more information about using this class.


__EventProviderRegistration

The __EventProviderRegistration system class registers event providers with WMI.

class __EventProviderRegistration : __ProviderRegistration
{
  [key] __Provider ref provider;
  string EventQueryList[];
};

Properties

The following table lists the properties for __EventProviderRegistration.

Property | Data type | Description
EventQueryList | string | One or more WQL queries that describe the events that the event provider supports.
provider | __Provider ref | Key property. Specifies the name of the event provider. This property is inherited from __ProviderRegistration.

Remarks

The __EventProviderRegistration class is derived from __ProviderRegistration.

See Also

Registering an Event Provider, Implementing an Event Provider, System Classes You Cannot Use as Base Classes


__EventQueueOverflowEvent

The __EventQueueOverflowEvent system class represents an event raised when an event is dropped as a result of delivery queue overflow.

class __EventQueueOverflowEvent: __EventDroppedEvent
{
  uint32 CurrentQueueSize;
};

Properties

The following table lists the property for __EventQueueOverflowEvent.

Property | Data type | Description
CurrentQueueSize | uint32 | Current queue size (bytes). Defaults to 10MB for all queues combined.

Remarks

The __EventQueueOverflowEvent class is derived from __EventDroppedEvent.

For more information, see the following:

  • MaximumQueueSize property in the __EventConsumer class.
  • the Highthresholdonevents property in the Win32_WMISetting class.


__EventSinkCacheControl

The __EventSinkCacheControl system class is used to determine when WMI should release an event consumer provider's IWbemUnboundObjectSink pointer. The __EventSinkCacheControl class is a singleton class. It is located only in the Root namespace.

class __EventSinkCacheControl : CacheControl
{
  CIM_DATETIME ClearAfter;
};

Properties

The following table lists the property for __EventSinkCacheControl.

Property | Data type | Description
ClearAfter | CIM_DATETIME | Number of seconds after which WMI should release an event provider. The time is in DMTF format. For detailed information on the DMTF date and time format, see Date and Time Format.

Remarks

The __EventSinkCacheControl class is derived from __CacheControl. See Unloading a Provider for more information about using this class.


__ExtendedStatus

The __ExtendedStatus system class is used to report detailed status and error information.

class __ExtendedStatus : __NotifyStatus
{
  string Description;
  string Operation;
  string ParameterInfo;
  string ProviderName;
};

Properties

The following table lists the properties for __Extended Status.

Property | Data type | Description
Description | string | Any user-defined string that describes an error or operational status.
Operation | string | String that describes the operation that was taking place at the time of the failure or anomaly. WMI typically sets this property to the name of a WMI API method such as CreateInstanceEnum.
ParameterInfo | string | String that identifies one or more parameters that was involved in the error or status change. For example, if an application attempted to retrieve a class that does not exist, ParameterInfo would be set to the offending class name.
ProviderName | string | String that identifies the provider that caused or reported the error or status change. If a provider was not involved, this string is set to "Windows Management".

Remarks

The __ExtendedStatus class is derived from the __NotifyStatus class.

Use the __ExtendedStatus class to report information that is more complex than a simple result code. Providers can derive their own classes from __ExtendedStatus if they require more properties to describe their errors.

The StatusCod e property, inherited from the __NotifyStatus superclass, is an unsigned integer that represents the error or status value. When instances of this class are returned from a method by a dynamic provider, the StatusCode and Description properties are set by the provider, and the other properties are set by WMI.

See Also

System Classes You Can Use as Base Classes


__ExtrinsicEvent

The __ExtrinsicEvent system class is an abstract base class that serves as a superclass for all user-defined event types, also known as extrinsic events.

class __ExtrinsicEvent : __Event
{
};

Properties

None.

Remarks

The __ExtrinsicEvent class is derived from __Event, which has no properties.

See Also

System Classes You Can Use as Base Classes


__FilterToConsumerBinding

The __FilterToConsumerBinding system class is an association class that relates an instance of the __EventConsumer system class to an instance of the __EventFilter system class.

[Association: DisableOverride ToInstance ToSubClass]
class __FilterToConsumerBinding : __IndicationRelated
{
  [key] __EventFilter ref Filter;
  [key] __EventConsumer ref Consumer;
  [not_null: DisableOverride ToInstance ToSubClass] boolean DeliverSynchronously = FALSE;
  boolean MaintainSecurityContext = FALSE;
  boolean SlowDownProviders = FALSE;
  [read: DisableOverride ToInstance ToSubClass] uint8 CreatorSID[] = {1, 1, 0, 0, 0, 0, 0, 5, 18, 0, 0, 0};
};

Properties

The following table lists the properties for __FilterToConsumerBinding.

Property | Data type | Description
Consumer | __EventConsumer ref | Key property. Object path to a logical consumer, a recipient of the event. A logical consumer is an instance of a class derived from __EventConsumer.
DeliverSynchronously | Boolean | Indicates whether the event should be delivered to the logical consumer synchronously. If FALSE (default), it is delivered asynchronously.
Filter | __EventFilter ref | Key property. Object path to an event filter, a query that specifies the type of event to be received.
MaintainSecuritycontext | Boolean | Indicates whether the events will be delivered in the same security context that the provider was in when it provided them.
SlowDownProviders | Boolean | Indicates whether providers will be slowed down if this consumer cannot keep up.
CreatorSID | uint8[] | Security identifier that uniquely identifies the user who created this filter. This is a read-only property.

Remarks

The _FilterToConsumerBinding class is derived from __IndicationRelated, which has no properties.

Permanent event consumers use the __FilterToConsumerBinding system class to bind event filters to final consumers. After the filter and consumer are bound together, WMI can forward events that match the filter to the corresponding consumer.

Only consumers that are extremely fast and can process an event in 100 microseconds or less should consider supporting synchronous notification by setting DeliverySynchronously to TRUE. Synchronous consumers that take too long to process events can seriously impact the delivery of events to all other consumers, and can inadvertently block the event provider.

See Also

Creating a Logical Consumer, Creating an Event Filter, System Classes You Cannot Use as Base Classes


__IndicationRelated

The __IndicationRelated system class is an abstract base class that serves as a superclass for all event-related classes. The class contains no properties or semantics. It is a common derivation point to facilitate queries and retrieve class definitions that relate to events.

[abstract]
class __IndicationRelated : __SystemClass
{
};

Properties

None.

Remarks

The __IndicationRelated class is derived from __SystemClass, which has no properties.

See Also

System Classes You Cannot Use as Base Classes


__InstanceCreationEvent

The __InstanceCreationEvent system class represents an instance creation event, which is a type of intrinsic event that is generated when a new instance is added to the namespace.

class __InstanceCreationEvent : __InstanceOperationEvent
{
};

Properties

The following table lists the property for __InstanceCreationEvent.

Property | Data type | Description
TargetInstance | object | Contains a copy of the instance that was created. This property is inherited from __InstanceOperationEvent.

Remarks

The __InstanceCreationEvent class is derived from __InstanceOperationEvent.

See Also

System Classes You Cannot Use as Base Classes


__InstanceDeletionEvent

The __InstanceDeletionEvent system class represents an instance deletion event, which is a type of intrinsic event generated when an instance is deleted from the namespace.

class __InstanceDeletionEvent : __InstanceOperationEvent
{
};

Properties

The following table lists the property for __InstanceDeletionEvent.

Property | Data type | Description
TargetInstance | object | Contains a copy of the instance that was deleted. This property is inherited from __InstanceOperationEvent.

Remarks

The __InstanceDeletionEvent class is derived from __InstanceOperationEvent.

See Also

System Classes You Cannot Use as Base Classes


__InstanceModificationEvent

The __InstanceModificationEvent system class represents an instance modification event, which is a type of intrinsic event generated when an instance changes in the namespace.

class __InstanceModificationEvent : __InstanceOperationEvent
{
  object PreviousInstance;
};

Properties

The following table lists the properties for __InstanceModificationEvent.

Property | Data type | Description
PreviousInstance | object | Contains a copy of the instance prior to modification.
TargetInstance | object | Contains the new version of the changed instance. This property is inherited from __InstanceOperationEvent.

Remarks

The __InstanceModificationEvent class is derived from __InstanceOperationEvent.

See Also

System Classes You Cannot Use as Base Classes


__InstanceOperationEvent

The __InstanceOperationEvent system class is a base class for all intrinsic events that relate to an instance.

class __InstanceOperationEvent : __Event
{
  object TargetInstance;
};

Properties

The following table lists the property for __InstanceOperationEvent.

Property | Data type | Description
TargetInstance | object | Instance affected by the event. For creation events, this is the newly created instance. For modification events, this is the new version of the changed instance. For deletion events, this is the deleted instance.

Remarks

The __InstanceOperationEvent class is derived from __Event.

Instances of __InstanceOperationEvent are not created; only instances of its subclasses are created. The following classes derive from __InstanceOperationEvent:

__InstanceCreationEvent

__InstanceModificationEvent

__InstanceDeletionEvent

See Also

Intrinsic and Extrinsic Events, System Classes You Cannot Use as Base Classes


__InstanceProviderRegistration

The __InstanceProviderRegistration system class registers instance providers with WMI.

class __InstanceProviderRegistration : __ObjectProviderRegistration
{
  [key] __Provider ref provider;
};

Properties

The following table lists the property for __InstanceProviderRegistration.

Property | Data type | Description
InteractionType sint32 Indicates whether the class or instance provider supplies its own data, or relies on WMI and the Common Information Model (CIM) repository. Pull providers support dynamic access to their data, while push providers store their data in the CIM repository, and rely on WMI to provide access to it. For more information, see Pull and Push Providers. The default value is 1 or 2. This property is inherited from __ObjectProviderRegistration.

Values are:
0 = Provider is a pull provider
1 = Provider is a push provider

2 = Provider is a pushverify provider

provider | __Provider ref | Key property. Specifies the object path to the instance provider. This property is inherited from __ProviderRegistration.
QuerySupportLevels array (string) Indicates the type of provider-included support for query processing. Class providers are required to support at least one type of query. Instance providers can set QuerySupportLevels to NULL if they do not support query processing. Providers that do support queries implement the IWbemServices::ExecQueryAsync method, and set this property to one or both of the following values:

WQL:UnarySelect

WQL:V1ProviderDefined

This property is inherited from __ObjectProviderRegistration.

SupportsEnumeration Boolean Indicates whether the provider supports data enumeration. If TRUE, the provider supports data enumeration by implementing one of the following methods:
IWbemServices::CreateClassEnumAsync (class providers)
IWbemServices::CreateInstanceEnumAsync (instance providers)

If FALSE, the provider does not support data enumeration, and returns WBEM_E_PROVIDER_NOT_CAPABLE from CreateClassEnumAsync or CreateInstanceEnumAsync. This property is inherited from __ObjectProviderRegistration.

SupportsDelete Boolean Indicates whether the provider supports data deletion. If TRUE, the provider supports class or instance deletion by implementing one of the following methods:
IWbemServices::DeleteClassAsync (class providers)
IWbemServices::DeleteInstanceAsync (instance providers)

If FALSE, the provider does not support data deletion, and returns WBEM_E_PROVIDER_NOT_CAPABLE from DeleteClassAsync or DeleteInstanceAsync. This property is inherited from __ObjectProviderRegistration.

SupportsGet | Boolean | Indicates whether the class or instance provider supports data retrieval. If TRUE, the provider supports data retrieval by implementing IWbemServices::GetObjectAsync. If FALSE, the provider does not support data retrieval, and returns WBEM_E_PROVIDER_NOT_CAPABLE from GetObjectAsync. This property is inherited from __ObjectProviderRegistration.
SupportsPut Boolean Indicates whether the class or instance provider supports data modification. If TRUE, the provider supports class or instance modification by implementing one of the following methods:
IWbemServices::PutClassAsync (class providers)
IWbemServices::PutInstanceAsync (class providers)

If FALSE, the provider does not support data modification and returns WBEM_E_PROVIDER_NOT_CAPABLE from PutClassAsync or PutInstanceAsync. This property is inherited from __ObjectProviderRegistration.

Remarks

The __InstanceProviderRegistration class derives and inherits several properties from its superclasses in the class hierarchy: __ObjectProviderRegistration, and__ProviderRegistration.

The __ObjectProviderRegistration properties indicate whether the instance provider supports data retrieval, modification, deletion, enumeration and query processing.

The __ProviderRegistration class defines the provider property.

See Also

Registering Class and Instance Providers, System Classes You Cannot Use as Base Classes


__IntervalTimerInstruction

The __IntervalTimerInstruction system class is used to generate events at intervals, much like a WM_TIMER message in Microsoft Windows programming. An event consumer registers to receive interval timer events by creating an instance of this class. Due to operating system behavior, there are no guarantees that events will be delivered at precisely the requested interval.

class __IntervalTimerInstruction : __TimerInstruction
{
  [not_null: DisableOverride ToInstance ToSubClass] uint32 IntervalBetweenEvents;
};

Properties

The following table lists the properties for __IntervalTimerInstruction.

Property | Data type | Description
IntervalBetweenEvents | uint32 | Number of milliseconds between event firings.
SkipIfPassed | Boolean | Indicates whether the timer event occurs if WMI is unavailable to generate it at the appropriate time interval, or the consumer requesting to receive the event is unavailable. If TRUE, the event will not occur. The default is FALSE. Once WMI or the consumer becomes available again, a notification event will be generated and received. This property is inherited from __TimerInstruction.
TimerId | string | Key property. Unique user-assigned string that identifies this particular timer event. To avoid naming conflicts with other timer identifiers, the string form of a distributed computer environment (DCE)-style GUID can be used. The TimerId property is part of the __TimerEvent instance that represents the event. This property is inherited from __TimerInstruction.

Remarks

The __IntervalTimerEvent class is derived from __TimerInstruction.

The event query entered to register for an interval timer event is usually based on the TimerId property.

Notification events generated from an interval timer event contain the property NumFirings which contains data reflecting how many events fired during the time the events were unable to be received. If SkipIfPassed is set to TRUE, that information is discarded.

The value for the IntervalBetweenEvents property should be reasonably large. If it is too small, WMI may ignore it and not generate the event due to limitations in some operating systems.

WMI generates the interval timer event by creating an instance of the __TimerEvent class.

Example

The following MOF declaration shows how to generate an interval timer event with the key property set to "MyEvent" every 10 seconds:

instance of __IntervalTimerInstruction
{
  TimerId = "MyEvent";     // inherited from __TimerInstruction
  SkipIfPassed = FALSE;    // also inherited
  IntervalBetweenEvents = 10000;
};

To actually receive this event, an appropriate event filter and logical consumer must be defined and then associated. For more information, see Permanent Event Consumers.

See Also

Timer Events, System Classes You Cannot Use as Base Classes


__MethodProviderRegistration

The __MethodProviderRegistration system class registers method providers with WMI.

class __MethodProviderRegistration : __ProviderRegistration
{
  [key] __Provider ref provider;
};

Properties

The following table lists the property for __MethodProviderRegistration.

Property | Data type | Description
provider | __Provider ref | Key property. Specifies the object path of the method provider. This property is inherited from __ProviderRegistration.

Remarks

The __MethodProviderRegistration class is derived from __ProviderRegistration.

See Also

Registering a Method Provider, System Classes You Cannot Use as Base Classes


__Namespace

The __Namespace system class represents a WMI namespace.

class __NAMESPACE : __SystemClass
{
  [key] string Name;
};

Properties

The following table lists the property for __Namespace.

Property | Data type | Description
Name | string | Key property. Namespace name.

Remarks

The __Namespace class is derived from __SystemClass.

Creating a new instance of __Namespace within any working namespace creates a new namespace within the working namespace. Conversely, deleting an instance of __Namespace removes the corresponding namespace.

Enumerating instances of this class within any working namespace gives the available child namespaces.

For example, within the Root namespace are two instances of __Namespace. One has its Name property set to "Default," the other has Name set to "Cimv2." These instances represent the Root\Default, and Root\Cimv2 namespaces, respectively.

See Also

System Classes You Can Use as Base Classes


__NamespaceCreationEvent

The __NamespaceCreationEvent system class represents a namespace creation event, which is a type of intrinsic event generated when a new namespace is added to the current namespace.

class __NamespaceCreationEvent : __NamespaceOperationEvent
{
};

Properties

The following table lists the property for __NamespaceCreationEvent.

Property | Data type | Description
TargetNamespace | __Namespace | Contains a copy of the __Namespace instance that was created. The Name property of the __Namespace instance indicates which namespace was created. This property is inherited from class __NamespaceOperationEvent.

Remarks

The __NamespaceCreationEvent class is derived from __NamespaceOperationEvent.

See Also

System Classes You Cannot Use as Base Classes


__NamespaceDeletionEvent

The __NamespaceDeletionEvent system class represents a namespace deletion event, which is a type of intrinsic event generated when a new namespace is removed from the namespace.

class __NamespaceDeletionEvent : __NamespaceOperationEvent
{
};

Properties

The following table lists the property for __NamespaceDeletionEvent.

Property | Data type | Description
TargetNamespace | __Namespace | Contains a copy of the __Namespace instance that was created. The Name property of the __Namespace instance indicates which namespace was created. This property is inherited from class __NamespaceOperationEvent.

Remarks

The __NamespaceDeletionEvent class is derived from __NamespaceOperationEvent.

See Also

System Classes You Cannot Use as Base Classes


__NamespaceModificationEvent

The __NamespaceModificationEvent system class represents a namespace modification event, which is a type of intrinsic event generated when a new namespace is removed from the namespace.

class __NamespaceModificationEvent : __NamespaceOperationEvent
{
  __Namespace PreviousNamespace;
};

Properties

The following table lists the properties for __NamespaceModificationEvent.

Property | Data type | Description
PreviousNamespace | __Namespace | Contains a copy of the original version of the __Namespace instance. The Name property of this instance indicates which namespace was modified.
TargetNamespace | __Namespace | Contains a copy of the __Namespace instance that was created. The Name property of the __Namespace instance indicates which namespace was created. This property is inherited from class __NamespaceOperationEvent.

Remarks

The __NamespaceModificationEvent class is derived from __NamespaceOperationEvent.

The only differences between the target namespace and the previous namespace will be in the qualifiers and any properties other than Name.

Note that the Name property of an __Namespace instance cannot change since namespaces cannot be renamed. To modify the name of a namespace, its __Namespace instance must be deleted and re-created with the new name. Therefore, namespace modification events are generated when a change occurs to qualifiers and properties other than Name. A namespace modification event is not generated whenever any kind of change occurs within the namespace. Rather, it is generated only when a namespace instance itself is modified.

See Also

System Classes You Cannot Use as Base Classes


__NamespaceOperationEvent

The __NamespaceOperationEvent system class is a base class for all intrinsic events that relate to a namespace.

class __NamespaceOperationEvent : __Event
{
  __Namespace TargetNamespace;
};

Properties

The following table lists the property for __NamespaceOperationEvent.

Property | Data type | Description
TargetNamespace | __Namespace | Namespace affected by the event. For creation events, this is the newly created namespace. For modification events, this is the changed namespace. For deletion events, this is the deleted namespace.

Remarks

The __NamespaceOperationEvent class is derived from __Event.

Instances of this class are not created. WMI creates instances of one of the following classes derived from this class:

__NamespaceCreationEvent

__NamespaceModificationEvent

__NamespaceDeletionEvent

See Also

Intrinsic and Extrinsic Events, System Classes You Cannot Use as Base Classes


__NotifyStatus

The __NotifyStatus system class is an abstract base class that can serve as the superclass for provider-defined error classes.

[abstract: DisableOverride ToInstance ToSubClass]
class __NotifyStatus
{
  uint32 StatusCode;
};

Properties

The following table lists the property for __NotifyStatus.

Property | Data type | Description
StatusCode | uint32 | Contains an error or information code for an operation. This can be any user-defined code, but the value 0 is usually reserved to indicate success.

Remarks

Although the __NotifyStatus class can be the superclass for provider-defined error classes, it is recommended that providers derive their error classes from __ExtendedStatus instead. Using __ExtendedStatus allows for greater standardization of error classes.

Providers should never create instances of __NotifyStatus directly because these instances convey no more information than a simple return code.

See Also

System Classes You Cannot Use as Base Classes


__NTLMUser9X

The __NTLMUser9X system class is used to allow remote access to a Windows 95/98 computer.

class __NTLMUser9X: __SecurityRelatedClass
{
  string Authority;
  sint32 Flags;
  sint32 Mask;
  string Name;
  sint32 Type;
};

Properties

The following table lists the properties for NTLMUser9X.

Property | Data type | Description
Authority | string | Domain to which the user name applies.
Flags | sint32 | Inheritance flags. Values are: 0 = No inheritance 2 = Apply to child namespaces in addition to the current one
Mask | sint32 | For information about the available access rights, see the Remarks section.
Name | string | User name.
Type | sint32 | Values are: 0= Access allowed 1 = Access denied

Remarks

The following table lists the access rights for Mask.

Access right | Bit mask position | Description
WBEM_ENABLE | 0X1 | Enables the account.
WBEM_METHOD_EXECUTE | 0X2 | Allows the execution of methods. Note that providers may perform additional access checks.
WBEM_FULL_WRITE_REP | 0X4 | Allows many types of writes to the repository.
WBEM_PARTIAL_WRITE_REP | 0X8 | Allows writing of non-system instances to the repository.
WBEM_WRITE_PROVIDER | 0X10 | Writing of classes and instance to providers. Note that impersonating providers may perform additional access checks.
WBEM_REMOTE_ACCESS | 0X20 | Allows remote access.
WRITE_DAC | 0X40000 | Writing the DACL.
READ_CONTROL | 0X20000 | Reading the SD.

See Also

System Classes You Cannot Use as Base Classes


__ObjectProviderCacheControl

The __ObjectProviderCacheControl system class is used to control when a provider is unloaded. It is located only in the Root namespace.

class __ObjectProviderCacheControl
{
  CIM_DATETIME ClearAfter;
};

Properties

The following table lists the properties for __ObjectProviderCacheControl.

Property | Data type | Description
ClearAfter | CIM_DATETIME | Number of seconds after which WMI should release an instance, class, or method provider. The time is in DMTF format. For detailed information on the DMTF date and time format, see Date and Time Format.

Remarks

The __ObjectProviderCacheControl class is derived from __CacheControl. See Unloading a Provider for more information about using this class.

See Also

Permanent Consumer Architecture


__ObjectProviderRegistration

The __ObjectProviderRegistration system class is an abstract base class that serves as the superclass for classes used to register class and instance providers with WMI.

[abstract]
class __ObjectProviderRegistration : __ProviderRegistration
{
  boolean SupportsPut = FALSE;
  boolean SupportsGet = FALSE;
  boolean SupportsDelete = FALSE;
  boolean SupportsEnumeration = FALSE;
  [ValueMap{"WQL:UnarySelect", "WQL:References", "WQL:Associators", "WQL:V1ProviderDefined"}: ToSubClass] string QuerySupportLevels[];
  [Values{"Pull", "Push", "PushVerify"}: ToSubClass] sint32 InteractionType = 0;
};

Properties

The following table lists the properties for __ObjectProviderRegistration.

Property | Data type | Description
InteractionType sint32 Indicates whether the class or instance provider supplies its own data, or relies on WMI and the Common Information Model (CIM) repository. Pull providers support dynamic access to their data, while push providers store their data in the CIM repository, and rely on WMI to provide access to it. For more information, see Pull and Push Providers. The default value is 1 or 2.

Values are:
0 = Provider is a pull provider
1 = Provider is a push provider

2 = Provider is a pushverify provider

provider | __Provider ref | Specifies the object path to the object provider. This property is inherited from __ProviderRegistration.
QuerySupportLevels array (string) Indicates the type of provider-included support for query processing. Class providers are required to support at least one type of query. Instance providers can set QuerySupportLevels to NULL if they do not support query processing. Providers that do support queries implement the IWbemServices::ExecQueryAsync method, and set this property to one or both of the following values:

WQL:UnarySelect

WQL:V1ProviderDefined
SupportsEnumeration Boolean Indicates whether the provider supports data enumeration. If TRUE, the provider supports data enumeration by implementing one of the following methods:
IWbemServices::CreateClassEnumAsync (class providers)
IWbemServices::CreateInstanceEnumAsync (instance providers)

If FALSE, the provider does not support data enumeration, and returns WBEM_E_PROVIDER_NOT_CAPABLE from CreateClassEnumAsync or CreateInstanceEnumAsync.
SupportsDelete Boolean Indicates whether the provider supports data deletion. If TRUE, the provider supports class or instance deletion by implementing one of the following methods:
IWbemServices::DeleteClassAsync (class providers)
IWbemServices::DeleteInstanceAsync (instance providers)

If FALSE, the provider does not support data deletion, and returns WBEM_E_PROVIDER_NOT_CAPABLE from DeleteClassAsync or DeleteInstanceAsync.
SupportsGet | Boolean | Indicates whether the class or instance provider supports data retrieval. If it is set to TRUE, the provider supports data retrieval by implementing IWbemServices::GetObjectAsync. If it is set to FALSE, the provider does not support data retrieval, and returns WBEM_E_PROVIDER_NOT_CAPABLE from GetObjectAsync.
SupportsPut Boolean Indicates whether the class or instance provider supports data modification. If it is set to TRUE, the provider supports class or instance modification by implementing one of the following methods:
IWbemServices::PutClassAsync (class providers)
IWbemServices::PutInstanceAsync (class providers)

If it is set to FALSE, the provider does not support data modification and returns WBEM_E_PROVIDER_NOT_CAPABLE from PutClassAsync or PutInstanceAsync.

Remarks

The __ObjectProviderRegistration class is derived from __ProviderRegistration.

Class providers must set the SupportsEnumeration property to TRUE because the providers must be able to supply WMI with a list of their classes. If a class provider attempts to set this property to FALSE, WMI flags the registration as illegal. Instance providers are not required to support enumeration, and can choose to set SupportsEnumeration to either TRUE or FALSE.

A provider that sets QuerySupportLevels to "WQL:UnarySelect" can accept a query consisting of the basic SELECT statement as supported in WMI version 1.0. Both class and instance providers are expected to be able to handle the __CLASS system property. Class providers are also expected to process the __SUPERCLASS system property and the ISA operator. The ISA operator is used to expand a result set to derived classes. If a provider is given a query that it cannot interpret, it requests that WMI handle it by returning the WBEM_E_TOO_COMPLEX error value. For a description of valid WQL syntax, see WMI Query Language.

A provider that sets QuerySupportLevels to "WQL:V1ProviderDefined" can try to support a larger set of the SQL syntax at its own risk, such as the ORDER BY clause. WMI will not interpret these additional clauses or attempt to ensure that the result set is correct.

See Also

System Classes You Cannot Use as Base Classes


__PARAMETERS

The __PARAMETERS system class is an abstract class used to define methods and to pass input and output arguments to a method provider.

Properties

None.

Remarks

To define a method, a method provider creates an instance of the __PARAMETERS class and adds a property for each of parameter in the method. If the method has both input and output parameters, then two __PARAMETERS instances are used. The method provider then stores the method parameters with a call to IWbemClassObject::PutMethod.

To invoke a method, a client:

  1. Calls IWbemClassObject::GetMethod to retrieve a copy of the __PARAMETERS instance that was stored by IWbemClassObject::PutMethod.
  2. Calls IWbemClassObject::SpawnInstance, and then sets one property for each input parameter to the method.
  3. Calls IWbemServices::ExecMethod or IWbemServices::ExecMethodAsync to execute the method.

After the method has finished executing, another __PARAMETERS class instance is returned as a parameter to IWbemServices::Indicate that holds the output parameters and method's return value.

See Also

Implementing IWbemServices::ExecMethodAsync, Calling a Method, System Classes You Cannot Use as Base Classes


__PropertyProviderCacheControl

The __PropertyProviderCacheControl system class is used to control the cache when a property provider is unloaded. It is located only in the Root namespace.

class __PropertyProviderCacheControl : CacheControl
{
  CIM_DATETIME ClearAfter;
};

Properties

ClearAfter
Number of seconds after which WMI should release a property provider. The time is in DMTF format. See Date and Time Format for detailed information on the DMTF date and time format.
Property | Data type | Description
ClearAfter | CIM_DATETIME | Number of seconds after which WMI should release a property provider. The time is in DMTF format. See Date and Time Format for detailed information on the DMTF date and time format.

Remarks

The __PropertyProviderCacheControl class is derived from __CacheControl. See Unloading a Provider for more information about using this class.


__PropertyProviderRegistration

The __PropertyProviderRegistration system class registers property providers with WMI.

class __PropertyProviderRegistration : __ProviderRegistration
{
  [key] __Provider ref provider;
  boolean SupportsPut = FALSE;
  boolean SupportsGet = FALSE;
};

Properties

The following table lists the properties for __PropertyProviderRegistration.

Property | Data type | Description
provider | __Provider ref | Key property. Specifies the object path of the property provider. This property is inherited from __ProviderRegistration.
SupportsGet | Boolean | Indicates whether the property provider supports data retrieval. If it is set to TRUE, the property provider supports data retrieval by implementing IWbemPropertyProvider:GetProperty. If it is set to FALSE, the property provider does not support data retrieval, and it returns WBEM_E_PROVIDER_NOT_CAPABLE from GetProperty.
SupportsPut | Boolean | Indicates whether the property provider supports data modification. If it is set to TRUE, the property provider supports data modification by implementing IWbemPropertyProvider::PutProperty. If it is set to FALSE, the property provider does not support data modification, and it returns WBEM_E_PROVIDER_NOT_CAPABLE from PutProperty.

Remarks

The __PropertyProviderRegistration class is derived from __ProviderRegistration.

See Also

Registering a Property Provider, System Classes You Cannot Use as Base Classes


__Provider

The __Provider system class is an abstract base class that serves as the superclass for the __Win32Provider system class.

[abstract]
class __Provider : __SystemClass
{
  [key] string Name;
};

Properties

The following table lists the property for __Provider.

Property | Data type | Description
Name | string | Key property. Language-neutral string that uniquely identifies the provider. The following format is suggested to prevent naming conflicts: vendor|provider|version For example, this provider name represents version 1.0 of the Microsoft TestProvider: "Microsoft|TestProvider|V1.0"

Remarks

The __Provider class is derived from __SystemClass.

Providers create __Win32Provider instances to specify information about their physical implementation.

See Also

__Win32Provider


__ProviderRegistration

The __ProviderRegistration system class is an abstract base class that serves as the superclass for registration classes for various types of providers.

[abstract]
class __ProviderRegistration : __SystemClass
{
  __Provider ref provider;
};

Properties

The following table lists the property for __ProviderRegistration.

Property | Data type | Description
provider | __Provider ref | Specifies the object path to the provider.

Remarks

The __ProviderRegistration class is derived from __SystemClass.

Instances of the __ProviderRegistration system class are never created. The classes that providers use to create instances for registration derive either directly or indirectly from this class. These classes are:

__ObjectProviderRegistration

__ClassProviderRegistration

__InstanceProviderRegistration

__PropertyProviderRegistration

__MethodProviderRegistration

__EventProviderRegistration

__EventConsumerProviderRegistration

See Also

Registering a Provider, System Classes You Cannot Use as Base Classes


__SecurityRelatedClass

The __SecurityRelatedClass system class is an abstract base class that serves as a superclass for all types of security classes. No instances of this class are ever created, and all security classes must derive from this base class.

[abstract]
class __SecurityRelatedClass
{
};

Properties

None.

See Also

System Classes You Cannot Use as Base Classes


__SystemClass

The __SystemClass system class is the abstract base class from which all system classes derive. Instances of this class cannot be created.

[abstract]
class __SystemClass
{
};

Properties

None.

See Also

System Classes You Cannot Use as Base Classes


__SystemEvent

The __SystemEvent system class represents a system event.

Properties

None.

Remarks

The __SystemEvent class is derived from __ExtrinsicEvent.


__SystemSecurity

[This is preliminary documentation and subject to change.]

[singleton: DisableOverride ToInstance ToSubClass]
class __SystemSecurity
{
  [Static] uint32 GetSD([out] uint8 SD[]);
  [Static] uint32 Get9XUserList([out] __ntlmuser9x ul[]);
  [Static] uint32 SetSD([in] uint8 SD[]);
  [Static] uint32 Set9XUserList([in] __ntlmuser9x ul[]);
  [Static] uint32 GetCallerAccessRights([out] sint32 rights);
};

Properties

None.

Methods

The following table lists the methods for __SystemSecurity.

Method | Description
GetSD |
Get9XUserList |
SetSD |
Set9XUserList |
GetCallerAccessRights |

Remarks

The __SystemSecurity class is not derived from another class.

See Also

System Classes You Cannot Use as Base Classes


__TimerEvent

The __TimerEvent system class represents an event generated by WMI in response to a consumer's request for an interval timer event or an absolute timer event. An interval timer event is an event that occurs at regular intervals. An absolute timer event is an event that occurs at a specific time. Timer events can occur in any namespace.

class __TimerEvent : __Event
{
  uint32 NumFirings;
  string TimerId;
};

Properties

The following table lists the properties for __TimerEvent.

Properties | Data type | Description
NumFirings | uint32 | Number of times the event occurred before a notification was delivered to the consumer.
TimerId | string | String that identifies the timer event registration. Consumers specify a timer identification in the TimerId property of the __TimerInstruction subclass that they create to register.

Remarks

The __TimerEvent class is derived from __Event.

Event consumers register for an absolute timer event by creating an instance of the __AbsoluteTimerInstruction system class. They register for an interval timer event by creating an instance of the __IntervalTimerInstruction system class.

During normal operation, the NumFirings property is set to 1. When it is not possible to reach the consumer or the firing interval is much quicker than the ability to deliver the event, NumFirings is set to a number greater than 1. When NumFirings is greater than 1, WMI automatically merges many timer events into the same event. This merging is similar to what occurs with WM_TIMER messages in Microsoft Windows programming.

See Also

Timer Events, System Classes You Cannot Use as Base Classes


__TimerInstruction

The __TimerInstruction system class is an abstract base class for classes used to specify instructions on how timer events should be generated for consumers.

[abstract]
class __TimerInstruction : __EventGenerator
{
  [key] string TimerId;
  boolean  = FALSE;
};

Properties

The following table lists the properties for __TimerInstruction.

Properties | Data type | Description
SkipIfPassed | Boolean | Indicates whether the timer event occurs if WMI is unavailable to generate it at the appropriate time interval, or the consumer requesting to receive the event is unavailable. The default setting is FALSE. Once WMI or the consumer becomes available again, a notification event will be generated and received. If set to TRUE, the event will not occur.
TimerId | string | Key property. Unique user-assigned string that identifies this particular timer event. To avoid naming conflicts with other timer identifiers, the string form of a distributed computer environment (DCE)-style GUID can be used. This property is part of the __TimerEvent instance that represents the event.

Remarks

The __TimerInstruction class is derived from __EventGenerator.

The __TimerInstruction subclasses are __AbsoluteTimerInstruction, used by consumers to register for an absolute timer event, and __IntervalTimerInstruction, used to register for an interval timer event.

See Also

System Classes You Cannot Use as Base Classes


__TimerNextFiring

The __TimerNextFiring system class is a reserved class, and should not be manipulated by the user.

See Also

System Classes You Cannot Use as Base Classes


__Win32Provider

The __Win32Provider system class registers information about a provider's physical implementation with WMI.

class __Win32Provider : __Provider
{
  [not_null: DisableOverride ToInstance ToSubClass] string CLSID;
  string ClientLoadableCLSID;
  string DefaultMachineName;
  [SUBTYPE("interval"): ToInstance ToSubClass] datetime UnloadTimeout;
  boolean InitializeAsAdminFirst;
  [Values{"None"}: ToSubClass] sint32 ImpersonationLevel = 0;
  [Values{"CLSID", "Namespace", "COM Object"}: ToSubClass] sint32 InitializationReentrancy = 0;
  boolean PerUserInitialization = FALSE;
  boolean PerLocaleInitialization = FALSE;
  boolean Pure = TRUE;
};

Properties

The following table lists the properties in __Win32Provider.

Property | Data type | Description
ClientLoadableCLSID | string | Reserved for future use.
CLSID | string | GUID that represents the class identifier (CLSID) of the provider's COM object. This COM object must contain an implementation of the IWbemProviderInit interface.
DefaultMachineName | string | Identifies the computer on which to launch the provider. If the provider runs on the local computer, it is NULL.
ImpersonationLevel | sint32 | Reserved for future use; must be set to 0.
InitializationReentrancy | sint32 | Set of flags that provide information about serialization. Values are: 0 = all initialization of this provider must be serialized 1 = all initializations of this provider in the same namespace must be serialized 2 = no initialization serialization is necessary
InitializeAsAdminFirst | Boolean | Indicates whether the provider requests that it is fully initialized as "Admin" before initializations begin for users. The default value is FALSE.
PerLocaleInitialization | Boolean | Indicates whether the provider is initialized for each locale if a user connects to the same namespace more than once using different locales.
PerUserInitialization | Boolean | Indicates whether the provider is initialized once for each actual Windows NT/Windows 2000 NTLM user making requests of the provider. If set to FALSE (default), the provider is initialized once for all users.
Pure | Boolean | Indicates whether the provider agrees to prepare to unload by calling IUnknown::Release on all outstanding interface points when WMI calls the Release method of its primary interface. Providers that must remain clients of WMI after they are no longer functioning as providers should set Pure to FALSE. The default setting is TRUE. See Remarks for more information.
UnloadTimeout | datetime | A string in the DMTF date/time format that specifies how long WMI allows the provider to remain idle before it is unloaded. Typically providers request that WMI wait no longer than 5 minutes. For the current version of WMI, the value of this property is ignored. WMI unloads the provider based on the timeout value in an internal class in the Root namespace. For more information see Unloading a Provider. It is recommended that providers set UnloadTimeout because it will be used in future versions.

Remarks

The __Win32Provider class is derived from __Provider.

Most providers can accept the default values for the InitializationReentrancy property. However, if a provider can support simultaneous initialization for separate users, this property can be set to 1. If serialized initialization is necessary, InitializationReentrancy remains 0. In both cases, PerUserInitialization is set to TRUE.

A pure provider, or one that sets the Pure property to TRUE, exists only to service requests from applications and WMI. Most providers are pure providers. A non-pure provider is the exception. Non-pure providers transition to the role of client after they have finished servicing requests.

An example of a non-pure provider would be a push provider that starts to issue queries, and make requests of WMI after it has completed its initialization. Push providers have no responsibilities other than to update the CIM repository with data at initialization time. After updating the repository, a push provider can either wait to be unloaded or transition to the role of client. The push provider that waits to be unloaded is a pure provider. The push provider that participates in client activities is non-pure.

WMI must be able to distinguish pure providers from non-pure providers so that it can determine when it is safe to shut down. WMI must wait for all operations involving non-pure providers to finish before it can safely shut down.

See Also

Registering a Provider, System Classes You Can Use as Base Classes


WMI System Properties

Windows Management Instrumentation (WMI) defines a set of system properties that are associated with all classes and instances of classes. As with system classes, system properties begin with a double underscore. This format makes it easy for you to distinguish them from properties created by applications or providers that may not start with a single or double underscore. Another way to identify a system property is to use the IWbemClassObject::Get method.

System properties are available at any time, even though their values might be NULL. NULL indicates a property does not apply to the object in question.

System properties are not necessarily available for all classes or instances at all times. The meaning and availability of the system properties are as follows:

__Class (CIM_STRING)

Class name. Read-only for instances; read/write for classes

__Derivation (CIM_STRING array)

Class hierarchy of the current class or instance. The first element is the immediate superclass, the next is its parent, and so on; the last element is the base class. Read-only for both instances and classes

__Dynasty (CIM_STRING)

Name of the top-level class from which this class or instance is derived. When this class or instance is the top-level class, the values of __Dynasty and __Class are the same. Read-only

__Genus (CIM_SINT32)

Value that is used to distinguish between classes and instances. This value is WBEM_GENUS_CLASS (1) for classes and WBEM_GENUS_INSTANCE (2) for instances. Read-only

__Namespace (CIM_STRING)

Name of the namespace from which this class or instance came. Read-only

__Path (CIM_STRING)

Full path to the class or instance, including server and namespace. Read-only

__Property_Count (CIM_SINT32)

Number of nonsystem properties defined for the class or instance. Read-only

__Relpath (CIM_STRING)

Relative path to the class or instance. Read-only

__Server (CIM_STRING)

Name of the server supplying this class or instance. Read-only

__Superclass (CIM_STRING)

Name of the immediate parent class of the class or instance. Read-only


WMI Standard Qualifiers

Qualifiers are used to characterize:

  • Classes
  • Class instances
  • Properties and methods of classes and class instances
  • Method parameters

Qualifiers are optional; they can be defined by using the Managed Object Format (MOF) language or the Put method of the IWbemQualifierSet interface. You can use other methods of IWbemQualifierSet to retrieve or delete existing qualifiers.

In MOF syntax, place the qualifier before the keyword or element that it describes.

[qualifiers...]
class StdDisk
{
  [qualifiers...]  uint32 dwNumCylinders;
  [qualifiers...]  uint32 dwNumHeads;
  [qualifiers...]  sint32 Method1();
  SINT32 Method2([qualifiers...] Parameter1);
};

All qualifier names are case-insensitive. You can determine the type of the qualifier from the declaration syntax.

Some qualifiers have predefined values; others do not. Those that do not, have a predefined, implied value of TRUE. For example, if the Abstract qualifier is present (indicating that the class in question is abstract) the implication is that Abstract is TRUE.

The following two MOF fragments are equivalent.

[Abstract(true), AnotherBool(false), PlainBool]
class TestOne
{
    [key]
    string akey;
};

Notice that true can be omitted but false cannot.

[Abstract, AnotherBool(false), PlainBool]
class TestOne
{
    [key] string akey;
};

Although Distributed Management Task Force (DMTF) and Windows Management Instrumentation (WMI) define standard qualifiers, developers can also define additional qualifiers. The sections that follow describe the types of qualifiers used in WMI (and WBEM in general); these types of qualifiers include:

  • Meta qualifiers
  • Standard qualifiers
  • Optional qualifiers
  • WMI-Specific Qualifiers

The name of each qualifier appears with its data type and an indicator of whether the qualifier can be applied to a class, an instance, a property, or a method.


Meta Qualifiers

Meta qualifiers refine the definition of meta constructs in the CIM model by clarifying the actual usage of a class or property declaration within the MOF syntax.

Qualifier | Description
ASSOCIATION | Indicates that a class is an association class used to describe a relationship between two other classes. The absence of this qualifier indicates that the class is not an association class. For more information on association classes, see Association Classes.
INDICATION | The object class is defining an indication.

Note These qualifiers are mutually exclusive.


Standard Qualifiers

All CIM-compliant implementations must handle a set of qualifiers, called the standard qualifiers. Any specific object will not have all of the qualifiers listed. Usually, extension classes supply additional qualifiers to facilitate provision of class instances and other operations on the class.

The following table lists and describes WMI standard qualifiers.

Qualifier | Description
ABSTRACT Indicates that the class is abstract and serves only as a base for new classes. You cannot create instances of abstract classes.

The absence of this qualifier indicates that the class is not abstract.
AGGREGATE Defines the parent component of an aggregation association.

Usage Rule: The AGGREGATION and AGGREGATE qualifiers are used together – AGGREGATION qualifies the association, and AGGREGATE specifies the parent reference.

AGGREGATION | Indicates that the association is an aggregation.
ALIAS | Establishes an alternate name for a property or method in the schema.
ARRAYTYPE Indicates the type of the qualified array.

Valid values are:

bag

indexed

ordered

Usage Rule: Apply this type of qualifier only to properties and method parameters that are arrays (which are defined by using square bracket syntax).
BITMAP Indicates which bit positions in a bit map are significant .

The position of a specific value in the bitmap array defines an index that is used in selecting a string literal from the BITVALUES array.
BITVALUES Translates a bit position value into an associated string.

For more information on bit mapping, see the description of the BITMAP qualifier.
DESCRIPTION | Provides a description of a named element.
DISPLAYNAME | Defines a name displayed in the UI instead of the actual name of the element.
GAUGE Represents a non-negative integer, which can increase or decrease, but never exceed a maximum value.

The maximum value cannot be greater than 2^n - 1. N can be 8, 16, 32 or 64 depending on the data type of the object to which the qualifier is applied.

The value of a gauge has its maximum value whenever the information being modeled is greater or equal to that maximum value. If the information being modeled subsequently decreases below the maximum value, the gauge also decreases.

Counter qualifiers are applicable only to unsigned integer types.
IN | Indicates that the associated parameter is used to pass values to a method.
IN, OUT | Indicates that a parameter is both an input and an output parameter.
KEY Indicates that the property is part of the namespace handle . If more than one property has the KEY qualifier, then all such properties collectively form the key (a compound key).

Marks a class property as a key. Only the value TRUE is allowed. A number of rules determine which properties may be keys. For more information about these rules, see Key Properties.

Usage Rule: Keys are written once at object instantiation and must not be modified later. It does not make sense to apply a default value to a key-qualified property.
MAPPINGSTRINGS | Maps Management Information Format (MIF) attributes and SNMP variables to CIM properties.
MAX Indicates the maximum cardinality of the reference (the maximum number of values a given reference can have for each set of other reference values in the association).

For example, if an association relates A instances to B instances and there must be at most one a instance for each B instance, then the reference to a should have a maximum of one qualifier.

MAXLEN Indicates the maximum length (in characters) of a string data item and indicates support of fixed-length arrays.

If a fixed-length array is encountered, the MAXLEN qualifier contains the fixed length found during parsing. If a variable-length array is encountered, then this qualifier is not used. MAXLEN is used to suggest the maximum number of elements that should be stored in an array.

When overriding the default value, any unsigned integer value (uint32) can be specified. A value of NULL implies unlimited length.
MAXVALUE | Indicates the maximum value of the object.
MIN Indicates the minimum cardinality of the reference (the minimum number of values a given reference can have for each set of other reference values in the association).

For example, if an association relates A instances to B instances, and there must be at least one A instance for each B instance, then the reference to a should have a minimum of one qualifier.
MINVALUE | Indicates the minimum value of the object.
MODEL CORRESPONDENCE Indicates a correspondence between an object's property and other properties in the CIM schema.

Object properties are identified using the following syntax.

<schema name> "_" <class or association name> "." <property name>
NONLOCAL Indicates the location of an instance, the value of which is <namespacetype>://<namespacehandle>

Usage Rule: Non-LOCAL qualifiers cannot be used with non-localtype qualifiers.
NONLOCALTYPE Indicates the type of location of an instance. Its value is <namespacetype>

Usage Rule: Cannot be used with the non-LOCAL qualifier.

NULLVALUE Defines a value that indicates that the associated property is NULL (the property does not have a valid or meaningful value).

The conventions and restrictions used for defining NULL values are the same as those applicable to the VALUEMAP qualifier.

Note this qualifier cannot be overridden. It is unreasonable to permit a subclass to return a different NULL value than that of the superclass.
OUT | Indicates that the associated parameter returns values from a method.
OVERRIDE

Indicates that the property, method, or reference in the derived class overrides the similar construct (of the same name) in the parent class.

The value of this qualifier may identify the parent class, whose subordinate construct (property, method, or reference) is overridden.

The format of the string to accomplish this is:

[<class>.]<subordinate construct>.

If the class name is omitted, the override applies to the subordinate construct in the parent class in the inheritance tree.

Usage Rule: The OVERRIDE qualifier can refer to constructs based on the same meta model only. It is not allowed to change a construct name or signature during an override operation.
PROPAGATED

Contains the name of the key being propagated.

Use of this qualifier assumes the existence of only one weak qualifier on a reference that has the containing class as its target. The associated property must have the same value as the property named by the qualifier in the class on the other side of the weak association. The format of the string to accomplish this is:

[<class>.]<subordinate construct>

Usage Rule: When the PROPAGATED qualifier is used, the KEY qualifier must be specified with a value of TRUE.
READ

Indicates that the property is readable.

REQUIRED

Indicates that a non-null value is required for the property.
REVISION

Provides the minor revision number of the schema object.

Usage Rule: The VERSION qualifier must be present to supply the major version number when the REVISION qualifier is used.
SCHEMA

Provides the name of the schema, in which the feature is defined.
SOURCE

Indicates the location of an instance.

The qualifier's value is <namespacetype>://<namespacehandle>.

Usage Rule: The SOURCE qualifier cannot be used with the SOURCETYPE qualifier.
SOURCETYPE

Indicates the type of location of an instance. The value of this qualifier is <namespacetype>

Usage Rule: The SOURCETYPE qualifier cannot be used with the source qualifier.

STATIC

Indicates that the property is a class variable rather than an instance variable.

Indicates that the method is a class method that does not depend on any per-instance data.

TERMINAL

Indicates that the class can have no subclasses.

If a subclass is declared, the compiler will generate an error.

This qualifier cannot coexist with the ABSTRACT qualifier. If both terminal and abstract qualifiers are specified, the compiler generates an error.
UNITS Provides units in which the associated data item is expressed.

For example, a size data item might have units (bytes).
VALUEMAP

Defines the set of permissible values for a property, method return type, or method parameter.

The value map can be used alone or in combination with the VALUES qualifier. When used in combination with the VALUES qualifier, the location of the value in the VALUEMAP array provides the location of the corresponding entry in the VALUES array.

Use the VALUEMAP qualifier only with string and integer values. The syntax for representing an integer value in the valuemap array is:

[+|-]digit[*digit]

The content, maximum number of digits, and represented value are constrained by the type of the associated property. For example, uint8 may not be signed, must be less than four digits, and must represent a value less than 256.

Specifies an array of integer values in string format that are used to map integer property values to string values specified by the VALUES qualifier. The VALUEMAP qualifier must be used with the VALUES qualifier; the corresponding property must be an integer. For more information, see MOF Enumerations.

VALUES

Translates an integer value into an associated string.

Also specifies an array of string values to be mapped to an enumeration property. This qualifier can be applied to either an integer property or a string property, and the mapping can be implicit or explicit. If the mapping is implicit, integer or string property values represent ordinal positions in the VALUES array. If the mapping is explicit, the property must be an integer, and valid property values are listed in the array defined by the VALUEMAP qualifier. For more information, see MOF Enumerations.

If a VALUEMAP qualifier is not present, the values array is indexed (zero-relative) by using the value in the associated property, method return type, or method parameter.

If a VALUEMAP qualifier is present, the values index is defined by the location of the property value in the valuemap.
VERSION

Provides the major version number of the schema object.

The version number is incremented when changes are made to the schema that alter the interface.

WEAK

Indicates that the keys of the referenced class include the keys of the other participants in the association.

This qualifier is used when the identity of the referenced class depends on the identity of the other participants in the association. No more than one reference to any given class can be weak. The other classes in the association must define a key. The keys of the other classes in the association are repeated in the referenced class and are tagged with a PROPAGATED qualifier.

WRITE Indicates whether write access is allowed for a property by any consumers of that property's data.

This qualifier address neither the initial assignment of a property value nor its maintenance by its provider. The qualifier, which describes the maximum level of access that is allowed, does not address whether security and authorization restrictions may actually prevent writing of the data.

A value of TRUE indicates that given appropriate administrative authorization, the property is readable and writeable by consumers ().

A value of FALSE indicates that regardless of authorization, the property is only readable by consumers.

The Applies to column identifies the meta-model constructs that can use a particular qualifier. For qualifiers such as ASSOCIATION (discussed in the previous section), there is an implied usage rule that the meta qualifier must also be present. For example, the implicit usage rule for the AGGREGATION qualifiers is that the ASSOCIATION qualifier must also be present.

Note You should be aware of the following usage limitations:

  • Not all standard qualifiers can be used together.
  • Not all qualifiers can be applied to all meta-model constructs. These limitations are identified in the Applies to column.
  • For a particular meta-model construct such as ASSOCIATIONS, the use of the legal qualifiers may be further constrained because some qualifiers are mutually exclusive, the use of one qualifier implies some restrictions on the value of another, and so on. These usage rules are documented in the Descriptions column.
  • Legal qualifiers are not inherited by meta-model constructs. For example, the MAXLEN qualifier that applies to properties is not inherited by references.


Optional Qualifiers

Optional qualifiers address situations not common to all CIM-compliant implementations. CIM-compliant implementations can ignore optional qualifiers because they are not required to interpret these qualifiers. Optional qualifiers are provided in the specification to avoid random user-defined qualifiers that might occur in these recurring situations.

Qualifier | Description
DELETE Indicates that the qualified association must be deleted if any of the objects referenced in the association are deleted and if the respective object referenced in the association is qualified with IFDELETED.

Indicates that the referenced object must be deleted if the association containing the reference is deleted and qualified with IFDELETED or if any of the objects referenced in the association are deleted and the respective object referenced in the association is qualified with IFDELETED.

Usage Rule: Applications must chase associations according to the modeled semantics and delete objects appropriately.

This usage rule must be verified when the CIM security model is defined.
EXPENSIVE | Indicates that the implied action requires extensive computation.
IFDELETED | Indicates that all objects within the association that are qualified by DELETE must be deleted if the referenced object or the association is deleted.
INDEXED Requests a class property be indexed. When applied to properties in classes hosted by the repository, this only has the meaning of creating (at the time of class creation) a fast secondary query lookup for that property.

Only the value TRUE is allowed.
INVISIBLE | Indicates that the association is defined only for internal purposes (for example, for definition of dependency semantics) and should not be displayed (for example, in maps).
LARGE | Indicates the property or class requires a large amount of storage space.
NOT_NULL Indicates that a class property cannot take on a value of NULL (VT_NULL). Only the value TRUE is allowed for the NOT_NULL qualifier.

If this qualifier is specified, WMI does not allow creation of instances with the property set to NULL, and NULL properties return the WBEM_E_ILLEGAL_NULL error code.

Note that the Key and Indexed qualifiers already imply this behavior.
PROVIDER Populates those elements in the schemas that refer to dynamic data.

This qualifier is an implementation-specific handle to the instrumentation.
SYNTAX Specific type assigned to a data item.

Usage Rule: You must use the SYNTAXTYPE qualifier with this qualifier.
SYNTAXTYPE Defines the format of the SYNTAX qualifier.

Usage Rule: You must use the SYNTAX qualifier with this qualifier.
TRIGGERTYPE Indicates the circumstances under which a trigger is fired.

Usage Rule: The trigger types vary by meta-model construct.

For classes and associations, the legal values are:

Create
Delete
Update
Access

For properties and references, the legal values are: Update and Access.

For methods, the legal values are Before and After.

For indications, the legal value is Thrown.
UNKNOWN
VALUES 		Indicates that the value of the associated property is unknown (the property cannot be considered as having a valid or meaningful value).

The conventions and restrictions used for defining unknown values are the same as those applicable to the VALUEMAP qualifier.

Note this qualifier cannot be overridden. It is unreasonable to permit a subclass to treat a value that is treated as unknown by some superclass as a known value.
UNSUPPORTEDVALUES Defines a set of values that indicate that the value of the associated property is unsupported (the property cannot be considered as having a valid or meaningful value).

The conventions and restrictions used for defining unsupported values are the same as those applicable to the VALUEMAP qualifier.

Note this qualifier cannot be overridden. It is unreasonable to permit a subclass to treat a value that is treated as unknown by some superclass as a supported value.


WMI-Specific Qualifiers

Qualifier | Description
AMENDMENT Indicates that a class contains amended qualifiers that have been localized.

The associated class can be translated; the translated version can be accessed by constructing a namespace name by using the locale identifier.
BITMAP Indicates that the associated property is a bitmap.

The values indicate the valid bits in the bitmap
BITVALUES | Provides symbolic representation of bitmap values as found in the bitmap qualifier.
CIM_KEY | Indicates that the associated property is a key in the CIM but not in WMI.
CIMTYPE Contains text describing the type of a property.

This text can be the MOF type such as "string" and "sint32" or the CIM type such as CIM_STRING and CIM_SINT32. There is a one-to-one correspondence between the CIMTYPE qualifier and the type of the property used in the pvtType parameter of the IWbemClassObject::Get method. The two exceptions are:

• Reference properties, which have the type CIM_REFERENCE. • Embedded object properties, which have the CIM_OBJECT type.

Please note however, that the CIMTYPE qualifier can and should be used to type a reference property more exactly. For example, if the property always refers to instances of the Win32_LogicalDisk class, its Cimtype qualifier should be set to:

"ref:Win32_LogicalDisk".

By default, the CIMTYPE qualifier of a reference property has the type ref.

As with reference properties, the CIMTYPE qualifier should used to type an embedded object property more exactly with the following syntax:

"object:EmbedClass"

Because WMI allows more types than can be expressed by standard constants with the VT_ prefix, the Cimtype qualifier can help interpret type values. The Cimtype qualifier is added automatically. For more information, see MOF Data Types.
CLASSCONTEXT | Indicates a class that has instances associated with additional information dynamically supplied by a provider.
DEPRECATED | Indicates the property has been superceded by another property.
DISPLAY | The UUID of the associated class.
DYNAMIC Indicates a class, whose instances are created dynamically. The value of this qualifier must be set to TRUE.

The DYNAMIC qualifier must be specified on all classes that contain data and for which instances are created dynamically. The PROVIDER qualifier is typically also specified to identify the provider responsible for supplying the data.

Classes that contain only methods that need implementation do not require the DYNAMIC qualifier. Only the PROVIDER qualifier is required to specify the name of the provider to supply the implementation.

When DYNAMIC is specified on a property of an instance, the PROPERTYCONTEXT qualifier must also be specified.
DYNPROPS Indicates that an instance contains values provided by dynamic property providers.

You must specify this qualifier on such an instance. Only the value TRUE is allowed.
ID Uniquely identifies and sequences a property or method parameter when MOF statements are generated automatically.

This qualifier is required for method parameters only. When creating parameters for a method, class designers should begin with Id(1) for the first parameter and use each successive integer for each successive parameter. If the ID qualifiers are unintentionally omitted, the MOF compiler generates ID qualifiers automatically.
IMPLEMENTED | Indicates that a method has an implementation supplied by a provider.
INSTANCECONTEXT Indicates that an instance contains values provided by a dynamic property provider.

The value is passed to the property provider as an argument to the IWbemPropertyProvider::GetProperty method.
LOCALE | Specifies the language of origin for a class or instance.
OPTIONAL | Indicates that a parameter is not required, and that it has a well-behaved default value.
PRIVILEGES | Used to inform the client which privileges are required to create instances, fill in properties, or perform methods.
PROPERTYCONTEXT Indicates that an instance property contains values provided by dynamic property providers.

You must specify this qualifier on such a property. The value is passed to the property provider as an argument to IWbemPropertyProvider::GetProperty.
PROVIDER Indicates that class instances are provided dynamically.

The value of this qualifier is the name of the dynamic provider that provides class instances. This name must be registered with WMI by creating an instance of the __Win32Provider class with the Name property containing this name. When this qualifier is specified on a class whose instances are provided dynamically, the DYNAMIC qualifier must also be specified.
SINGLETON Designates a class that can only have one instance and that does not contain key properties.

Only the value TRUE is allowed.
STATIC Indicates that a method can called by using the class definition or its instances.

The method cannot be invoked from an instance.
SUBTYPE Indicates that a property of type CIM_DATETIME represents a time interval rather than a specific time.

To identify the property as an interval, the value of this qualifier must be "interval" .All other values for this qualifier are reserved for future use.
UUID | A universally unique identifier applied to the class.
WRITEPRIVILEGES | Specifies which system privileges must be available and enabled for a successful write operation.


Provider Framework Classes

The provider framework implements the following classes.

Framework class | Description
CWbemProviderGlue | Implements IWbemProviderInit and methods that control the loading and unloading of the framework provider.
Provider | Contains helper functions and provides default implementations of the methods of IWbemServices.
CInstance | Contains methods for setting and retrieving properties and is an encapsulation of the IWbemClassObject interface. Implementer should not have to access IWbemClassObject methods directly.
CFrameworkQuery | Contains methods for query processing.
CThreadBase | Supports thread safety. Serves as the base class for the TrefPointerCollection and Provider classes.
MethodContext | Wrapper object for the IWbemContext pointer that is passed from Windows Management Instrumentation (WMI) to a framework provider. Helps in threading issues.

Note that many of the framework methods use CHString parameters. CHString supports many of the same methods and properties as the Microsoft® Foundation Classes (MFC), but without the overhead of MFC. For more information on CHString, see CHString Class Reference.


CInstance Class Methods

The CInstance class is used to retrieve and update the values of properties defined for the instances supported by the framework provider. The CInstance class also provides access to the provider framework's implementation of the CInstance interface.

Methods

CInstance methods | Description
Commit | Returns the current instance to WMI.
Getbool | Retrieves a Boolean property.
GetByte | Retrieves a BYTE-compatible property.
GetCHString | Retrieves a string property.
GetClassObjectInterface | Returns an IWbemClassObject interface pointer.
GetDateTime | Returns a datetime property.
GetDOUBLE | Retrieves a DOUBLE property.
GetDWORD | Retrieves a DWORD property.
GetEmbeddedObject | Retrieves an embedded CInstance property.
GetMethodContext | Returns a pointer to a MethodContext object.
GetStatus | Determines whether a property exists and, if so, determines its type.
GetStringArray | Retrieves a property that represents an array of strings.
GetTimeSpan | Retrieves a property that represents a WMI time span.
GetVariant | Retrieves a VARIANT property.
GetWBEMINT16 | Retrieves a 16-bit integer property.
GetWBEMINT64 | Retrieves a 64-bit integer property.
GetWCHAR | Retrieves a WCHAR string property.
GetWORD | Retrieves a WORD property.
IsNull | Determines if the value of a particular property is NULL.
Setbool | Sets a Boolean property.
SetByte | Sets a BYTE property.
SetCharSplat | Sets a string property.
SetCHString | Sets a string property.
SetDateTime | Sets a datetime property.
SetDOUBLE | Sets a DOUBLE property.
SetDWORD | Sets a DWORD property.
SetEmbeddedObject | Sets an embedded CInstance property.
SetNull | Sets a property to NULL.
SetStringArray | Sets a property that represents an array of strings.
SetTimeSpan | Sets a property that represents a time span.
SetVariant | Sets a VARIANT property.
SetWBEMINT16 | Sets a 16-bit integer property.
SetWBEMINT64 | Sets a 64-bit integer property.
SetWCHARSplat | Sets a string property.
SetWORD | Sets a WORD property.


CInstance::Commit

The Commit method returns the current instance to WMI.

HRESULT Commit(
);

Parameters

None.

Return Values

Use the SUCCEEDED or FAILED macro on the returned HRESULT to determine success or failure of the method.

Remarks

If the client cancels the query, the Commit method will return an error. A provider writer can use this fact to terminate an enumeration.

Also, framework providers should call this method to commit rather than Provider::Commit. Provider::Commit calls CInstance::Release automatically. Smart CInstance pointers cannot be used in this case because the smart CInstance pointer would call CInstance::Release in its destructor. If the release has already occurred, an exception will result. Issues of this type are best resolved by allowing the CInstance instance, or a smart pointer to it, to perform the CInstance::Release when it is appropriate.


CInstance::Getbool

The Getbool method retrieves a Boolean property.

bool Getbool(
  LPCWSTR name,
  bool& b
) const;

Parameters

name
Name of the property retrieved.
b
Buffer to receive the Boolean property.

Return Values

Returns TRUE if the operation was successful and FALSE if an attempt was made to retrieve a non-Boolean property or a nonexistent property. More information is available in the log file, Framework.log.


CInstance::GetByte

The GetByte method retrieves a BYTE-compatible property.

bool GetByte(
  LPCWSTR name,
  BYTE& b
) const;

Parameters

name
Name of property retrieved.
b
Buffer to receive the BYTE-compatible property.

Return Values

Returns TRUE if the operation was successful and FALSE if an attempt was made to retrieve a property that is not BYTE-compatible or a property that doesn't exist. More information is available in the log file, Framework.log.


CInstance::GetCHString

The GetCHString method retrieves a string property.

bool GetCHString(
  LPCWSTR name,
  CHString& str
) const;

Parameters

name
Name of the string property retrieved.
str
Buffer to receive the string property.

Return Values

Returns TRUE if the operation was successful and FALSE if an attempt was made to retrieve a non-string property or a nonexistent property. More information is available in the log file, Framework.log.


CInstance::GetClassObjectInterface

The GetClassObjectInterface method returns an IWbemClassObject interface pointer.

IWbemClassObject* GetClassObjectInterface(
);

Parameters

None.

Return Values

Returns an IWbemClassObject interface pointer.

Remarks

The framework provider probably will never call GetClassObjectInterface, but if it does, it is responsible for releasing the IWbemClassObject pointer by calling its Release method.


CInstance::GetDateTime

The GetDateTime method returns a datetime property.

bool GetDateTime(
  LPCWSTR name,
  WBEMTime& wbemtime
) const;

Parameters

name
Name of the datetime property retrieved.
wbemtime
Buffer to receive the datetime property.

Return Values

Returns TRUE if the operation was successful and FALSE if an attempt was made to retrieve a property that is not a datetime value or a property that does not exist. More information is available in the log file, Framework.log.


CInstance::GetDOUBLE

The GetDOUBLE method retrieves a DOUBLE property.

bool GetDOUBLE(
  LPCWSTR name,
  DOUBLE& d
) const;

Parameters

name
Name of the DOUBLE property retrieved.
n
Buffer to receive the DOUBLE property.

Return Values

Returns TRUE if the operation was successful and FALSE if an attempt was made to retrieve a property that is not a DOUBLE-compatible type or a property that does not exist. More information is available in the log file, Framework.log.


CInstance::GetDWORD

The GetDWORD method retrieves a DWORD property.

bool GetDWORD(
  LPCWSTR name,
  DWORD& d
) const;

Parameters

name
Name of the DWORD property retrieved.
d
Buffer to receive the DWORD property.

Return Values

Returns TRUE if the operation was successful and FALSE if an attempt was made to retrieve a property that is not a type that is DWORD-compatible or a property that does not exist. More information is available in the log file, Framework.log.


CInstance::GetEmbeddedObject

The GetEmbeddedObject method retrieves an embedded CInstance property.

bool CInstance::GetEmbeddedObject(
  LPCWSTR name,
  CInstance** pInstance,
  MethodContext* pMethodContext
) const;

Parameters

name
Name of the CInstance property retrieved.
pInstance
Buffer that receives the embedded CInstance property.
pMethodContext
Additional information communicated to the provider.

Return Values

Returns TRUE if the operation was successful and FALSE if an attempt was made to retrieve a property that is not a CInstance-compatible type or a property that does not exist. More information is available in the log file, Framework.log.


CInstance::GetMethodContext

The GetMethodContext method returns a pointer to a MethodContext object.

MethodContext* GetMethodContext() const;

Parameters

None.

Return Values

Returns a pointer to the current MethodContext object.

Remarks

Framework providers should not release the MethodContext pointer returned by this function.


CInstance::GetStatus

The GetStatus method determines whether a property exists and, if so, determines its type.

bool CInstance::GetStatus(
  LPCWSTR name,
  bool& a_Exists,
  VARTYPE& a_VarType
) const;

Parameters

name
Name of the property to verify.
a_Exists
TRUE if property exists and FALSE if the property does not exist.
a_VarType
Type of property.

Return Values

Returns TRUE if the operation was successful and FALSE otherwise.


CInstance::GetStringArray

The GetStringArray method retrieves a property that represents an array of strings.

bool CInstance::GetStringArray(
  LPCWSTR name,
  SAFEARRAY*& strArray
) const;

Parameters

name
Name of the string array property retrieved.
strArray
Buffer to receive the array of strings.

Return Values

Returns TRUE if the operation was successful and FALSE if the supplied string array type is not valid for the property being returned or an attempt is made to retrieve a nonexistent property. More information is available in the log file, Framework.log.


CInstance::GetTimeSpan

The GetTimeSpan method retrieves a property that represents a WMI time span.

bool GetTimeSpan(
  LPCWSTR name,
  WBEMTimeSpan& wbemtimespan
) const;

Parameters

name
Name of the time span property retrieved.
wbemtimespan
Buffer to receive the time span property.

Return Values

Returns TRUE if the operation was successful and FALSE if the supplied time span type is not valid for the property being returned or an attempt is made to retrieve a nonexistent property. More information is available in the log file, Framework.log.


CInstance::GetVariant

The GetVariant method retrieves a VARIANT property.

bool GetVariant(
  LPCWSTR name,
  VARIANT& variant
) const;

Parameters

name
Name of the VARIANT property retrieved.
variant
Buffer to receive the VARIANT property.

Return Values

Returns TRUE if the operation was successful and FALSE if an attempt was made to retrieve a nonexistent property or a property with an incompatible data type. More information is available in the log file, Framework.log.


CInstance::GetWBEMINT16

The GetWBEMINT16 method retrieves a 16-bit integer property.

bool GetWBEMINT16(
  LPCWSTR name,
  WBEMINT16& wbemint16
) const;

Parameters

name
Name of the 16-bit integer property retrieved.
wbemint16
Buffer to receive the 16-bit integer property.

Return Values

Returns TRUE if the operation was successful and FALSE if an attempt was made to retrieve a nonexistent property or a property that was not a 16-bit integer. More information is available in the log file, Framework.log.


CInstance::GetWBEMINT64

The GetWBEMINT64 method retrieves a 64-bit integer property.

bool GetWBEMINT64(
  LPCWSTR name,
  WBEMINT64& wbemint64
) const;
bool GetWBEMINT64(
  LPCWSTR name,
  LONGLONG& i64Value
) const;
bool GetWBEMINT64(
  LPCWSTR name,
  ULONGLONG& i64Value
) const;

Parameters

name
Name of the 64-bit integer property retrieved.
wbemint64
Buffer to receive the 64-bit integer property.
i64Value
Buffer to receive the 64-bit integer property.

Return Values

Returns TRUE if the operation was successful and FALSE if an attempt was made to retrieve a nonexistent property or a property that was not a 64-bit integer. More information is available in the log file, Framework.log.

Remarks

The provider framework currently returns a CHString value rather than a WBEMINT64 value.


CInstance::GetWCHAR

The GetWCHAR method retrieves a WCHAR string property.

bool CInstance::GetWCHAR(
  LPCWSTR name,
  WCHAR** pw
) const;

Parameters

name
Name of the WCHAR string property retrieved.
pw
Buffer that receives the WCHAR string property.

Return Values

Returns TRUE if the operation was successful and FALSE if an attempt was made to retrieve a property that is not a type that is WCHAR string-compatible or a property that does not exist. More information is available in the log file, Framework.log.

Remarks

It is the responsibility of the implementer to free the memory occupied by the WCHAR string:

    free(pw);

Use free rather than delete because the Provider Framework allocates the string using malloc and does not use the new operator.


CInstance::GetWORD

The GetWORD method retrieves a WORD property.

bool GetWORD(
  LPCWSTR name,
  WORD& n
) const;

Parameters

name
Name of the WORD property retrieved.
n
Buffer that receives the WORD property.

Return Values

Returns TRUE if the operation was successful and FALSE if an attempt was made to retrieve a property that is not a type that is WORD-compatible or a property that does not exist. More information is available in the log file, Framework.log.


CInstance::IsNull

The IsNull method determines if the value of a particular property is NULL.

bool CInstance:IsNull(
  LPCWSTR name
  ) const;

Parameters

name
Name of property that is checked.

Return Values

Returns TRUE if the property specified by name is NULL and FALSE if it is not.


CInstance::Setbool

The Setbool method sets a Boolean property.

bool Setbool(
  LPCWSTR name,
  bool b
);

Parameters

name
Name of the Boolean property that is set.
b
Value assigned to the Boolean property.

Return Values

Returns TRUE if the operation was successful and FALSE if an attempt was made to set a non-Boolean property or a property that does not exist. More information is available in the log file, Framework.log.


CInstance::SetByte

The SetByte method sets a BYTE property.

bool SetByte(
  LPCWSTR name,
  BYTE b
);

Parameters

name
Name of the BYTE property that is set.
b
Value assigned to the BYTE property.

Return Values

Returns TRUE if the operation was successful and FALSE if an attempt was made to set a nonexistent property or a property that is not BYTE compatible. More information is available in the log file, Framework.log.


CInstance::SetCharSplat

The SetCharSplat method sets a string property.

bool SetCharSplat (
  LPCWSTR name,
  DWORD dwResID
);
bool SetCharSplat (
  LPCWSTR name,
  LPCWSTR pStr
);
bool SetCharSplat (
  LPCWSTR name,
  LPCSTR pStr
);

Parameters

name
Name of the string property that is set.
dwResID
Resource ID of new string value.
pStr
Pointer to the new string value.

Return Values

Returns TRUE if the operation was successful and FALSE if an attempt was made to set a nonexistent or non-string property. More information is available in the log file, Framework.log.


CInstance::SetCHString

The SetCHString method sets a string property.

bool SetCHString(
  LPCWSTR name,
  LPCWSTR str
);
bool SetCHString(
  LPCWSTR name,
  const CHString& str
);
bool SetCHString(
  LPCWSTR name,
  LPCSTR str
);

Parameters

name
Name of the string property that is set.
str
Value assigned to the string property.

Return Values

Returns TRUE if the operation was successful and FALSE if an attempt was made to set a nonexistent or non-string property. More information is available in the log file, Framework.log.


CInstance::SetDateTime

The SetDateTime method sets a datetime property.

bool SetDateTime(
  LPCWSTR name,
  const WBEMTime& wbemtime
);

Parameters

name
Name of the datetime property that is set.
wbemtime
Value assigned to the datetime property.

Return Values

Returns TRUE if the operation was successful and FALSE if an attempt was made to set a nonexistent or non-datetime property. More information is available in the log file, Framework.log.

Note The wbemtime argument will be converted to local time, and any arbitrary offsets will be lost.


CInstance::SetDOUBLE

The SetDOUBLE method sets a DOUBLE property.

bool SetDOUBLE(
  LPCWSTR name,
  DOUBLE d
);

Parameters

name
Name of the DOUBLE property that is set.
d
Value assigned to the DOUBLE property.

Return Values

Returns TRUE if the operation was successful and FALSE if an attempt was made to set a nonexistent or non-DOUBLE property. More information is available in the log file, Framework.log.


CInstance::SetDWORD

The SetDWORD method sets a DWORD property.

bool SetDWORD(
  LPCWSTR name,
  DWORD d
);

Parameters

name
Name of the DWORD property that is set.
d
Value assigned to the DWORD property.

Return Values

Returns TRUE if the operation was successful and FALSE if an attempt was made to set a nonexistent or non-DWORD property. More information is available in the log file, Framework.log.


CInstance::SetEmbeddedObject

The SetEmbeddedObject method sets an embedded CInstance property.

bool CInstance::SetEmbeddedObject(
  LPCWSTR name,
  CInstance& cInstance
);

Parameters

name
Name of the CInstance property that is set.
cInstance
Value assigned to the embedded CInstance property.

Return Values

Returns TRUE if the operation was successful and FALSE if an attempt was made to set a nonexistent or non-CInstance property. More information is available in the log file, Framework.log.


CInstance::SetNull

The SetNull method sets a property to NULL.

bool CInstance::SetNull(
  LPCWSTR name
);

Parameters

name
Name of the property to set to NULL.

Return Values

Returns TRUE if the operation was successful and FALSE if an attempt was made to set a nonexistent property. More information is available in the log file, Framework.log.


CInstance::SetStringArray

The SetStringArray method sets a property that represents an array of strings.

bool CInstance::SetStringArray(
  LPCWSTR name,
  const SAFEARRAY& strArray
);

Parameters

name
Name of the property that is set to an array of strings.
strArray
Value assigned to the array of strings.

Return Values

Returns TRUE if the operation was successful and FALSE if an attempt was made to set a nonexistent property or a property that is not an array of strings. More information is available in the log file, Framework.log.


CInstance::SetTimeSpan

The SetTimeSpan method sets a property that represents a time span.

bool SetTimeSpan(
  LPCWSTR name,
  const WBEMTimeSpan& wbemtimespan
);

Parameters

name
Name of the property that is set.
wbemtimespan
Value assigned to the time span property.

Return Values

Returns TRUE if the operation was successful and FALSE if an attempt was made to set a nonexistent property or a property that is not a time span value. More information is available in the log file, Framework.log.


CInstance::SetVariant

The SetVariant method sets a VARIANT property.

bool SetVariant(
  LPCWCSTR name,
  const VARIANT& variant
);

Parameters

name
Name of the VARIANT property that is set.
variant
Value assigned to the VARIANT property.

Return Values

Returns TRUE if the operation was successful and FALSE if the supplied variant type is not correct for the property being set. SetVariant also returns FALSE if an attempt is made to set a nonexistent property. More information is available in the log file, Framework.log.


CInstance::SetWBEMINT16

The SetWBEMINT16 method sets a 16-bit integer property.

bool SetWBEMINT16(
  LPCWSTR name,
  const WBEMINT16& wbemint16
);

Parameters

name
Name of the 16-bit integer property that is set.
wbemint16
Value assigned to the 16-bit integer property.

Return Values

Returns TRUE if the operation was successful and FALSE if an attempt was made to set a nonexistent property or a property that is not a 16-bit integer. More information is available in the log file, Framework.log.


CInstance::SetWBEMINT64

The SetWBEMINT64 method sets a 64-bit integer property.

bool SetWBEMINT64(
  LPCWSTR name,
  const WBEMINT64& wbemint64
);

bool SetWBEMINT64(
  LPCWSTR name,
  const LONGLONG wbemint64
);
bool SetWBEMINT64(
  LPCWSTR name,
  const ULONGLONG __int64 wbemint64
);

Parameters

name
Name of the 64-bit integer property that is set.
wbemint64
Value assigned to the 64-bit integer property.

Return Values

Returns TRUE if the operation was successful and FALSE if an attempt was made to set a nonexistent property or a property that is not a 64-bit integer. More information is available in the log file, Framework.log.

Remarks

The provider framework currently uses a CHString type to set the 64-bit integer rather than a WBEMINT64 type.


CInstance::SetWCHARSplat

The SetWCHARSplat method sets a string property.

bool SetWCHARSplat(
  LPCWSTR name,
  LPCWSTR pStr
);

Parameters

name
Name of the string property to be modified.
pStr
Pointer to the Unicode string.

Return Values

Returns TRUE if the operation was successful and FALSE if an attempt was made to set a nonexistent or non-string property. More information is available in the log file, Framework.log.


CInstance::SetWORD

The SetWORD method sets a WORD property.

bool SetWORD(
  LPCWSTR name,
  WORD n
);

Parameters

name
Name of the WORD property that is set.
n
Value assigned to the WORD property.

Return Values

Returns TRUE if the operation was successful and FALSE if an attempt was made to set a nonexistent or non-WORD property. More information is available in the log file, Framework.log.


Provider Class Methods

The Provider class is the base class for the class or classes that the framework provider supports. The Provider class encapsulates implementations of the methods of IWbemServices and includes several helper functions. A framework provider overrides one of the methods of the Provider class for each feature that it supports. For example, a provider that supports query processing overrides the Provider::ExecQuery method. Unlike Windows Management Instrumentation (WMI) providers created without the help of the provider framework, framework providers implement the synchronous versions of the IWbemServices methods.

An instance of the Provider class is created for each framework provider.

Methods

Provider methods | Description
Commit | Returns the current instance to WMI.
CreateNewInstance | Allocates a new CInstance object and returns a pointer to it.
DeleteInstance | WMI calls the DeleteInstance method to delete an instance.
EnumerateInstances | Retrieves all instances of a framework provider's class. Called by WMI.
ExecMethod | Invokes a method on a class or instance. Called by WMI.
ExecQuery | Processes a WQL query. Called by WMI.
Flush | Called by the Provider Framework to delete all unnecessary memory in use by the provider.
GetLocalComputerName | Returns a constant reference to the computer name in CHString format.
GetLocalInstancePath | Attempts to build a full object path to a specified instance.
GetObject | Retrieves an instance of a class. Called by WMI.
GetProviderName | Retrieves the name of the provider.
MakeLocalPath | Builds a full instance path from a relative path.
PutInstance | Updates an instance.
SetCreationClassName | Sets the CreationClassName string property of the given instance to the name of this provider.
ValidateDeletionFlags | Determines whether a set of flags is valid for a delete operation.
ValidateEnumerationFlags | Determines whether a set of flags is valid for an enumeration.
ValidateFlags | Determines whether a set of flags is valid.
ValidateGetObjFlags | Determines whether a set of flags is valid for an instance retrieval operation.
ValidateMethodFlags | Determines whether a set of flags is valid for an execute method operation.
ValidatePutInstanceFlags | Determines whether a set of flags is valid for an instance update operation.
ValidateQueryFlags | Determines whether a set of flags is valid for a query operation.


Provider::Commit

The Commit method is used to send an instance to WMI. Commit is a helper function and should not be overridden.

HRESULT Commit(
  CInstance *pInstance,
  bool bCache = false
);

Parameters

pInstance
Pointer to the instance to be stored by WMI.
bCache
An indicator of whether a cache is implemented. This value must be set to FALSE in the current version of the provider framework.

Return Values

Use the SUCCEEDED or FAILED macros on the returned HRESULT to determine if the method was successful.

Remarks

If the client cancels the query, the Commit method will return an error. A provider writer can use this fact to terminate an enumeration.

Also, this method calls CInstance::Release on the pInstance pointer. Because of this, the framework provider must be careful not to call CInstance::Release again. This means that a pInstance smart pointer is incompatible with this method since the smart pointer will call CInstance::Release in its destructor.

This method should only be used when the framework provider does not wish to call CInstance::Release on the pInstance pointer and if the pInstance pointer is not, and will never be, a smart pointer.


Provider::CreateNewInstance

The CreateNewInstance method allocates a new CInstance object and returns a pointer to it.

CInstance* CreateNewInstance(
  MethodContext *pMethodContext
);

Parameters

pMethodContext
Pointer to the context associated with this instance.

Return Values

Returns a pointer to the new instance.

Remarks

The caller is responsible for calling either CInstance::Release or Provider::Commit on the returned pointer. Either of these methods may be used but they are not interchangeable. Refer to the Remarks on each of these methods to determine which is appropriate.

This method will not return a NULL pointer. If it's going to fail, it will throw an exception.


Provider::DeleteInstance

WMI calls the DeleteInstance method to delete an instance.

HRESULT DeleteInstance(
  const CInstance& Instance,
  long lFlags = 0L
);

Parameters

Instance
Instance to be deleted.
lFlags
A bitmask of flags with information about the Delete operation. This is the value specified by the client in the IWbemServices::DeleteInstance function.

The following flag is handled by (and filtered out) by WMI:

WBEM_FLAG_RETURN_IMMEDIATELY

Return Values

The default Framework Provider implementation of this method returns WBEM_E_PROVIDER_NOT_CAPABLE to the calling function. The provider developer commonly returns values listed in the documentation for IWbemServices::DeleteInstance, but can return any other COM return code.

Remarks

Framework providers that allow instances to be deleted must override this method. See IWbemServices::DeleteInstance for information about deleting instances.


Provider::EnumerateInstances

WMI calls the EnumerateInstances method to retrieve all instances of a framework provider's class.

HRESULT EnumerateInstances(
  MethodContext *pMethodContext,
  long lFlags = 0L
);

Parameters

pMethodContext
Pointer to the context object for this call. This value will contain any IWbemContext properties specified by the client. Also this pMethodContext must be used as a parameter to any calls back into WMI.
lFlags
A bitmask of flags with information about the EnumerateInstances operation. This is the value specified by the client in the IWbemServices::CreateInstanceEnum function.

The following flags are handled by (and filtered out) by WMI:

WBEM_FLAG_DEEP
WBEM_FLAG_SHALLOW
WBEM_FLAG_RETURN_IMMEDIATELY
WBEM_FLAG_FORWARD_ONLY
WBEM_FLAG_BIDIRECTIONAL
WBEM_FLAG_USE_AMENDED_QUALIFIERS

Return Values

The default Framework Provider implementation of this method returns WBEM_E_PROVIDER_NOT_CAPABLE to the calling function. The provider developer commonly returns values listed in the documentation for IWbemServices::CreateInstanceEnum, but can return any other COM return code.

Remarks

To override this method, a framework provider creates, populates, and commits one CInstance class instance for each instance of the provider's supported class.

It is not an error for EnumerateInstances to return zero instances by instantiating zero CInstance instances and setting the return value to WBEM_S_NO_ERROR.


Provider::ExecMethod

WMI calls the ExecMethod method to invoke a method on a class or instance.

HRESULT ExecMethod(
  const CInstance& Instance,
  const BSTR bstrMethodName,
  CInstance *pInParams,
  CInstance *pOutParams,
  long lFlags = 0L
);

Parameters

Instance
Instance on which the method should be invoked.
bstrMethodName
Name of the method that is invoked.
pInParams
Pointer to the input parameters of the method.
pOutParams
Pointer to the method output parameters.
lFlags
A bitmask of flags with information about the ExecMethod operation. This is the value specified by the client in the IWbemServices::ExecMethod function.

The following flag is handled by (and filtered out) by WMI:

WBEM_FLAG_RETURN_IMMEDIATELY

Return Values

The default Framework Provider implementation of this method returns WBEM_E_PROVIDER_NOT_CAPABLE to the calling function. The provider developer commonly returns values listed in the documentation for IWbemServices::ExecMethod, but can return any other COM return code.

Remarks

Framework method providers must override this method and supply their own implementation. See IWbemServices::ExecMethod for more information.


Provider::ExecQuery

WMI calls the ExecQuery method to process a WQL query.

HRESULT ExecQuery(
  MethodContext *pMethodContext,
  CFrameworkQuery& Query,
  long lFlags
);

Parameters

pMethodContext
Pointer to the context object for this call. This value will contain any IWbemContext properties specified by the client. Also this pMethodContext must be used as a parameter to any calls back into WMI.
Query
Pointer to a query that has already been parsed by the provider framework.
lFlags
A bitmask of flags with information about the ExecQuery operation. This is the value specified by the client in the IWbemServices::ExecQuery function.

The following flags are handled by (and filtered out) by WMI:

WBEM_FLAG_ENSURE_LOCATABLE
WBEM_FLAG_FORWARD_ONLY
WBEM_FLAG_BIDIRECTIONAL
WBEM_FLAG_USE_AMENDED_QUALIFIERS
WBEM_FLAG_RETURN_IMMEDIATELY
WBEM_FLAG_PROTOTYPE

Return Values

The default Framework Provider implementation of this method returns WBEM_E_PROVIDER_NOT_CAPABLE to the calling function. The provider developer commonly returns values listed in the documentation for IWbemServices::ExecQuery, but can return any other COM return code.

Remarks

Framework providers should override the Provider::ExecQuery method in their classes if they want to support query processing. If they do not want to support query processing, they can return WBEM_E_NOT_SUPPORTED.

The Provider::ExecQuery method calls the framework provider's version of ExecQuery. If the framework provider's ExecQuery returns WBEM_E_NOT_SUPPORTED, Provider::ExecQuery relies on WMI to handle the query. WMI does this by calling Provider::CreateInstanceEnum to provide all the instances. These instances are then filtered by WMI before returning them to the client.

Only queries containing a WHERE clause will cause a call to this method.

For more information on the query parameter see CFrameworkQuery.


Provider::Flush

The Provider Framework calls the Flush method to delete all unnecessary memory in use by the provider.

void Flush();

Parameters

None.

Return Values

None.

Remarks

Override this method only if your framework provider allocates memory that can be flushed. If your provider chooses to override, include a call to Provider::Flush in the provider's implementation.

The current version of the provider framework does not support the cache.


Provider::GetLocalComputerName

The GetLocalComputerName method returns a constant reference to the computer name in CHString format.

const CHString& GetLocalComputerName();

Parameters

None.

Return Values

Returns a constant reference to the name of the computer.


Provider::GetLocalInstancePath

The GetLocalInstancePath method attempts to build a full object path to a specified instance. GetLocalInstancePath is a helper function and should not be overridden.

bool GetLocalInstancePath(
  const CInstance *pInstance,
  CHString& strPath
);

Parameters

pInstance
[in] Pointer to the instance that the path should be built for.
strPath
[out] Full object path, complete from the machine name to the key value.

Return Values

Returns TRUE if the operation was successful and FALSE if the operation was unsuccessful.


Provider::GetNamespace

The GetNamespace method returns a constant reference to the namespace name in CHString format.

const CHString& GetNamespace();

Parameters

None.

Return Values

Returns a constant reference to the namespace.


Provider::GetObject

WMI calls the GetObject method to retrieve an instance of a class.

HRESULT GetObject(
  CInstance *pInstance,
  long lFlags = 0L
);
HRESULT GetObject(
  CInstance *pInstance,
  long lFlags,
  CFrameworkQuery& Query
);

Parameters

pInstance
Pointer to a CInstance object to be filled in by the framework provider.
lFlags
A bitmask of flags with information about the GetObject operation. This is the value specified by the client in the IWbemServices::GetObject function.

The following flags are handled by (and filtered out) by WMI:

WBEM_FLAG_USE_AMENDED_QUALIFIERS
WBEM_FLAG_RETURN_WBEM_COMPLETE
WBEM_FLAG_RETURN_IMMEDIATELY

Query
A query object which indicates the set of properties to be populated, as is requested by a call to Provider::GetObject.

A provider can realize a significant performance gain by filling in only these requested property values. The provider determines which properties are requested by using CFrameworkQuery::IsPropertyRequired. Otherwise, the provider must fill in all property values.

Return Values

The default Framework Provider implementation of this method returns WBEM_E_PROVIDER_NOT_CAPABLE to the calling function. The provider developer commonly returns values listed in the documentation for IWbemServices::GetObject, but can return any other COM return code.

Remarks

Framework providers must override this method. Provider::GetObject provides an instance with only the key properties populated. The provider version of GetObject must fill in all of the other properties.


Provider::GetProviderName

The GetProviderName method retrieves the name of the class used in the constructor of the provider.

const CHString &GetProviderName();

Parameters

None.

Return Values

If successful, the method returns the name of the class used in the constructor of the provider as a CHString reference. The name returned is the first argument originally given to the Provider::Provider constructor.


Provider::MakeLocalPath

The MakeLocalPath method builds a full instance path from a relative path.

CHString MakeLocalPath(
  const CHString& strRelPath
);

Parameters

strRelPath
Relative path used to build the full path.

Return Values

Returns the full path in CHString format.

Remarks

Consider using GetLocalInstancePath before using this function.


Provider::PutInstance

The PutInstance method updates an instance.

HRESULT PutInstance(
  const CInstance& newInstance,
  long lFlags = 0L
);

Parameters

newInstance
Instance that is updated.
lFlags
A bitmask of flags with information about the PutInstance operation. This is the value specified by the client in the IWbemServices::PutInstance function.

The following flag is handled by (and filtered out) by WMI:

Flag values

WBEM_FLAG_RETURN_IMMEDIATELY

A bitmask of flags that provide information about the update operation. Valid values are:

WBEM_FLAG_CREATE_ONLY
WBEM_FLAG_CREATE_OR_UPDATE
WBEM_FLAG_UPDATE_ONLY

Return Values

The default Framework Provider implementation of this method returns WBEM_E_PROVIDER_NOT_CAPABLE to the calling function. The provider developer commonly returns values listed in the documentation for IWbemServices::PutInstance, but can return any other COM return code.

Remarks

Framework providers that allow instances to be updated must override this method. Their implementation of PutInstance should determine if the requested changes can be supported. If they cannot be supported, return an appropriate error code. See IWbemServices::PutInstance for a list of valid error codes.


Provider::SetCreationClassName

The SetCreationClassName method sets the CreationClassName string property, if any, of the given instance to the name of this provider.

bool SetCreationClassName(
  CInstance *pInstance
);

Parameters

pInstance
Pointer to the affected instance.

Return Values

Returns TRUE if the operation was successful and FALSE if it was unsuccessful.

Remarks

The SetCreationClassName method sets the value of the CreateClassName property to the name of the current class. Not all classes have a CreationClassName property.


Provider::ValidateDeletionFlags

The ValidateDeletionFlags method determines whether a set of flags is valid for a delete operation.

HRESULT ValidateDeletionFlags(
  long lFlags
);

Parameters

lFlags
A bitmask of flags that are validated.

Return Values

Returns WBEM_S_NO_ERROR if the flags are valid and WBEM_E_UNSUPPORTED_PARAMETER if one or more flags are invalid.

Remarks

At present, the Provider class does not support any deletion flags. Therefore, if lFlags is set to a value other than zero (0), Provider::ValidateDeletionFlags automatically returns WBEM_E_UNSUPPORTED_PARAMETER.

Framework providers must override this method to validate flags that are unknown to the base Provider class.


Provider::ValidateEnumerationFlags

The ValidateEnumerationFlags method determines whether a set of flags is valid for an enumeration.

HRESULT ValidateEnumerationFlags(
  long lFlags
);

Parameters

lFlags
A bitmask of flags that are validated.

Return Values

Returns WBEM_S_NO_ERROR if the flags are valid and WBEM_E_UNSUPPORTED_PARAMETER if one or more flags are invalid.

Remarks

At present, the Provider class does not support any enumeration flags. Therefore, if lFlags is set to a value other than zero, Provider::ValidateEnumerationFlags automatically returns WBEM_E_UNSUPPORTED_PARAMETER.

Framework providers must override this method to validate flags that are unknown to the base Provider class.


Provider::ValidateFlags

The ValidateFlags method determines whether a set of flags is valid.

HRESULT ValidateFlags(
  long lFlags,
  FlagDefs lAcceptableFlags
);

Parameters

lFlags
A bitmask of flags that are validated.
lAcceptableFlags
A bitmask of Iflag values that are acceptable to the calling function. The values are limited to the FlagDefs enumeration defined as
    enum FlagDefs
    {
        EnumerationFlags = 0,
        GetObjFlags = 0,
        MethodFlags = 0,
        DeletionFlags = 0,
        PutInstanceFlags = (WBEM_CREATE_ONLY |
                            WBEM_FLAG_CREATE_ONLY |
                            WBEM_FLAG_UPDATE_ONLY),
        QueryFlags = 0
    };.

Return Values

Returns WBEM_S_NO_ERROR if the flags are valid and WBEM_E_UNSUPPORTED_PARAMETER if one or more flags are invalid.

Remarks

This helper method can be called by an override of any of the following virtual methods to indicate which flags are acceptable as arguments to the virtual method:

Provider::ValidateDeletionFlags

Provider::ValidateEnumerationFlags

Provider::ValidateGetObjFlags

Provider::ValidateMethodFlags

Provider::ValidatePutInstanceFlags

Provider::ValidateQueryFlags


Provider::ValidateGetObjFlags

The ValidateGetObjFlags method determines whether a set of flags is valid for an instance retrieval operation.

HRESULT ValidateGetObjFlags(
  long lFlags
);

Parameters

lFlags
A bitmask of flags that are validated.

Return Values

Returns WBEM_S_NO_ERROR if the flags are valid and WBEM_E_UNSUPPORTED_PARAMETER if one or more flags are invalid.

Remarks

At present, the Provider class does not support any retrieval flags. Therefore, if lFlags is set to a value other than zero (0), Provider::ValidateGetObjFlags automatically returns WBEM_E_UNSUPPORTED_PARAMETER.

Framework providers must override this method to validate flags that are unknown to the base Provider class.


Provider::ValidateMethodFlags

The ValidateMethodFlags method determines whether a set of flags is valid for an execute method operation.

HRESULT ValidateMethodFlags(
  long lFlags
);

Parameters

lFlags
A bitmask of flags that are validated.

Return Values

Returns WBEM_S_NO_ERROR if the flags are valid and WBEM_E_UNSUPPORTED_PARAMETER if one or more flags are invalid.

Remarks

At present, the Provider class does not support any method flags. Therefore, if lFlags is set to a value other than zero (0), Provider::ValidateMethodFlags automatically returns WBEM_E_UNSUPPORTED_PARAMETER.

Framework providers must override this method to validate flags that are unknown to the base Provider class.


Provider::ValidatePutInstanceFlags

The ValidatePutInstanceFlags method determines whether a set of flags is valid for an instance update operation.

HRESULT ValidatePutInstanceFlags(
  long lFlags
);

Parameters

lFlags
A bitmask of flags that are validated.

Return Values

Returns WBEM_S_NO_ERROR if the flags are valid and WBEM_E_UNSUPPORTED_PARAMETER if one or more flags are invalid.

Remarks

Framework providers can override this method to validate flags that are unknown to the base Provider class. At present, the Provider class supports the following update flags:

WBEM_FLAG_CREATE_ONLY
WBEM_FLAG_CREATE_OR_UPDATE
WBEM_FLAG_UPDATE_ONLY


Provider::ValidateQueryFlags

The ValidateQueryFlags method determines whether a set of flags is valid for a query operation.

HRESULT ValidateQueryFlags(
  long lFlags
);

Parameters

lFlags
A bitmask of flags that are validated.

Return Values

Returns WBEM_S_NO_ERROR if the flags are valid and WBEM_E_UNSUPPORTED_PARAMETER if one or more flags are invalid.

Remarks

At present, the Provider class does not support any query flags. Therefore, if lFlags is set to a value other than zero (0), Provider::ValidateQueryFlags automatically returns WBEM_E_UNSUPPORTED_PARAMETER.

Framework providers must override this method to validate flags that are unknown to the base Provider class.


CFrameworkQuery Class Methods

The CFrameworkQuery class is used to parse and manipulate a query. It contains methods that return specific property values and methods that test the query to determine the particular properties that are included.

Methods

CFrameworkQuery methods | Description
AllPropertiesAreRequired | Indicates whether all of the properties for the instance are being requested.
GetRequiredProperties | Returns a list of all of the properties specified in the SELECT statement of a query. It will return the properties from both the SELECT and the WHERE clauses.
GetQuery | Retrieves the actual WQL command associated with the CFrameworkQuery object.
GetQueryClassName | Retrieves the class name from the query.
GetValuesForProp | Returns all of the values for a particular property that are generated by that property as it appears within the query.
IsPropertyRequired | Determines if a particular property was requested by the query. Both the SELECT and the WHERE clauses are checked.
KeysOnly | Indicates whether only the key properties are required.


CFrameworkQuery::AllPropertiesAreRequired

The AllPropertiesAreRequired method indicates whether all of the properties for the instance are being requested.

bool AllPropertiesAreRequired();

Parameters

None.

Return Values

Returns TRUE if all properties are required and FALSE if only a subset of the properties are required.


CFrameworkQuery::GetRequiredProperties

The GetRequiredProperties method returns a list of all of the properties specified in the SELECT statement of a query. It will return the properties from both the SELECT and the WHERE clauses.

void GetRequiredProperties(
  CHStringArray& saProperties
);

Parameters

saProperties
Array of properties that were included in the query's SELECT statement.

Return Values

None.

Remarks

If the saProperties array that is returned is empty, then all properties are required.


CFrameworkQuery::GetQuery

The GetQuery method retrieves the actual WQL command associated with the CFrameworkQuery object.

const CHString& GetQuery();

Parameters

None.

Return Values

Returns the WQL command if the operation was successful and NULL otherwise.

Remarks

If GetQuery is called within Provider::GetObject, the WSL command line will not contain a WHERE clause.


CFrameworkQuery::GetQueryClassName

The GetQueryClassName method retrieves the class name from the query.

BSTR GetQueryClassName();

Parameters

None.

Return Values

Returns the class name if the operation was successful and NULL otherwise.

Remarks

It is the programmer's responsibility to call ::SysFreeString() on the BSTR returned by this method to avoid a memory leak.


CFrameworkQuery::GetValuesForProp

The GetValuesForProp method returns all of the values for a particular property that are generated by that property as it appears within the query.

For example, a call to GetValuesForProp(L"Name", sa) will return the array sa, which will contain all the values of "Name" that require instances to be sent back in order to satisfy the query. If sa contains {"a","b"}, then all the instances where "Name=a" plus all the instances where "Name=b" must be sent back to completely satisfy the query.

If the constraints on "Name" are not sufficiently limiting, an empty sa array is returned.

HRESULT GetValuesForProp(
  LPCWSTR wszPropName,
  CHStringArray& aszNames
);

HRESULT GetValuesForProp(
  LPCWSTR wszPropName,
  std::vector<_bstr_t>& aszNames
);

Parameters

wszPropName
Name of the target property.
aszNames
Array of values for the property specified by wszPropName.

Return Values

This method returns WBEM_S_NO_ERROR or WBEM_S_PARTIAL_RESULTS on success, and WBEM_E_FAILED, or any other HRESULT error code, on failure.

Return code | Description
WBEM_E_FAILED | No values could be returned for the property.
WBEM_S_NO_ERROR | Values for the property specified by wszPropName were successfully returned.
WBEM_S_PARTIAL_RESULTS | Implies an additional element to aszNames, which is NULL.

Remarks

Given a property name, this method returns all of the result values in a CHStringArray or vector container. The vector container holds _bstr_t objects containing the result values.

For example, the following table indicates the values that would be returned by GetValuesForProp for a variety of queries when called with wszPropName set to "Drive".

Query | Results
Select * from Win32_Directory where Drive = "C:" | C:
Select * from Win32_Directory where Drive = "C:" or Drive = "D:" | C:, D:
Select * from Win32_Directory where Drive <> "C:" | No results; aszNames is empty.
Select * from Win32_Directory where Path = "\DOS" | No results; aszNames is empty.

Remarks

GetValuesForProp only supports string types. For example, a query of

select * from Test where PropInt = 32 and PropStr = "a"

followed by a call to GetValuesForProp("PropInt", values) returns WBEM_E_INVALID_QUERY while GetValuesForProp("PropStr", values) returns S_OK.

See Also

Provider::ExecQuery


CFrameworkQuery::IsPropertyRequired

The IsPropertyRequired method determines if a particular property was requested by the query. Both the SELECT and the WHERE clauses are checked.

bool IsPropertyRequired(
  LPCWSTR propName
);

Parameters

propName
Name of property that is checked.

Return Values

Returns TRUE if the property specified by propName was requested and FALSE if it was not requested.


CFrameworkQuery::KeysOnly

The KeysOnly method indicates whether only the key properties are required.

bool KeysOnly();

Parameters

None.

Return Values

Returns TRUE if only the key properties are required and FALSE if non-key properties are required.


CWbemProviderGlue Class Methods

The CWbemProviderGlue class ties the COM interfaces of the WMI API to the classes derived from the Provider class and supplies methods for providers to use to query each other.

Methods

CWbemProviderGlue methods | Description
FrameworkLoginDLL | Called when DLL_PROCESS_ATTACH is sent to DllMain to determine whether the provider server can be loaded.
FrameworkLogoffDLL | Called by DllCanUnloadNow to determine whether the provider server is not in use and can be unloaded.
GetAllDerivedInstances | Retrieves a list of instances derived from a particular base class.
GetAllDerivedInstancesAsynch | Retrieves a list of instances supported by a particular provider and derived from a particular base class. Returns one instance at a time.
GetAllInstances | Retrieves a list of instances supported by a particular provider.
GetAllInstancesAsynch | Retrieves a list of instances supported by a particular provider. Returns one instance at a time.
GetEmptyInstance | Retrieves a single instance from a particular provider.
GetInstanceByPath | Retrieves the instance identified by a particular object path.
GetInstanceKeysByPath | Retrieves the instance identified by a particular object path, with only the key properties populated.
GetInstancePropertiesByPath | Retrieves the instance identified by a particular object path, with only the specified properties populated.
GetInstancesByQuery | Retrieves a list of instances that match a particular query.
GetInstancesByQueryAsynch | Retrieves a list of instances supported by a particular provider that match a particular query. Returns one instance at a time.
IsDerivedFrom | Determines whether one class is derived from another.


CWbemProviderGlue::FrameworkLoginDLL

The FrameworkLoginDLL method is called when DLL_PROCESS_ATTACH is sent to DllMain to determine whether the provider server can be loaded.

static BOOL WINAPI CWbemProviderGlue::FrameworkLoginDLL(
  LPCWSTR name
);

Parameters

name
Name of the server that is loaded.

Return Values

The method returns TRUE if the server can be loaded and FALSE if the server cannot be loaded.

Remarks

FrameworkLoginDLL should be called from DllMain when the fdwReason parameter is DLL_PROCESS_ATTACH. If FrameworkLoginDLL returns FALSE, the server should return FALSE from DllMain to fail the load.


CWbemProviderGlue::FrameworkLogoffDLL

The FrameworkLogoffDLL method is called by DllCanUnloadNow to determine whether the provider server is not in use and can be unloaded.

static BOOL WINAPI CWbemProviderGlue::FrameworkLogoffDLL(
  LPCWSTR name
);

Parameters

name
The name of the server that is unloaded.

Return Values

The method returns TRUE if the server is not in use and can be unloaded and FALSE if the server is still in use and cannot be unloaded.

Remarks

For now, FrameworkLogoffDLL returns FALSE until the refcount for CWbemProviderGlue is zero. This approach prevents unloading any client DLL while instances of CWbemProviderGlue still exist.


CWbemProviderGlue::GetAllDerivedInstances

The GetAllDerivedInstances method retrieves a list of instances derived from a particular base class by calling the derived provider's EnumerateInstances method.

static HRESULT WINAPI GetAllDerivedInstances(
  LPCWSTR pszBaseClassName,
  TRefPointerCollection<CInstance> *pList,
  MethodContext *pMethodContext,
  LPCWSTR pszNamespace = NULL
);

Parameters

pszBaseClassName
Pointer to name of base class for which list should be returned.
pList
Pointer to linked list of instances derived from the class specified by pszBaseClassName.
pMethodContext
Pointer to the context for the instance. This parameter must not be NULL.
pszNamespace
Namespace of the class name specified by pszBaseClassName. When this parameter is NULL, the default namespace Root\Cimv2 will be used.

Return Values

The method returns WBEM_S_NO_ERROR if the operation was successful, WBEM_E_OUT_OF_MEMORY if the operation failed due to lack of memory, or any other HRESULT error code.

Remarks

GetAllDerivedInstances allows framework providers to access data from other providers. Framework providers pass the name of a base class to GetAllDerivedInstances, which returns a list of all of the instances that derive from it.

If a class has no derived classes, but if the framework provider normally provides instances of this class, these instances will be provided using this method.

The return codes include all the possible returns from IWbemServices::ExecQuery.

This method is semantically equivalent to the query SELECT * FROM pszBaseClassName.


CWbemProviderGlue::GetAllDerivedInstancesAsynch

The GetAllDerivedInstancesAsynch method retrieves a list of instances supported by a particular provider and derived from a particular base class by calling the derived provider's EnumerateInstances method. GetAllDerivedInstancesAsynch allows the provider to respond asynchronously by returning one instance at a time.

static HRESULT WINAPI GetAllDerivedInstancesAsynch(
  LPCWSTR pszClassName,
  Provider *pRequester,
  LPProviderInstanceCallback pCallback,
  LPCWSTR pszNamespace,
  MethodContext *pMethodContext,
  void* pUserData
);

Parameters

pszClassName
Name of base class for which list should be returned.
pRequester
Pointer for the callback function pointed to by pCallback.
pCallback
Pointer to a function that is called to return each instance supported by the provider specified by pszClassName.
pszNamespace
Namespace of the class name specified by pszClassName. When this parameter is NULL, the default namespace Root\Cimv2 will be used.
pMethodContext
Pointer to the context or NULL to indicate a lack of context.
pUserData
Pointer to user-defined data that is passed to the function pointed to by pCallback.

Return Values

The method returns WBEM_S_NO_ERROR if the operation was successful, WBEM_E_OUT_OF_MEMORY if the operation failed due to lack of memory, or any other HRESULT error code.

Remarks

GetAllDerivedInstancesAsynch allows framework providers to access data from another provider without having to make a WMI API call. The Framework providers pass the name of the provider to GetAllDerivedInstancesAsynch and GetAllDerivedInstancesAsynch calls the function specified by the pCallback parameter to return the instances that the provider supports.

This method is semantically equivalent to the query SELECT * FROM pszBaseClassName.


CWbemProviderGlue::GetAllInstances

The GetAllInstances method retrieves a list of instances supported by a particular provider by calling the provider's EnumerateInstances method.

static HRESULT WINAPI GetAllInstances(
  LPCWSTR pszClassName,
  TRefPointerCollection<CInstance> *pList,
  LPCWSTR pszNamespace,
  MethodContext *pMethodContext
);

Parameters

pszClassName
Name of class for which list of instances should be returned.
pList
Linked list of instances supported by the provider specified by pszClassName.
pszNamespace
Namespace of the provider specified by pszClassName. This parameter can be NULL to indicate the default namespace, which is Root\Cimv2.
pMethodContext
Pointer to the context or NULL to indicate a lack of context.

Return Values

The method returns WBEM_S_NO_ERROR if the operation was successful, WBEM_E_OUT_OF_MEMORY if the operation failed due to lack of memory, or any other HRESULT error code.

Remarks

GetAllInstances allows framework providers to access data from another provider without having to make a WMI API call. Framework providers pass the name of the provider to GetAllInstances, which returns a list of all of the instances that the provider supports.

This method is semantically equivalent to the query SELECT * FROM pszBaseClassName WHERE __Class = pszBaseClassName.


CWbemProviderGlue::GetAllInstancesAsynch

The GetAllInstancesAsynch method retrieves a list of instances supported by a particular provider by calling the provider's EnumerateInstances method. GetAllInstancesAsynch allows the provider to respond asynchronously by returning one instance at a time.

static HRESULT WINAPI GetAllInstancesAsync(
  LPCWSTR pszClassName,
  Provider *pRequester,
  LPProviderInstanceCallback pCallback,
  LPCWSTR pszNamespace,
  MethodContext *pMethodContext,
  void *pUserData
);

Parameters

pszClassName
Name of class for which list of instances should be returned.
pRequester
The "This" pointer for the callback function pointed to by pCallback.
pCallback
Pointer to a function that is called to return each instance supported by the provider specified by pszClassName.
pszNamespace
Namespace of the provider specified by pszClassName. This parameter can be NULL to indicate the default namespace, which is Root\Cimv2.
pMethodContext
Pointer to the context or NULL to indicate a lack of context.
pUserData
Pointer to user-defined data that is passed to the function pointed to by pCallback.

Return Values

The method returns WBEM_S_NO_ERROR if the operation was successful, WBEM_E_OUT_OF_MEMORY if the operation failed due to lack of memory, or any other HRESULT error code.

Remarks

GetAllInstancesAsynch allows framework providers to access data from another provider without having to make a WMI API call. The Framework providers pass the name of the provider to GetAllInstancesAsynch, which calls the function specified by the pCallback parameter to return the instances that the provider supports.

For performance reasons, when calling this function, specify only the properties you need (for example, specify SELECT name instead of SELECT *).

This method is semantically equivalent to the query SELECT * FROM pszBaseClassName WHERE __Class = pszBaseClassName.


CWbemProviderGlue::GetEmptyInstance

The GetEmptyInstance method retrieves a single instance from a particular provider. None of the properties of the instance are supplied.

static HRESULT WINAPI GetEmptyInstance(
  MethodContext *pMethodContext,
  LPCWSTR pszClassName,
  CInstance **ppInstance,
  LPCWSTR pszNamespace = NULL
);
static HRESULT WINAPI GetEmptyInstance(
  LPCWSTR pszClassName,
  CInstance **ppInstance,
  LPCWSTR pszNamespace = NULL
);

Parameters

pMethodContext
A pointer to the current context.
pszClassName
Name of the class whose instance is to be returned.
ppInstance
Pointer to an instance of the CInstance class used to store the new instance. This pointer must be released by the framework provider calling GetEmptyInstance.
pszNamespace
Namespace of the class name specified by pszClassName. This parameter can be NULL to indicate the default namespace, which is Root\Cimv2.

Return Values

Returns WBEM_S_NO_ERROR if the operation was successful, WBEM_E_OUT_OF_MEMORY if the operation failed due to lack of memory, or any other HRESULT error code.

Remarks

GetEmptyInstance allows framework providers to access data from another provider without having to make a WMI API call. The Framework providers pass the name of the provider to GetEmptyInstance, which returns an empty instance.

The second function prototype is deprecated. It is provided only to support existing code.


CWbemProviderGlue::GetInstanceByPath

The GetInstanceByPath method retrieves the instance identified by a particular object path by calling the provider's GetObject method.

static HRESULT WINAPI GetInstanceByPath(
  LPCWSTR pszInstancePath,
  CInstance **ppInstance,
  MethodContext *pMethodContext = NULL
);

Parameters

pszInstancePath
Object path to the instance to be returned.
ppInstance
Pointer to a pointer to a CInstance instance used to store the new instance. The framework provider making the request is responsible for releasing this pointer.
pMethodContext
Pointer to a MethodContext instance containing the IWbemContext interface that is needed for propagation.

Return Values

Returns WBEM_S_NO_ERROR if the operation was successful, WBEM_E_OUT_OF_MEMORY if the operation failed due to lack of memory, or any other HRESULT error code.

Remarks

GetInstanceByPath allows framework providers to access data from another provider without having to make a WMI API call. Framework providers pass the object path of an instance to GetInstanceByPath, which returns the instance.

In the current version of the provider framework, pszInstancePath must resolve to be an instance path on the same computer.

Although pMethodContext has a default value of NULL, a context must be provided to prevent deadlocks. Either use the context passed into the provider by Provider::EnumerateInstances or Provider::ExecQuery, or else obtain it from the instance using CInstance::GetMethodContext.


CWbemProviderGlue::GetInstanceKeysByPath

The GetInstanceKeysByPath method retrieves the instance identified by a particular object path, with only the key properties populated.

static HRESULT WINAPI GetInstanceKeysByPath(
  LPCWSTR pszInstancePath,
  CInstance **ppInstance,
  MethodContext *pMethodContext
);

Parameters

pszInstancePath
Object path to the instance to be returned.
ppInstance
Pointer to a pointer to a new CInstance whose keys are copied from the object identified by pszInstancePath. The framework provider making the request is responsible for releasing this pointer.
pMethodContext
Pointer to a MethodContext instance containing the IWbemContext interface that is needed for propagation.

Return Values

Returns WBEM_S_NO_ERROR if the operation was successful, WBEM_E_OUT_OF_MEMORY if the operation failed due to lack of memory, or any other HRESULT error code.

Remarks

pMethodContext must be provided to prevent deadlocks. Either use the context passed into the provider by Provider::EnumerateInstances or Provider::ExecQuery, or else obtain it from the instance using CInstance::GetMethodContext.

In the current version of the provider framework, pszInstancePath must resolve to be an instance path on the same computer.

See Also

GetInstanceByPath, GetInstancePropertiesByPath


CWbemProviderGlue::GetInstancePropertiesByPath

The GetInstancePropertiesByPath method retrieves the instance identified by a particular object path, with only the specified properties populated. The properties to be populated are named in a CHString array.

static HRESULT WINAPI GetInstancePropertiesByPath(
  LPCWSTR pszInstancePath,
  CInstance **ppInstance,
  MethodContext *pMethodContext,
  CHStringArray &csaProperties
);

Parameters

pszInstancePath
Object path to the instance to be returned. This parameter must point to a full path.
ppInstance
Pointer to a pointer to a new CInstance whose keys are copied from the object identified by pszInstancePath. The framework provider making the request is responsible for releasing this pointer.
pMethodContext
Pointer to a MethodContext instance containing the IWbemContext interface that is needed for propagation.
csaProperties
An array containing the names of the properties to be copied into the new instance.

Return Values

Returns WBEM_S_NO_ERROR if the operation was successful, WBEM_E_OUT_OF_MEMORY if the operation failed due to lack of memory, or any other HRESULT error code.

Remarks

pMethodContext must be provided to prevent deadlocks. Either use the context passed into the provider by Provider::EnumerateInstances or Provider::ExecQuery, or else obtain it from the instance using CInstance::GetMethodContext.

See Also

GetInstanceByPath, GetInstanceKeysByPath


CWbemProviderGlue::GetInstancesByQuery

The GetInstancesByQuery method retrieves a list of instances that match a particular query by calling the provider's EnumerateInstances method..

static HRESULT WINAPI GetInstancesByQuery(
  LPCWSTR Query,
  TRefPointerCollection<CInstance> *pList,
  MethodContext *pMethodContext,
  LPCWSTR pszNamespace = NULL
);

Parameters

Query
The query to be executed.
pList
Linked list of instances that match the query specified by Query.
pMethodContext
Pointer to a MethodContext instance containing an appropriate IWbemContext implementation.
pszNamespace
Pointer to the namespace containing the instances. If NULL, the default namespace, Root\Cimv2, will be used.

Return Values

The method returns WBEM_S_NO_ERROR if the operation was successful, WBEM_E_FAILED if the operation failed, or any other HRESULT error code.

Remarks

GetInstancesByQuery allows framework providers to access data from other providers without having to make a WMI API call. Framework providers pass a query to GetInstancesByQuery, which returns the appropriate instances.


CWbemProviderGlue::GetInstancesByQueryAsynch

The GetInstancesByQueryAsynch method retrieves a list of instances supported by a particular provider, and that match a particular query. GetInstancesByQueryAsynch allows the provider to respond asynchronously by returning one instance at a time.

static HRESULT WINAPI GetInstancesByQueryAsynch(
  LPCWSTR query,
  Provider *pRequester,
  LPProviderInstanceCallback pCallback,
  LPCWSTR pszNamespace,
  MethodContext *pMethodContext,
  void *pUserData
);

Parameters

query
The query to be executed.
pRequester
The "this" pointer of the instance of the class being provided by the framework provider. This "this" pointer is passed to the pCallback function in case the callback function needs it.
pCallback
A pointer to a static function with this prototype:
   static HRESULT WINAPI Classname::FunctionName(
     Provider *pProvider,
     CInstance *pInstance,
     MethodContext *pMethodContext,
     void *pUserData );

where Classname is the name of a class derived from class Provider. It is an instance of this class that is the "this" pointer defined by pRequester.

pszNamespace
Namespace for query. If NULL, the default namespace, Root\CimV2, will be used.
pMethodContext
Pointer to the context or NULL to indicate a lack of context.
pUserData
Pointer to user-defined data that is passed to the function pointed to by pCallback. If NULL, there is no user-defined data.

Return Values

The method returns WBEM_S_NO_ERROR if the operation was successful, WBEM_E_OUT_OF_MEMORY if the operation failed due to lack of memory, or any other HRESULT error code.

Remarks

GetInstancesByQueryAsynch allows framework providers to access data from other providers without having to make a WMI API call. Framework providers pass a query to GetInstancesByQueryAsynch, which returns the appropriate instances.


CWbemProviderGlue::IsDerivedFrom

The IsDerivedFrom method determines whether one class is derived from another.

static bool IsDerivedFrom(
  LPCWSTR pszBaseClassName,
  LPCWSTR pszDerivedClassName,
  MethodContext *pMethodContext,
  LPCWSTR pszNamespace = NULL
);

Parameters

pszBaseClassName
Name of base class.
pszDerivedClassName
Name of class to be tested.
pMethodContext
Pointer to a MethodContext instance containing an appropriate IWbemContext implementation.
pszNamespace
The namespace containing the pszBaseClassName and pszDerivedClassname. If NULL, the default namespace, Root\CimV2, will be used.

Return Values

The method returns TRUE if the class pointed to by pszDerivedClassName is a subclass of the class pointed to by pszBaseClassName and FALSE if pszDerivedClassName does not derive from pszBaseClassName. If asked if a class is derived from itself, this method returns FALSE.


CWbemProviderGlue::SetStatusObject

The SetStatusObject method sets the parameters of a status object which is used to supply additional information when an error occurs. This status object is derived from the Win32_PrivilegesStatus.

static bool WINAPI SetStatusObject(
  MethodContext *pContext,
  LPCWSTR pNamespace,
  LPCWSTR pDescription,
  HRESULT hr,
  const SAFEARRAY *pPrivilegesNotHeld = NULL,
  const SAFEARRAY *pPrivilegesRequired = NULL
);

Parameters

pContext
Pointer to a MethodContext instance containing an appropriate IWbemContext implementation.
pNamespace
Pointer to the namespace that contains the registration of the Win32_PrivilegesStatus class.
pDescription
Pointer to the value to be put in the Description property of the status object instance.
hr
Value to be put in the StatusCode property of the status object instance.
pPrivilegesNotHeld
This parameter is not currently implemented and must be NULL.
pPrivilegesRequired
Pointer to the value to be put in the pPrivilegesRequired property of the status object instance.

Return Values

The method returns true if successful, and false otherwise.


Provider Framework Utility Classes

The provider framework libraries Framedyd.dll (debug version) and Framedyn.dll (release version) implement several provider helper classes.

Utility class | Description
WBEMTime | Facilitates conversions between various Microsoft® Windows NT®/Microsoft® Windows® 2000 and ANSI C run-time time formats.
WBEMTimeSpan | Contains helper functions used to calculate and hold the time span difference between two WBEMTime objects.

Note The WBEMTime and WBEMTimeSpan classes are similar to the Microsoft® Foundation Classes (MFC) CTime and CTimeSpan classes. The WMI versions are capable of storing time to nanosecond accuracy, and can also convert to and from BSTRs.

BSTRs returned by WBEMTime methods are in Date and Time Format:

yyyymmddHHMMSS.mmmmmmsUUU

BSTRs returned by WBEMTimeSpan methods are in Interval Format:

ddddddddHHMMSS.mmmmmm:000

Although times and time spans are stored internally as nanoseconds, they are not necessarily stored with nanosecond accuracy. This is because WBEMTime objects can be constructed using time formats that are accurate to a second (struct tm, and time_t). Adding artificial decimal places does not increase the accuracy.


WBEMTime Class Methods

The WBEMTime class facilitates conversions between various Microsoft® Windows NT®/Microsoft® Windows® 2000 and ANSI C run-time time formats. See also WBEMTimeSpan Class Methods.

Methods

WBEMTime methods | Description
WBEMTime | A constructor that facilitates conversions between various Windows NT/Windows 2000 and ANSI C run-time time formats.
Clear | Sets the time in the WBEMTime object to an invalid time.
GetBSTR | Presents the time as a BSTR in Date and Time Format.
GetDMTF | Gets the time as a BSTR in CIM datetime format.
GetFILETIME | Gets the time as an MFC FILETIME structure.
GetStructtm | Gets the time as an ANSI C run-time struct tm structure.
GetSYSTEMTIME | Gets the time as an MFC SYSTEMTIME structure.
Gettime_t | Gets the time as an ANSI C run-time time_t variable.
IsOk | Indicates whether the WBEMTime object represents a valid time.
SetDMTF | Sets the time in the WBEMTime object in CIM datetime format.

WBEMTime overloaded operators | Description
= | Facilitates conversions between various Windows NT/Windows 2000 and ANSI C run-time time formats.
+= | The add-and-assign operator has been increments an object's time by a time span.
+ | The add operator increments an object's time by a time span. The result is returned in a new WBEMTime object.
-= | The subtrace-and-assign operator decrements an object's time by a time span.
- | The subtract operator decrements an object's time by another object's time. The result is returned in a new WBEMTime object.
== != < <= > >= | Compare two WBEMTime objects.


WBEMTime::WBEMTime

The WBEMTime class constructor facilitates conversions between various Windows NT/Windows 2000 and ANSI C run-time time formats.

WBEMTime();
WBEMTime(
  const time_t& t
);
WBEMTime(
  const struct tm& tmin
);
WBEMTime(
  const SYSTEMTIME& st
);
WBEMTime(
  const FILETIME& ft
);
WBEMTime(
  BSTR bstrDMTFFormat
);

Parameters

t
An ANSI C time_t structure that holds the number of seconds since midnight Jan 1, 1970 (CIM format: 19700101000000.000000-000). See Date and Time Format for more information.
tmin
An ANSI C tm structure. A tm structure holds a time value using individual members and expressed as the number of years, months, day of month, hours, minutes, and seconds elapsed since 1900. See MSDN for more information.
ft
A MFC FILETIME structure representing the number of 100-nanosecond intervals since January 1, 1601 as a 64-bit value.
st
A MFC SYSTEMTIME structure representing a date and time and using individual members for the month, day, year, weekday, hour, minute, second, and millisecond.
bstrDMTFFormat
A BSTR in Date and Time Format. The BSTR will be converted to GMT. Now when you use WBEMTime::GetDMTF to retrieve it you have only two choices: Get as Local Time or Get as GMT. At this point the actual offset used in the BSTR to build the WBEMTime object has been lost.

Remarks

If you use the WBEMTime( BSTR bstrDMTFFormat) form of the constructor, you can only retrieve the time in one of two ways: Get as Local Time or Get as GMT. The actual offset used in the BSTR to build the WBEMTime object has been lost.

Should a "*" appear in any location in the inbound datetime string bstrDMTFFormat, the * will be replaced on a positional basis with the default datetime string "16010101000000.000000+000".

The microsecond separator "." and UTC offset sign "+/-" must be present in the correct locations. * in these locations constitutes an error. All other positions will be replaced by the default element if * is detected in the corresponding location. Invalid character symbols are not allowed.

Example: "1979**********.000000+000" will appear as "197910101000000.000000+000".

"1979**********.000000+0*1" will convert to "197910101000000.000000+001". Note the * in the UTC offset changes to 0 in the second position. On reading this datetime field the resulting UTC of 001 impacts the minute field to yield "197910100000000.000000+000".


WBEMTime::operator=

The WBEMTime class assignment operators have been overloaded to facilitate conversions between various Windows NT/Windows 2000 and ANSI C run-time time formats.

const WBEMTime& operator=(
  const time_t& t
);
const WBEMTime& operator=(
  const struct tm& tmin
);
const WBEMTime& operator=(
  const FILETIME& ft
);
const WBEMTime& operator=(
  const SYSTEMTIME& st
);
const WBEMTime& operator=(
  const BSTR bstrDMTFormat
);

Parameters

t
An ANSI C time_t structure that holds time values in seconds since midnight Jan 1, 1970.
tmin
An ANSI C tm structure that holds time values since midnight Jan 1, 1900 .
ft
A MFC FILETIME structure representing the number of 100-nanosecond intervals since January 1, 1601 as a 64-bit value.
st
A MFC SYSTEMTIME structure representing a date and time and using individual members for the month, day, year, weekday, hour, minute, second, and millisecond.
bstrDMTFormat
A BSTR in Date and Time Format.


WBEMTime::operator+=

The WBEMTime class add-and-assign operator has been overloaded to increment an object's time by a time span.

const WBEMTime& operator+=(
  const WBEMTimeSpan& ts
);

Parameters

ts
A reference to the WBEMTimeSpan object, whose time will be added to the specified object.


WBEMTime::operator+

The WBEMTime class addition operator has been overloaded to increment an object's time by a time span.

const WBEMTime& operator+(
  const WBEMTimeSpan& uAdd
) const;

Parameters

uAdd
A reference to the WBEMTimeSpan object.

Return Values

A new WBEMTime object whose value is the sum of the "this" object and the WBEMTimeSpan argument. The value of the "this" object is unchanged by this method.


WBEMTime::operator-=

The WBEMTime class subtract-and-assign operator has been overloaded to decrement an object's time by a time span.

const WBEMTime& operator-=(
  const WBEMTimeSpan& ts
);

Parameters

ts
A reference to the WBEMTimeSpan object, whose time span will be subtracted from the specified object.

Returns

The return value is a new WBEMTime object with a value equal to the "this" object after it has been decremented.


WBEMTime::operator-

The WBEMTime class subtraction operator has been overloaded to decrement an object's time by another object's time.

The WBEMTime class subtraction operator has been overloaded to 1) subtract a time span from an object's time to produce a new time object containing the resulting time, and 2) subtract a time from the object's time to produce a new time span object containing the difference between the two times.

WBEMTime operator-(
  const WBEMTimeSpan& subtractSpan
);

WBEMTimeSpan operator-(
  const WBEMTime& subtractTime
);

Parameters

subtractSpan
A reference to the WBEMTimeSpan object, whose time span will be subtracted from the "this" object.
subtractTime
A reference to the WBEMTime object, whose time will be subtracted from the "this" object.

Return Values

When a WBEMTime is returned, it is a new object whose time is the difference between the "this" object and the WBEMTimeSpan used as the argument.

When a WBEMTimeSpan is returned, it is a new time span object whose value is the difference between the "this" object and the WBEMTime used as an argument.

Any returned objects which would have a negative time span or a time before Jan 1, 1601 will be set to INVALID_TIME.


WBEMTime Comparison Operators

The WBEMTime comparison operators (== != < <= > >=) have been overloaded to compare two WBEMTime objects.

BOOL operator==(
  const WBEMTime& uTarget
) const;
BOOL operator!=(
  const WBEMTime& uTarget
) const;
BOOL operator<(
  const WBEMTime& uTarget
) const;
BOOL operator<=(
  const WBEMTime& uTarget
) const;
BOOL operator>(
  const WBEMTime& uTarget
) const;
BOOL operator>=(
  const WBEMTime& uTarget
) const;

Parameters

uTarget
A reference to the WBEMTime object, whose time will be compared to this one.

Return Values

The operators return TRUE if the comparison succeeds and FALSE if the comparison fails.


WBEMTime::Clear

The Clear method sets the time in the WBEMTime object to an invalid time.

void Clear();

Parameters

None.

See Also

WBEMTime::IsOk


WBEMTime::GetBSTR

The GetBSTR method presents the time as a BSTR in Date and Time Format.

BSTR GetBSTR(void) const throw (CHeap_Exception);

Parameters

None.

Return Values

The method returns a BSTR in Date and Time Format. The time is given as GMT. If the internal time value is INVALID_TIME, the method returns NULL.

Remarks

If the value returned is not NULL, the calling function must call SysFreeString on the returned value.

See Also

WBEMTime::GetDMTF


WBEMTime::GetDMTF

The GetDMTF method gets the time as a BSTR in CIM datetime format.

BSTR GetDMTF(
  BOOL bLocal = FALSE
) const throw (CHeap_Exception);

Parameters

bLocal
If TRUE, returns the local time, adjusted for daylight savings time; otherwise, returns GMT.

Return Values

A BSTR in CIM datetime format.

Remarks

The calling function must call SysFreeString on the return value.

See Also

WBEMTime::GetBSTR, WBEMTime::SetDMTF


WBEMTime::GetDMTFNonNtfs

The GetDMTFNonNtfs method gets a DMTF date that is based upon a FAT or a Date Time Format where the UTC is not known.

BSTR GetDMTFNonNtfs(
) const;

Return Values

A BSTR in Date Time Format.

Remarks

The calling function must call SysFreeString on the return value.

The time property of WBEMTime is held in GMT. GetDMTFNonNtfs adjusts this time to local time, converts it to a DMTF string, and sets the UTC to "***". . This is compatible with the Win32 API methods which return time without being time-zone aware.

See Also

WBEMTime, WBEMTimeSpan, and FAT versus NTFS Time.


WBEMTime::GetFILETIME

The GetFILETIME method gets the time as an MFC FILETIME structure.

BOOL GetFILETIME(
  FILETIME *pst
);

Parameters

pst
An MFC FILETIME structure. The FILETIME structure is a 64-bit value that represents the number of 100-nanosecond intervals since January 1, 1601.

Return Values

The method returns TRUE if the time is valid and FALSE if the time is invalid. If the time is invalid, the value of pst is indeterminate.

WBEMTime::GetLocalOffsetForDate

The GetLocalOffsetForDate method returns the offset in minutes(+ or -) between GMT and local time for the time supplied in the argument.

static LONG WINAPI GetLocalOffsetForDate(
  const struct tm* tmin
);
static LONG WINAPI GetLocalOffsetForDate(
  const SYSTEMTIME* pst
);
static LONG WINAPI GetLocalOffsetForDate(
  const FILETIME* pft
);
static LONG WINAPI GetLocalOffsetForDate(
  const time_t& t
);

Parameters

tmin
A pointer to an ANSI C tm structure that holds time values since midnight Jan 1, 1900 .
pst
A pointer to a MFC SYSTEMTIME structure representing a date and time and using individual members for the month, day, year, weekday, hour, minute, second, and millisecond.
pft
A pointer to a MFC FILETIME structure representing the number of 100-nanosecond intervals since January 1, 1601 as a 64-bit value.
t
A reference to an ANSI C time_t structure that holds time values in seconds since midnight Jan 1, 1970.

Return Values

Returns the offset in minutes(+ or -) between GMT and local time for the time supplied in the argument.

Remarks

These are public static functions which permits their usage anywhere without having a WBEMTime object.


WBEMTime::GetStructtm

The GetStructtm method gets the time as an ANSI C run-time struct tm structure.

BOOL GetStructtm(
  struct tm *ptm
) const;

Parameters

ptm
An ANSI C run-time struct tm structure.

Return Values

The method returns TRUE if the object's time is equal to or later than midnight Jan 1, 1900.

The method returns FALSE on all other times or of the object's time is set to INVALID_TIME. In this case, the value of ptm is indeterminate.


WBEMTime::GetSYSTEMTIME

The GetSYSTEMTIME method gets the time as an MFC SYSTEMTIME structure.

BOOL GetSYSTEMTIME(
  SYSTEMTIME *pst
) const;

Parameters

pst
An MFC SYSTEMTIME structure. The SYSTEMTIME structure represents a date and time using individual members for the month, day, year, weekday, hour, minute, second, and millisecond.

Return Values

The method returns TRUE if the time is valid.

The method returns FALSE if the time is INVALID_TIME. In this case, the value of pst is indeterminate.


WBEMTime::GetTime

The GetTime method gets the time as GMT FILETIME structure.

ULONGLONG GetTime(
) const;

Return Value

Returns the time as GMT FILETIME structure. If the time is invalid, it returns INVALID_TIME.


WBEMTime::Gettime_t

The Gettime_t method gets the time as an ANSI C run-time time_t variable.

BOOL Gettime_t(
  time_t *ptm
) const;

Parameters

ptm
An ANSI C run-time time_t variable, which represents the number of seconds since midnight Jan 1, 1970. In DMTF format, this is 19700101000000.000000-000.

Return Values

The method returns TRUE if the object's time is equal to or later than midnight Jan 1, 1970.

The method returns FALSE on all other times or of the object's time is set to INVALID_TIME. In this case, the value of ptm is indeterminate.


WBEMTime::IsOk

The IsOk method indicates whether the WBEMTime object represents a valid time.

bool IsOk();

Parameters

None.

Return Values

The method returns true if the time is valid and false if the time is invalid.

See Also

WBEMTime::Clear


WBEMTime::SetDMTF

The SetDMTF method sets the time in the WBEMTime object. The time is given by its BSTR parameter in Date and Time Format. A date and time argument earlier than midnight January 1, 1601 is invalid.

BOOL SetDMTF(
  const BSTR wszText
);

Parameters

wszText
A BSTR in Date and Time Format.

Return Values

The method returns TRUE if the time is valid and FALSE if the time is invalid.

Remarks

Should a "*" appear in any location in the inbound datetime string wszText, the * will be replaced on a positional basis with the default datetime string "16010101000000.000000+000".

The microsecond separator "." and UTC offset sign "+/-" must be present in the correct locations. * in these locations constitutes an error. All other positions will be replaced by the default element if * is detected in the corresponding location. Invalid character symbols are not allowed.

Example: "1979**********.000000+000" will appear as "197910101000000.000000+000".

"1979**********.000000+0*1" will convert to "197910101000000.000000+001". Note the * in the UTC offset changes to 0 in the second position. On reading this datetime field the resulting UTC of 001 impacts the minute field to yield "197910100000000.000000+000".

See Also

WBEMTime::GetBSTR, WBEMTime::GetDMTF


WBEMTimeSpan Class Methods

The WBEMTimeSpan class holds time spans in nanoseconds. WBEMTimeSpan objects can result from the arithmetic manipulation of WBEMTime objects. For example, subtracting one WBEMTime object from another results in a WBEMTimeSpan object representing the difference in time between the two objects.

Methods

WBEMTimeSpan methods | Description
WBEMTimeSpan | A constructor creates a time span object.
Clear | Sets the time span to INVALID_TIME..
GetBSTR | Gets the time span as a BSTR in WMI time span format.
GetTime | Returns the time span as a 64-bit integer.
IsOk | Indicates whether the WBEMTimeSpan object represents a valid time span.

WBEMTimeSpan overloaded operators | Description
= | Facilitates conversions between various Windows NT/Windows 2000 and ANSI C run-time time formats.
+= | The add-and-assign adds one time span to another.
+ | The add operator adds one time span to another, placing the sum in a new WbemTimeSpan object returned by the method.
-= | The subtract-and-assign operator subtracts one time span from another.
- | The subtract operator subtracts a time span from the "this object" to create a new time span containing the difference in time.
== != < <= > >= | Compare two WBEMTimeSpan objects.

See also

WBEMTime Class Methods.


WBEMTimeSpan::WBEMTimeSpan

The WBEMTimeSpan class constructor creates a time span object.

WBEMTimeSpan();
WBEMTimeSpan(
  int iDays,
  int iHours,
  int iMinutes,
  int iSeconds,
  int iMSec=0,
  int iUSec=0,
  int iNSec=0
);
WBEMTimeSpan(
  BSTR bstrDMTFFormat
);

Parameters

iDays
Number of elapsed days.
iHours
Number of elapsed hours.
iMinutes
Number of elapsed minutes.
iSeconds
Number of elapsed seconds.
iMSec
Number of elapsed milliseconds.
iUSec
Number of elapsed microseconds.
iNSec
Number of elapsed nanoseconds.
bstrDMTFFormat
A BSTR in Interval Format.


WBEMTimeSpan::operator=

The WBEMTimeSpan class assignment operators have been overloaded to facilitate conversions between various Windows NT/Windows 2000 and ANSI C run-time time formats.

const WBEMTimeSpan& operator=(
  BSTR bstrDMTFFormat
);

Parameters

bstrDMTFFormat
A BSTR in Interval Format.


WBEMTimeSpan::operator+=

The WBEMTimeSpan class add-and-assign operator has been overloaded to add one time span to another.

const WBEMTimeSpan& operator+=(
  const WBEMTimeSpan& uAdd
);

Parameters

uAdd
A reference to the WBEMTimeSpan object, whose time span will be added to this one.


WBEMTimeSpan::operator+

The WBEMTimeSpan class add operator has been overloaded to add one time span to another, placing the sum in a new WbemTimeSpan object returned by the method.

WBEMTimeSpan operator+(
  const WBEMTimeSpan& uAdd
) const;

Parameters

uAdd
A reference to a WBEMTimeSpan object, whose time span will be added to this one.

Return Values

A new WBEMTimeSpan object, whose time span is equal to the sum of its two WBEMTimeSpan arguments.


WBEMTimeSpan::operator-=

The WBEMTimeSpan class subtract-and-assign operator has been overloaded to subtract one time span from another.

const WBEMTimeSpan& operator-=(
  const WBEMTineSpan& uSub
);

Parameters

uSub
A reference to the WBEMTimeSpan object, whose time span will be subtracted from the "this" object.

Return Values

This method returns a new WBEMTimeSpan object with a value equal to the difference in time.


WBEMTimeSpan::operator-

The WBEMTimeSpan class subtract operator subtracts a time span from the "this object" to create a new time span containing the difference in time.

WBEMTimeSpan operator-(
  const WBEMTimeSpan& uSubTimeSpan
) const;

Parameters

uSubTimeSpan
A reference to the WBEMTimeSpan object, whose time span will be subtracted from this time span, producing a new time span.

Return Values

This method returns a new WBEMTimeSpan object with a value equal to the difference in time.

Notes The new time span will be set to INVALID_TIME if a negative time span results. Subtracting a time span from an object containing INVALID_TIME produces a new time span object set to INVALID_TIME.


WBEMTimeSpan Comparison Operators

The WBEMTimeSpan comparison operators (== != < <= > >=) have been overloaded to compare two WBEMTimeSpan objects.

BOOL operator==(
  const WBEMTimeSpan& uTarget
);
BOOL operator!=(
  const WBEMTimeSpan& uTarget
);
BOOL operator<(
  const WBEMTimeSpan& uTarget
);
BOOL operator<=(
  const WBEMTimeSpan& uTarget
);
BOOL operator>(
  const WBEMTimeSpan& uTarget
);
BOOL operator>=(
  const WBEMTimeSpan& uTarget
);

Parameters

uTarget
A reference to the WBEMTimeSpan object, whose time span will be compared to this one.

Return Values

The operators return TRUE if the comparison succeeds and FALSE if the comparison fails.


WBEMTimeSpan::Clear

The Clear method sets the time span to INVALID_TIME.

void Clear();


WBEMTimeSpan::GetBSTR

The GetBSTR method gets the time span as a BSTR in Date and Time format.

BSTR GetBSTR() throw (CHeap_Exception);

Parameters

None.

Return Values

The time span is returned as a BSTR in Date and Time Format.

Remarks

The calling function must call SysFreeString on the return value.


WBEMTimeSpan::GetTime

The GetTime returns the time span as a 64-bit integer.

ULONGLONG GetTime() const;

Remarks

The method is provided to assist users in debugging.


WBEMTimeSpan::IsOk

The IsOk method indicates whether the WBEMTimeSpan object represents a valid time span.

bool IsOk() const;

Parameters

None.

Return Values

The method returns true if the time span is valid and false if the time span is invalid.


COM API for WMI

The COM API for WMI reference documents the application programming interface (API) components for the Windows Management Instrumentation (WMI) Component Object Model (COM). Using the API components covered in the following reference topics, you can access WMI services. This reference also describes the communication link between COM and WMI. The COM API reference provides information for advanced system administrators, as well as developers who are writing client and provider applications.

Note Microsoft only supports WMI C++ development using Microsoft® Visual C++® version 6.0 and later development system . However, you can also use other compilers such as those from Borland, Watcom, and so on.

Each of the many different WMI objects inherits from an interface that is ultimately inherited from the IUnknown interface. COM dictates how object implementers, or interfaces, handle tasks such as memory management, parameter management, and multithreading. By conforming to COM, the WMI COM API guarantees that it supports the functionality provided by the interfaces of each API object.

WMI is accessed through the following COM interfaces specific to WMI.

WMI COM interfaces | Description
IEnumWbemClassObject | This interface is an enumerator that works with objects of type IWbemClassObject. It is similar to standard COM enumerators, such as IEnumVariant.
IMofCompiler | This interface is implemented by Mofd.dll, and provides a COM interface that is used by the MOF Compiler and any other applications that need to compile MOF files.
IUnsecuredApartment | This interface is used to simplify the process of making asynchronous calls from a client process.
IWbemCallResult | This interface optionally is used to query for the result of semisynchronous calls.
IWbemClassObject | This interface contains and manipulates both class definitions and class object instances. Developers need not implement this interface; WMI provides its implementation.
IWbemConfigureRefresher | This interface is used to add or remove refreshers, objects, or enumerators to a refresher object.
IWbemContext | This interface optionally is used to provide additional context information for other WMI calls.
IWbemEventConsumerProvider | This interface is used to initiate communication with a consumer provider.
IWbemEventProvider | This interface is used to initiate communication with a provider.
IWbemEventProviderQuerySink | This interface is optionally implemented by event providers that expose information on the kinds of event query filters that are currently active, to optimize performance.
IWbemEventProviderSecurity | This interface is optionally implemented by event providers who want to restrict consumer access to their event.
IWbemHiPerfProvider | This interface is used to initiate communication with a high-performance provider.
IWbemHiperfEnum | This interface is used to setup an enumeration with a high-performance provider.
IWbemLocator | This interface obtains the initial pointer to the IWbemServices interface for WMI on a specific host computer.
IWbemObjectAccess | This interface is used as a container for class instances. This interface is used by to read and write the properties of object instances returned by IWbemHiperfProvider and IWbemHiperfEnum interfaces.
IWbemObjectSink | This interface is used to receive both the results of the asynchronous methods of IWbemServices and certain types of event notifications.
IWbemPropertyProvider | This interface is implemented only by dynamic property providers, which must expose their data sources at the level of properties rather than instances.
IWbemProviderIdentity | This interface would be implemented if a provider is registered using more than one name yet a single CLSID. The class provides a mechanism for distinguishing which named provider should be used.
IWbemProviderInit | This interface is used to initialize all provider types.
IWbemProviderInitSink | This interface is implemented by WMI and called by providers to report initialization status.
IWbemQualifierSet | This interface enables WMI clients to read or modify qualifiers on properties or entire objects. Developers need not implement this interface; WMI provides its implementation.
IWbemRefresher | This interface is used to contain and update a refresher object.
IWbemServices | This is the primary interface to WMI. It provides management services to client processes and to other providers.
IWbemStatusCodeText | This interface extracts text string descriptions of error codes or the name of the subsystem where the error occurred.
IWbemUnboundObjectSink | This interface is implemented by event consumers. It is a simple sink interface that accepts delivery of event objects.

Note Many of the WMI COM API functions return numeric error codes which are documented as named constants. These constants are defined in the file Wbemcli.h in the WMI SDK \Include folder.

The Microsoft Platform Software Development Kit (SDK) documentation includes a comprehensive discussion of the rules for implementing objects that conform to COM. These rules address how to:

  • Design interfaces and objects.
  • Implement IUnknown.
  • Manage memory.
  • Handle reference counting.

For more information on these rules, see the COM section of the Platform SDK.


Automation Interfaces

[This is preliminary documentation and subject to change.]

The Automation API makes the interfaces of the Scripting API for WMI available to C/C++ programmers, who would want to access them instead of the COM API versions. For a detailed description of Automation API functionality, see the Scripting API documentation. Due to programming language differences, look up the exact syntax of specific Automation functionality in the Wbemdisp.idl, which is included in the WMI SDK installation. (Look in the \Include subdirectory of the directory where the WMI SDK is installed.)

The following table describes WMI objects and how they are used in the Automation API. The jumps will bring you to the interface documentation for the Scripting API equivalents.

Object | Description
ISWbemEventSource | Retrieves events in conjunction with ISWbemServices.ExecNotificationQuery.
ISWbemLastError | Provides extended error information when an error occurs.
ISWbemLocator | Obtains a reference to an ISWbemServices object that can access WMI on a particular host machine.
ISWbemMethod | Contains a single CIM method definition.
ISWbemMethodSet | Gets access to a collection of ISWbemMethod objects.
ISWbemNamedValue | Contains a single named value.
ISWbemNamedValueSet | Gets access to a collection of ISWbemNamedValue objects.
ISWbemObject | Contains and manipulates a single Common Information Model (CIM) object class or instance.
ISWbemObjectPath | Generates and validates an object path.
ISWbemObjectSet | Gets access to a collection of ISWbemObject objects.
ISWbemPrivilege | Sets or clears a privilege.
ISWbemPrivilegeSet | Gets access to a collection of ISWbemPrivilege objects.
ISWbemProperty | Used to contain a single CIM property.
ISWbemPropertySet | Get access to a collection of ISWbemProperty objects.
ISWbemQualifier | Contains a single CIM qualifier.
ISWbemQualifierSet | Gets access to a collection of ISWbemQualifier objects.
ISWbemSecurity | Manages security settings such as Distributed Component Object Model (DCOM) Privilege, AuthenticationLevel, and ImpersonationLevel.
ISWbemServices | Creates, updates, and retrieves instances or classes.
ISWbemSink | Receives the results of client application asynchronous operations and event notifications.


IEnumWbemClassObject

The IEnumWbemClassObject interface is used to enumerate Common Information Model (CIM) objects and is similar to a standard Component Object Model (COM) enumerator. You will receive an object of type IEnumWbemClassObject from calls to the following methods: IWbemServices::ExecQuery, IWbemServices::CreateInstanceEnum, IWbemServices::CreateClassEnum, and IWbemServices::ExecNotificationQuery.

CIM objects are retrieved from an enumeration as objects of type IWbemClassObject by calling the Next method. You can reset an enumeration back to the beginning by calling the Reset method.

IEnumWbemClassObject Methods | Description
Clone | Makes a copy of the enumerator.
Next | Retrieves the next object or objects in the enumeration starting from the current position.
NextAsync | Retrieves the next object or objects using asynchronous integration with IWbemObjectSink.
Reset | Resets an enumeration sequence back to the beginning.
Skip | Causes the enumeration to skip ahead so that future calls to the Next method will retrieve objects one or more ahead of the current location in the enumeration.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IEnumWbemClassObject::Reset

The IEnumWbemClassObject::Reset method resets an enumeration sequence back to the beginning. Since CIM objects are dynamic, calling this method does not necessarily return the same list of objects that you obtained previously.

Note This method will fail if the enumerator was originally created with the WBEM_FLAG_FORWARD_ONLY option.

HRESULT Reset( );

Parameters

None.

Return Values

Value | Meaning
WBEM_S_NO_ERROR | The operation succeeded.
WBEM_E_INVALID_OPERATION | The operation failed.

The DCOM-specific error codes may also be returned if the remote connection to the Windows Management is lost due to network problems.

Note You may see DCOM-specific error codes returned if network problems cause you to lose the remote connection to Windows Management.

If WBEM_S_NO_ERROR is not returned, you can call the COM function GetErrorInfo for more information about the error.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IEnumWbemClassObject::Next

Use the IEnumWbemClassObject::Next method to get one or more objects starting at the current position in an enumeration. This method advances the current position in the enumeration by uCount objects, so that subsequent calls return the subsequent objects.

HRESULT Next(
  LONG lTimeOut,
  ULONG uCount,
  IWbemClassObject **ppObjects,
  ULONG *puReturned
);

Parameters

lTimeOut
[in] Specifies the maximum amount of time in milliseconds that the call will block before returning. If you use the constant WBEM_INFINITE (0xFFFFFFFF), the call blocks until objects are available. If you use the value zero (WBEM_NO_WAIT), the call will return immediately, whether any objects are available or not.
uCount
[in] The number of requested objects.
ppObjects
[out, size_is(uCount) length_is(*puReturned)] A pointer to enough storage to hold the number of IWbemClassObject interface pointers specified by uCount. This storage must be supplied by the caller. This parameter may not be NULL. The caller must call Release on each of the received interface pointers when they are no longer needed.
puReturned
[out] A pointer to a ULONG that receives the number of objects returned. This number can be less than the number requested in uCount. This pointer cannot be NULL.

Note The IEnumWbemClassObject::Next method may return WBEM_S_FALSE even when objects have been returned successfully. WBEM_S_NO_ERROR returns only when the number of objects returned matches the number requested in uCount. Therefore, you should use loop termination logic that examines the puReturned value to ensure you have reached the end of the enumeration.

Return Values

Value | Meaning
WBEM_E_INVALID_PARAMETER | One or more invalid parameters were specified in the call.
WBEM_OUT_OF_MEMORY | There was not enough memory to complete the enumeration.
WBEM_E_UNEXPECTED | An object in the enumeration has been deleted, destroying the validity of the enumeration.
WBEM_E_TRANSPORT_FAILURE | This indicates the failure of the remote procedure call (RPC) link between the current process and Windows Management.
WBEM_S_NO_ERROR | The number of objects returned was the same as the number requested.
WBEM_S_FALSE | The number of objects returned was less than the number requested. WBEM_S_FALSE is also returned when this method is called with a value of zero for the uCount parameter.
WBEM_S_TIMEDOUT | A time out occurred before you obtained all the objects.

Note You may see DCOM-specific error codes returned if network problems cause you to lose the remote connection to Windows Management.

On error, you can call the COM function GetErrorInfo to obtain more error information.

If more than one object is requested, and if the number of requested objects is returned, the function returns WBEM_S_NO_ERROR. If less than the requested number of objects is available, and if the enumeration has completed, those objects will be returned and the function will return WBEM_S_FALSE.

If the enumeration has not completed, the call will wait for objects to be available up to the specified timeout. If the enumeration times out before the objects are available, the function will return WBEM_S_TIMEDOUT.

In the following example, more than one object is requested:

HRESULT ProcessEnum( IEnumWbemClassObject*    pEnum )
{
    HRESULT    hRes = WBEM_S_NO_ERROR;

    // Final Next wil return WBEM_S_FALSE
    while ( WBEM_S_NO_ERROR == hRes )
    {
        ULONG            uReturned;
        IWbemClassObject*    apObj[10];

        hRes = pEnum->Next( WBEM_INFINITE, 10, apObj, &uReturned );

        if ( SUCCEEDED( hRes ) )
        {
            // Do something with the objects
            ProcessObjects( uReturned,  apObj );

            for ( ULONG n = 0; n < uReturned; n++ )
            {
                apObj[n]->Release();
            }

        }    // If Enum Succeeded

    }    // While Enum returning objects
}

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IEnumWbemClassObject::NextAsync

Use the IEnumWbemClassObject::NextAsync method when a controlled asynchronous retrieval of objects to a sink is required. Normal asynchronous retrieval, such as a call to IWbemServices::ExecQueryAsync , results in uncontrolled delivery of objects to the caller's implementation of IWbemObjectSink. This method is helpful for cases where components want to control delivery of objects.

HRESULT NextAsync(
  ULONG uCount,
  IWbemObjectSink *pSink
);

Parameters

uCount
[in] The number of objects being requested.
pSink
[in] The sink to receive the objects. The sink must be implemented by the caller. As each batch of objects is requested, they will be delivered to the pSink->Indicate method followed by a final call to pSink->SetStatus. If the sink is going to be used to deliver objects, this API will return WBEM_S_NO_ERROR, even if the number of objects to be delivered is less than requested. However, if there are no more objects remaining, then the pSink parameter will be ignored (no calls to pSink->SetStatus will be made). Instead, this API will return WBEM_S_FALSE.

Return Values

Value | Meaning
WBEM_E_FAILED | The call failed, and it is not expected to complete.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_UNEXPECTED | An object in the enumeration has been deleted destroying the validity of the enumeration.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_TRANSPORT_FAILURE | This indicates the failure of the remote procedure call (RPC) link between the current process and Windows Management.
WBEM_S_NO_ERROR | One or more objects successfully returned. It is not considered an error if less objects are returned than requested.
WBEM_S_FALSE | This will be returned when no more objects are available. WBEM_S_FALSE is also returned when this method is called with a value of zero for the uCount parameter.

A call to the COM function GetErrorInfo provides more information about the error.

Note DCOM-specific error codes may also be returned if network problems cause you to lose the remote connection to Windows Management.

Remarks

This call returns immediately, and delivery to the sink occurs in the background. If multiple calls are made to this method from one or more threads, they are logically queued, and the order of calls and object delivery is preserved. Multiple calls made to this method from one or more threads will block (will not return) until all the sink objects related to previous calls to this method have been serviced. A call to Reset does not affect delivery of objects currently in progress as a result of previous calls. Reset only causes new calls to start at the beginning of the object sequence.

If the number of requested objects is immediately available, the function will return WBEM_S_NO_ERROR. If less than the number of requested objects is available, the available objects will be returned and WBEM_S_NO_ERROR will be returned. The remainder of the objects will be delivered via the user-supplied sink.

As the objects become available, the caller's implementation of IWbemObjectSink::Indicate is called zero or more times to deliver the objects. This is followed by a call to IWbemObjectSink::SetStatus with a value of WBEM_S_NO_ERROR if uCount items are returned.

If fewer objects are available than the number requested, IWbemObjectSink::Indicate is called for those objects that are available. IWbemObjectSink::SetStatus is then called with a value of WBEM_S_FALSE, or the error code if an error occurred.

If the requested number of objects is delivered, the final object will be followed by a call to IWbemObjectSink::SetStatus with an status code of WBEM_S_NO_ERROR. If the enumeration completes before the requested number of objects can be delivered, the IWbemObjectSink::SetStatus function will have a status code of WBEM_S_FALSE.

If there are no available objects, IWbemObjectSink::Indicate is not called. However, a final call to IWbemObjectSink::SetStatus will always occur to indicate the status of the entire operation.

Sample Code

void ListObjects(
    IEnumWbemClassObject *pEnum,
    IWbemObjectSink *pSink
    )
{
    HRESULT hRes;

    while (1)
    {
        hRes = pEnum->NextAsync(5, pSink);

            // Wait until sink is ready for more by
            // some private mechanism. Note that hRes gives
            // no indication as to whether to continue the
            // enumeration or not.

           BOOL bContinue = WaitUntilMoreObjectsNeeded();

            if (!bContinue)
                break;
    }
}

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IEnumWbemClassObject::Clone

The IEnumWbemClassObject::Clone method makes a logical copy of the entire enumerator, retaining its current position in an enumeration. This method will make only a "best effort" copy. Due to the dynamic nature of many CIM objects, it is possible that the new enumerator does not enumerate the same set of objects as the source enumerator.

Note When the enumeration was initialized with the WBEM_FLAG_FORWARD_ONLY flag, IEnumWbemClassObject::Clone is not supported.

Any pending asynchronous deliveries begun by NextAsync are not cloned.

HRESULT Clone(
  IEnumWbemClassObject **ppEnum
);

Parameters

ppEnum
[out] Receives a pointer to a new IEnumWbemClassObject object. The caller must call Release when the interface pointer is no longer required. On error, there will not be a return of a new object.

Return Values

Value | Meaning
WBEM_E_FAILED | An unspecified error occurred.
WBEM_E_INVALID_PARAMTER | The caller passed an invalid parameter.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_TRANSPORT_FAILURE | This indicates the failure of the remote procedure call (RPC) link between the current process and Windows Management.
WBEM_S_NO_ERROR | The call succeeds and the current position was updated.

On error, you can call the COM function GetErrorInfo to obtain more error information.

Note DCOM-specific error codes may also be returned if network problems cause you to lose the remote connection to Windows Management.

Sample Code

BOOL CloneEnum(IEnumWbemClassObject *pSrc)
{
    IEnumWbemClassObject *pCopy = 0;

    HRESULT hRes = pSrc->Clone(&pCopy);

    if (hRes != WBEM_S_NO_ERROR)       // Failed to clone it
        return FALSE;

    // Use the copy of the enumerator
    // ...

    pCopy->Release();

    return TRUE;
}

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IEnumWbemClassObject::Skip

You can use the IEnumWbemClassObject::Skip method to move the current position in an enumeration ahead by a specified number of objects. Also, this affects subsequent calls to NextAsync, but it does not affect pending deliveries begun with NextAsync.

HRESULT Skip(
  LONG lTimeOut,
  ULONG UCount
);

Parameters

lTimeOut
[in] Specifies the maximum amount of time in milliseconds that the call to Skip will block before returning. If you use the constant WBEM_INFINITE (0xFFFFFFFF), the call will block until the operation succeeds. If Skip cannot complete the operation before the lTimeout value expires, the call returns WBEM_S_TIMEDOUT.
UCount
[in] Specifies the number of objects to skip. If this parameter is greater than the number of objects left to enumerate then this call will skip to the end of the enumeration and WBEM_S_FALSE will be returned.

Return Values

Value | Meaning
WBEM_E_INVALID_PARAMTER | The caller passes an invalid parameter.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_S_FALSE | The call skips less objects than specified by the uCount parameter.
WBEM_S_NO_ERROR | The call succeeds and the current position in the enumeration was updated.
WBEM_S_TIMEDOUT | The lTimeout parameter specified expired before Skip could complete the operation.
WBEM_E_TRANSPORT_FAILURE | This indicates the failure of the remote procedure call (RPC) link between the current process and Windows Management.
WBEM_E_FAILED | An unspecified error occurred.

Note DCOM-specific error codes may also be returned if network problems cause you to lose the remote connection to Windows Management.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IMofCompiler Interface

Windows Management Instrumentation

IMofCompiler

[This is preliminary documentation and subject to change.]

The IMofCompiler interface, which is implemented by Mofd.dll, provides a COM interface that is used by the MOF Compiler and any other applications that need to compile MOF files. Objects can be obtained using the CLSID_MofCompiler CLSID.

IMofCompiler methods | Description
CompileBuffer | Takes the information in a buffer and stores it into WinMgmt. The buffer must contain binary MOF data.
CompileFile | Called to compile a particular MOF file.
CreateBMOF | Reads a MOF file and outputs binary MOF data to another file.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IMofCompiler::CompileFile

[This is preliminary documentation and subject to change.]

The CompileFile method compiles a MOF file (including binary MOFs) and stores the information into Winmgmt.

HRESULT IMofCompiler::CompileFile(
[in, string] LPWSTR FileName,
[in, string] LPWSTR ServerAndNamespace,
[in, string] LPWSTR User,
[in, string] LPWSTR Authority,
[in, string] LPWSTR Password,
[in] LONG lOptionFlags,
[in] LONG lClassFlags,
[in] LONG lInstanceFlags,
[in, out] WBEM_COMPILE_STATUS_INFO* pInfo
);

Parameters

FileName
Name of the file to be compiled.
ServerAndNamespace
Path to the default namespace where any classes or instance are written.

You can specify a namespace on a remote machine (\\computer\root, for example) This value may be overriden by pragmas and should not be used if auto recovery is desired. If NULL, then the Root\Default namespace on the local machine is the default.

User
This parameter specifies the credentials used to compile on remote machines. If the value is NULL, the user context is whatever the calling process is using. This is always ignored when connecting to the local machine. See the Remarks section later in this topic.
Authority
This parameter specifies the credentials for compiling on remote machines. If the value is NULL, the Authority context is whatever the calling process is using. This is always ignored when connecting to the local machine. See the Remarks section.
Password
This parameter specifies the credentials for compiling on remote machine. If the value is NULL, the password of the current context is used. This is always ignored when connecting to the local machine.
lOptionFlags
When you use the CompileFile method, you can combine one or more of the following flags.
Value | Meaning
WBEM_FLAG_CHECK_ONLY | Performs only a syntax check.
WBEM_FLAG_AUTORECOVER If the method is successful, adds the name of the file to the list of files to that are to be compiled during automatic database recovery.

Note that this flag cannot be combined with either the namespace, class, or instance flags.
WBEM_FLAG_CONSOLE_PRINT | Sends various useful messages to the console.
WBEM_FLAG_DONT_ADD_TO_LIST Prevents the file from being added to the list of files compiled during automatic database recovery.

This flag is not compatible with WBEM_FLAG_AUTORECOVER.

lClassFlags
Flags controlling the creation of classes.

Parameters may be zero or a combination of the following values.
Value Meaning
WBEM_FLAG_UPDATE_ONLY Prevents creation of a class.

You can combine this flag with either WBEM_FLAG_UPDATE_SAFE_MODE or WBEM_FLAG_UPDATE_FORCE_MODE.
WBEM_FLAG_CREATE_ONLY Allows only class creation.

You may not combine this flag with the other flags.
WBEM_FLAG_UPDATE_SAFE_MODE Updates the class unless conflicts exist.

You may combine this flag with WBEM_FLAG_UPDATE_ONLY.
WBEM_FLAG_UPDATE_FORCE_MODE Updates and resolves conflicts wherever possible.

You may combine this flag with llnstanceFlags.

lInstanceFlags
Flags controlling the creation of instances.

Parameter values can be either zero or one of the following flags.
Value | Meaning
WBEM_FLAG_UPDATE_ONLY | Only allow updates.
WBEM_FLAG_CREATE_ONLY | Allow only new instances.

pInfo
Pointer to the "C" style structure, WBEM_COMPILE_STATUS_INFO.

If the value is not NULL, an error has occurred, and the structure is filled in with error information.

struct
{
long lPhaseError; // 0 = no error, 1 = argument error, 2 = parsing, 3 error occurred while storing the data
HRESULT hRes; // Actual error code
long ObjectNum; // object which is at fault
long FirstLine; // first line number of the object
long LastLine; // last line number of the object
DWORD dwOutFlags; // reserved
} WBEM_COMPILE_STATUS_INFO;

Note ObjectNum, FirstLine, and LastLine only contain values for errors that relate to a particular class or instance in the file.

Return Values

If the CompilerFile method is successful, the compilation was performed successfully, and the method returns WBEM_S_NO_ERROR. If the method is unsuccessful, it returns WBEM_S_FALSE.

Remarks

If the User argument is in the form of <domain\user>, the Authority field must be NULL.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IMofCompiler::CompileBuffer

[This is preliminary documentation and subject to change.]

The CompileBuffer method compiles a buffer containing binary MOF data. Binary MOF files contain parsed data and only need to be stored in the database.

HRESULT IMofCompiler::CompileBuffer(
[in] long BuffSize,
[in, size_is(BuffSize)]BYTE *pBuffer,
[in, string] LPWSTR ServerAndNamespace,
[in, string] LPWSTR User,
[in, string] LPWSTR Authority,
[in, string] LPWSTR Password,
[in] LONG lOptionFlags,
[in] LONG lClassFlags,
[in] LONG lInstanceFlags,
[in, out] WBEM_COMPILE_STATUS_INFO *pInfo
);

Parameters

BuffSize
Size of the data pointed to by the pBuffer parameter.
pBuffer
Pointer to the binary MOF file data.
ServerAndNamespace
Name of the server and namespace.

This parameter is ignored because the binary MOF file already contains the information. The parameter value should be NULL.

User
Name of the user requesting the service.

This parameter specifies the credentials for compiling on remote machines. If the value is NULL, then the user context is whatever the current process is using. This is always ignored when connecting to the local machine. See the Remarks section of this topic.

Authority
This parameter specifies the credentials for compiling on remote machines. If the value is NULL, the Authority context is whatever the current process is using. This parameter is always ignored when connecting to the local machine. See the Remarks section of this topic.
Password
This parameter specifies the credentials for compiling on remote machine. If the value is NULL, the password of the current context is used. This parameter is always ignored when connecting to the local machine.
lOptionFlags
You can combine one or more of the following flags.
Value | Meaning
WBEM_FLAG_CHECK_ONLY | Performs only a syntax check.
WBEM_FLAG_AUTORECOVER If the method is successful, adds the name of the file to the list of files to are to be compiled during automatic database recovery.

Note that you cannot combine this flag with either the namespace, class, or instance flags.
WBEM_FLAG_CONSOLE_PRINT | Sends various useful messages to the console.
WBEM_FLAG_DONT_ADD_TO_LIST Prevents the addition of the file to the list of files to be compiled during automatic database recovery.

This flag is not compatible with WBEM_FLAG_AUTORECOVER.

lClassFlags
This parameter is ignored because the binary MOF file already contains the information. The parameter value should be zero.
lInstanceFlags
This parameter is ignored because the binary MOF file already contains the information. The parameter value should be zero.
pInfo
Pointer to the "C" style structure, WBEM_COMPILE_STATUS_INFO.

If the parameter value is not NULL, an error has occurred, and the structure is filled in with error information.

struct
{
long lPhaseError; // 0 = no error, 1 = argument error, 2 = parsing, 3 error occurred while storing the data
HRESULT hRes; // Actual error code
long ObjectNum; // object which is at fault
long FirstLine; // first line number of the object
long LastLine; // last line number of the object
DWORD dwOutFlags; // reserved
} WBEM_COMPILE_STATUS_INFO;

Note ObjectNum, FirstLine, and LastLine only contain values for errors that relate to a particular class or instance in the file.

Return Values

If the CompileBuffer method is successful, the method returns WBEM_S_NO_ERROR. If the method is unsuccessful, it returns WBEM_S_FALSE.

Remarks

If the User parameter takes the form <domain\user>, the Authority field must be NULL.

Binary MOF data can be generated by the CreateBMOF method, which stores the binary MOF data into a file that can be read before calling the CompileBuffer method.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IMofCompiler::CreateBMOF

[This is preliminary documentation and subject to change.]

The CreateBMOF method creates a binary MOF file.

File creation is accomplished by parsing a regular MOF file and storing a binary representation of the classes and instances into a special file format. Typically, this data binary large object (BLOB) is stored as a resource in an executable file, which can later be extracted for a call to the CompileBuffer method.

HRESULT IMofCompiler::CreateBMOF(
[in, string] LPWSTR TextFileName,
[in, string] LPWSTR BMOFFileName,
[in, string] LPWSTR ServerAndNamespace,
[in] LONG lOptionFlags,
[in] LONG lClassFlags,
[in] LONG lInstanceFlags,
[in, out] WBEM_COMPILE_STATUS_INFO * pInfo
);

Parameters

TextFileName
Name of the text file that is to be parsed.
BMOFFileName
Name of the file in which the resulting binary MOF data is to be stored.
ServerAndNamespace
Path of the default namespace, where any classes or instances are written.

You can use this parameter to specify a namespace on a remote machine (\\Computer\Root, for example). This value may be overridden by pragmas and should not be used if you use autorecovery. If the parameter value is NULL, the Root\Default namespace on the local machine is the default.

lOptionFlags
You can combine one or more of the following flags.
Value | Meaning
WBEM_FLAG_CHECK_ONLY | Performs only a syntax check.
WBEM_FLAT_CONSOLE_PRINT | Sends various useful messages to the console.
WBEM_FLAG_WMI_CHECK | Performs additional checks on the resulting binary MOF file using the WMIMOFCHK program, which is part of the WMI SDK.

lClassFlags
Flags controlling the creation of classes. The parameter value may be zero or a combination of the following flags.
Value Meaning
WBEM_FLAG_UPDATE_ONLY Prevents class creation.

You can combine this flag with either WBEM_FLAG_UPDATE_SAFE_MODE or WBEM_FLAG_UPDATE_FORCE_MODE.
WBEM_FLAG_CREATE_ONLY Permits only class creation.

You may not combine this and other flags.
WBEM_FLAG_UPDATE_SAFE_MODE Updates the class unless conflicts exist.

You may combine this flag with WBEM_FLAG_UPDATE_ONLY.
WBEM_FLAG_UPDATE_FORCE_MODE Updates and resolves conflicts wherever possible.

You can combine this flag with lInstanceFlags

lInstanceFlags
Flags controlling the creation of instances.

The parameter value may be either zero or one of the following flags.
Value | Meaning
WBEM_FLAG_UPDATE_ONLY | Permits only permit updates.
WBEM_FLAG_CREATE_ONLY | Permits only new instances.

pInfo
Pointer to the "C" style structure, WBEM_COMPILE_STATUS_INFOb

If the parameter value is not NULL, an error has occurred, and the structure is filled in with error information.

struct
{
long lPhaseError; // 0 = no error, 1 = argument error, 2 = parsing, 3 error occurred while store the data
HRESULT hRes; // Actual error code
long ObjectNum; // object which is at fault
long FirstLine; // first line number of the object
long LastLine; // last line number of the object
DWORD dwOutFlags; // reserved
} WBEM_COMPILE_STATUS_INFO;

Note ObjectNum, FirstLine, and LastLine only contain values for errors that relate to a particular class or instance in the file.

Return Values

If the CreateBMOF method is successful, it returns WBEM_S_NO_ERROR. If the method is unsuccessful, it returns WBEM_S_FALSE.

IWbemBackupRestore

[This is preliminary documentation and subject to change.]

The IWbemBackupRestore interface defines the following methods:

Method | Description
Backup |
Restore

Remarks

Remarks here.


IWbemBackupRestore::Backup

[This is preliminary documentation and subject to change.]

The Backup method ..TELL US WHAT IT DOES HERE…

Definition

HRESULT IWbemBackupRestore::Backup(
  LPCWSTR strBackupToFile,
  long lFlags
);

Parameters

strBackupToFile
[in, string] Constant null-terminated string of 16-bit Unicode characters that contains the backup To file. VERIFY THIS INFO
lFlags
[in] Integer that contains the flags. VERIFY THIS INFO WHAT Lflags are valid for this?

Return Values

This method returns an HRESULT with one of the following values: VERIFY THE RETURN VALUE AND MEANING

Value | Meaning
S_OK | Method succeeded.

Remarks

Remarks here.

Example

The following example ___:

PUT IN AN EXAMPLE myWbemBackupRestore.Backup(strBackupToFile, lFlags);


IWbemBackupRestore::Restore

[This is preliminary documentation and subject to change.]

The Restore method …TELL US WHAT IT DOES HERE.

Definition

HRESULT IWbemBackupRestore::Restore(
  LPCWSTR strRestoreFromFile,
  long lFlags
);

Parameters

strRestoreFromFile
[in, string] Constant null-terminated string of 16-bit Unicode characters that contains IWbemBackupRestore::Backupthe restore from file. VERIFY THIS INFO
lFlags
[in] Integer that contains the flags. VERIFY THIS INFO WHAT Lflags are valid for this?

Return Values

This method returns an HRESULT with one of the following values: VERIFY THE RETURN VALUE AND MEANING

Value | Meaning
S_OK | Method succeeded.

Remarks

Remarks here.

Example

The following example ___:

PUT IN AN EXAMPLE myWbemBackupRestore.Restore(strRestoreFromFile, lFlags); ›

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemCallResult

You can use the IWbemCallResult interface for semisynchronous calls of the IWbemServices interface. When you make such calls, the IWbemServices method returns immediately, along with an IWbemCallResult object. Periodically, you can poll the returned IWbemCallResult object to determine the status of the call. You can obtain the result of the original IWbemServices call after it is complete by calling IWbemCallResult::GetCallStatus. You can obtain the result of the original IWbemServices call after it is complete by calling IWbemCallResult::GetCallStatus.

This call-return paradigm is useful in cases where a thread cannot afford to be blocked for more than a few seconds because it is servicing other tasks, such as processing window messages.

Not all IWbemServices methods support this interface because it is not required for all of them. The intent is to allow nonblocking synchronous operation (semisynchronous operation) for all relevant operations. Since many of the IWbemServices methods are already nonblocking due to the use of enumerators or other constructs, only OpenNamespace, GetObject, PutInstance, PutClass, DeleteClass, DeleteInstance, and ExecMethod need this helper interface to support semisynchronous operation.

IWbemCallResult Methods | Description
GetCallStatus | Reports whether a semisynchronous call was successful.
GetResultObject | Returns an IWbemClassObject; which is the result of a semisynchronous call to IWbemServices::GetObject.
GetResultServices | Returns the result of a semisynchronous call to IWbemServices::OpenNamespace verb action.
GetResultString | Returns an object path, which is the result of a semisynchronous call to IWbemServices::PutInstance.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemCallResult::GetResultObject

The IWbemCallResult::GetResultObject method will attempt to retrieve an object from a previous semisynchronous call to IWbemServices::GetObject or IWbemServices::ExecMethod. If the object is not yet available, the call returns WBEM_S_TIMEDOUT. Also, before invoking this method to get the resultant object, you may call IWbemCallResult::GetCallStatus until it returns WBEM_S_NO_ERROR, indicating that the original semisynchronous operation is complete.

HRESULT GetResultObject(
  LONG lTimeout,
  IWbemClassObject **ppResultObject
);

Parameters

lTimeout
[in] Specifies the maximum time in milliseconds that this call will block before returning. If you use the constant WBEM_INFINITE (0xFFFFFFFF), the call will block until the object is available. If you use zero, the call immediately returns either the object or a status code.
ppResultObject
[out] This parameter cannot be NULL. It receives the copy of the object when it becomes available. You must call IWbemClassObject::Release on the returned object when the object is no longer required.

A new object is not returned on error.

Return Values

Value | Meaning
WBEM_S_NO_ERROR | The object successfully returned .
WBEM_S_TIMEDOUT | The object was not yet available after the lTimeout value expired.
WBEM_E_UNEXPECTED | The call failed, and it is not expected to complete.
WBEM_E_TRANSPORT_FAILURE | This indicates the failure of the remote procedure call (RPC) link between the current process and Windows Management.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.

Note If the original semi-synchronous operation failed such as when the object was not found, or the method could not be invoked, this method will return the error code that the original API would have returned in its synchronous version.

On error, you can call the COM function GetErrorInfo to obtain more error information.

DCOM-specific error codes may also be returned if network problems cause you to lose the remote connection to Windows Management.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemServices::GetObject, IWbemServices::ExecMethod


IWbemCallResult::GetResultString

The IWbemCallResult::GetResultString method returns the assigned object path of an instance newly created by IWbemServices::PutInstance.

Note The call result object is primarily used when the PutInstance call is carried out by a provider and the client needs to know the object path (the values of the key properties) assigned the provider. For example, if the key property to the class is a globally unique identifier (GUID), and it is assigned by the provider during the PutInstance operation, the client would have no way of knowing this GUID unless the provider was able to return it in this way.

HRESULT GetResultString(
  LONG lTimeout,
  BSTR *pstrResultString
);

Parameters

lTimeout
[in] Specifies the maximum time in milliseconds that this call will block before returning. If you use the constant WBEM_INFINITE (0xFFFFFFFF), the call will block until the object path is available. If you use zero, the call immediately returns either the object path or a status code.
pstrResultString
[out] Cannot be NULL. This parameter receives a pointer to the object path, which, in turn, leads to the newly created object. The returned string must be deallocated using the system call SysFreeString. On error, a new string is not returned.

Return Values

Value | Meaning
WBEM_S_NO_ERROR | The object path was retrieved.
WBEM_S_TIMEDOUT | The object was not yet available after the lTimeout value expired.
WBEM_E_UNEXPECTED | An internal failure occurred.
WBEM_E_TRANSPORT_FAILURE | This indicates the failure of the remote procedure call (RPC) link between the current process and Windows Management.
WBEM_E_ACCESS_DENIED | The caller attempted an unauthorized operation.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_FAILED | An unspecified error occurred.

On error, you can call the COM function GetErrorInfo to obtain more error information.

Note DCOM-specific error codes may also be returned if network problems cause you to lose the remote connection to Windows Management.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemServices::PutInstance


IWbemCallResult::GetResultServices

You can use the IWbemCallResult::GetResultServices method to retrieve the IWbemServices pointer, which resulted from a semisynchronous call to IWbemServices::OpenNamespace when it becomes available.

HRESULT GetResultServices(
  LONG lTimeout,
  IWbemServices **ppServices
);

Parameters

lTimeout
[in] Specifies the maximum time in milliseconds that this call will block before it returns. If you use the constant WBEM_INFINITE (0xFFFFFFFF), the call will block until the interface pointer is available. If you use zero, the call immediately returns either the pointer or a status code.
ppServices
[out] This parameter cannot be NULL. It receives a pointer to the IWbemServices interface requested by the original call to OpenNamespace when it becomes available The caller must call IWbemServices::Release on the returned object when it is no longer required.

On error, a new object is not returned.

Return Values

Value | Meaning
WBEM_S_NO_ERROR | The call succeeded and returned an IWbemServices pointer.
WBEM_S_TIMEDOUT | The time-out occurred, and the call has not yet completed.
WBEM_E_UNEXPECTED | An internal failure occurred.
WBEM_E_TRANSPORT_FAILURE | This indicates the failure of the remote procedure call (RPC) link between the current process and Windows Management.
WBEM_E_ACCESS_DENIED | The user attempted to perform an unauthorized operation.
WBEM_E_INVALID_NAMESPACE | The specified namespace did not exist on the server.
WBEM_E_FAILED | There has been a general failure.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.

On error, the COM function GetErrorInfo can be called to obtain more error information.

Note DCOM-specific error codes may also be returned if network problems cause you to lose the remote connection to Windows Management.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemServices::OpenNamespace


IWbemCallResult::GetCallStatus

The IWbemCallResult::GetCallStatus method returns to the user the status of the current outstanding semisynchronous call. When this call returns WBEM_S_NO_ERROR, the original call to the IWbemServices method is complete.

HRESULT GetCallStatus(
  LONG lTimeout,
  LONG *plStatus
);

Parameters

lTimeout
[in] Specifies the maximum time in milliseconds that this call will block before it returns. If you use the constant WBEM_INFINITE (0xFFFFFFFF), the call will block until the original semisynchronous call to an IWbemServices method is complete. If you use zero, the call immediately returns the call status.
plStatus
[out] If WBEM_S_NO_ERROR returns in the HRESULT to this method, this parameter will receive the final result status of a call to one of the IWbemServices methods: OpenNamespace, PutInstance, PutClass, GetObject, DeleteInstance, DeleteClass, or ExecMethod. On error, the value pointed to by plStatus will not be used.

Return Values

Value | Meaning
WBEM_S_NO_ERROR | The call is complete, and plStatus has been assigned.
WBEM_S_TIMEDOUT | The object was not yet available after the lTimeout value expired.
WBEM_E_TRANSPORT_FAILURE | This indicates the failure of the remote procedure call (RPC) link between the current process and Windows Management.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_FAILED | An unexpected system error has occurred.

On error, you can call the COM function GetErrorInfo to obtain more error information.

Note DCOM-specific error codes may also be returned if network problems cause you to lose the remote connection to Windows Management.

Remarks

After invoking an IWbemServices method semisynchronously, you can call GetCallStatus at any time to determine whether the call is complete. After GetCallStatus has returned WBEM_S_NO_ERROR, which indicates completion of the original IWbemServices operation, calls to other IWbemCallResult methods may be required to retrieve the result of the call, according to the following rules:

  1. For the IWbemServices method OpenNamespace, the GetResultServices method must be called to retrieve the new IWbemServices pointer.
  2. For the IWbemServices method PutInstance, the GetResultString method must be called to obtain the object path that was assigned to the object.
  3. For the IWbemServices method GetObject, the GetResultObject method must be called to retrieve the object.
  4. For the IWbemServices methods DeleteInstance, DeleteClass, and ExecMethod, the GetCallStatus method is the only call that returns information regarding these operations.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemServices::OpenNamespace, IWbemServices::PutInstance, IWbemServices::GetObject, IWbemServices::DeleteInstance, IWbemServices::DeleteClass, IWbemServices::ExecMethod


IWbemClassObject

The IWbemClassObject interface contains and manipulates both class definitions and class object instances.

From the Windows Management Instrumentation (WMI) client perspective, this interface is always in-process. Put (write) operations will only affect the local copy of the object, and Get (read) operations always retrieve values from the local copy. You can perform updates to Windows Management only when entire objects are read or written using methods on the IWbemServices interface. Examples of such updates are: IWbemServices::PutInstance or IWbemServices::PutClass.

This interface is not implemented by the user or by a provider under any circumstances. The implementation provided by Windows Management is the only one that is supported.

IWbemClassObject Methods | Description
BeginEnumeration | Begins an enumeration of the properties.
BeginMethodEnumeration | Begins an enumeration of CIM methods for the object.
Clone | Makes a copy of the current object.
CompareTo | Tests two objects for equality.
Delete | Removes the specified property from the object.
DeleteMethod | Removes a CIM method.
EndEnumeration | Ends an enumeration begun with BeginEnumeration.
EndMethodEnumeration | Ends the enumeration of CIM methods for an object.
Get | Gets a particular property value.
GetMethod | Gets the in- and out-parameter definitions for a specific CIM method.
GetMethodOrigin | Reports the class in which a CIM method is defined.
GetMethodQualifierSet | Returns the qualifier set object for a specific CIM method.
GetNames | Obtains a list of the names of the properties in the object.
GetObjectText | Obtains the textual rendition of the object in Managed Object Format (MOF) syntax.
GetPropertyOrigin | Reports the class in which a particular property was introduced.
GetPropertyQualifierSet | Allows access to the qualifiers of a particular property.
GetQualifierSet | Allows access to the qualifier set of the entire object.
InheritsFrom | Reports whether the current object inherits from a particular class.
Next | Obtains the next property in an enumeration after an initial call to BeginEnumeration.
NextMethod | Retrieves the next CIM method definition in an enumeration of methods.
Put | Updates or creates a particular property value.
PutMethod | Creates a CIM method.
SpawnDerivedClass | Creates a new derived class from the current class.
SpawnInstance | Creates a new instance from the current class.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemClassObject::GetQualifierSet

The IWbemClassObject::GetQualifierSet method returns an interface pointer that allows read and write operations on the set of qualifiers for the entire class object, whether the object is an instance or a class definition. Any qualifiers added, deleted, or edited using the returned pointer apply to the entire instance or class definition.

HRESULT IWbemClassObject::GetQualifierSet(
  IWbemQualifierSet **ppQualSet
);

Parameters

ppQualSet
[out] Receives the interface pointer that allows access to the qualifiers for the class object. The returned object has a positive reference count upon return from the call. The caller must call IWbemQualifierSet::Release when the object is no longer needed. This parameter cannot be NULL. On error, a new object is not returned and the pointer is left unmodified.

Return Values

Value | Meaning
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the call.
WBEM_S_NO_ERROR | The call succeeded.
WBEM_E_INVALID_PARAMETER | A null pointer was used in the parameter list.
WBEM_E_FAILED | There has been a general failure.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemQualifierSet, IWbemClassObject::GetPropertyQualifierSet


IWbemClassObject::Get

The IWbemClassObject::Get method retrieves the specified property value, if it exists. This method also can return system properties.

HRESULT IWbemClassObject::Get(
  LPCWSTR wszName,
  LONG lFlags,
  VARIANT *pVal,
  CIMTYPE *pvtType,
  LONG *plFlavor
);

Parameters

wszName
[in] Name of the desired property. It is treated as read-only.
lFlags
[in] Reserved. It must be zero.
pVal
[out, OPTIONAL] Points to an existing uninitialized VARIANT structure that receives the property value, if found. Since this is an output parameter, this method calls VariantInit on this VARIANT, so you must be sure that this is not pointing to an active VARIANT. The pVal parameter can be NULL if a property value is not required. If an error code is returned from this method, the pointer is left unmodified.

Note You must call VariantClear on the returned VARIANT when its value is no longer required. This will prevent memory leaks in the client process. The type of the VARIANT returned does not always indicate the real CIM type of the property, which is indicated by the pType out-parameter. If the property currently has no value (the null value), or the caller doesn't have the authority to read it, the VARIANT is of type VT_NULL. Client applications must use the plType parameter to learn the real CIM type of the property.

If the type is VT_UNKNOWN, the returned property in the VARIANT is an embedded IWbemClassObject. After extracting the IUnknown pointer, the user must call IUnknown::QueryInterface for IID_IWbemClassObject and use the returned pointer to access the embedded IWbemClassObject. Note that VariantClear invokes Release on the IUnknown pointer. In addition, the user must explicitly Release the IWbemClassObject retrieved from IUnknown::QueryInterface.

pvtType
[out, OPTIONAL] Can be NULL. If it is not NULL, it receives the CIM type of the property, that is, one of the CIM-type constants, such as CIM_SINT32, CIM_STRING, and so on. This indicates the CIM semantics of the property value packed into VARIANT.
plFlavor
[out, OPTIONAL] Can be NULL. If not NULL, the LONG value pointed to receives information on the origin of the property:
WBEM_FLAVOR_ORIGIN_LOCAL
The property belongs to the derived-most class.
WBEM_FLAVOR_ORIGIN_PROPAGATED
The property was inherited from a parent class.
WBEM_FLAVOR_ORIGIN_SYSTEM
The property is a standard system property.
WBEM_FLAVOR_ORIGIN_LOCAL
The property value is overridden in the instance.

Return Values

Value | Meaning
WBEM_E_FAILED | There has been a general failure.
WBEM_E_NOT_FOUND | The specified property was not found.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_INVALID_PARAMETER | One or more parameters was not valid.
WBEM_S_NO_ERROR | The call succeeded.

Remarks

If the underlying type of the property is an object path, a date/time string, or another special type, the returned values in the VARIANT will not contain enough information to identify the true type. The pvtType out-parameter will indicate this.

To obtain the string form of the CIM type for the property, the IWbemQualifierSet pointer for the property must be obtained and the Cimtype qualifier retrieved. That qualifier is the string form of the CIM type, such as "sint32" versus CIM_SINT32 (a numeric constant).

Note When you create a new object using IWbemClassObject::SpawnInstance, it is important to note that some system properties are not set until the object has been written to Windows Management. In all cases, IWbemClassObject::Get will succeed in accessing the requested system property, but the returned VARIANT may contain VT_NULL.

Sample Code

The following sample code retrieves the CIM class name from an object using the system property __CLASS:

IWbemClassObject *pObj = NULL;
VARIANT v;
BSTR strClassProp = SysAllocString(L"__CLASS");
pObj->Get(strClassProp, 0, &v, 0, 0);
SysFreeString(strClassProp);
wprintf(L"The class name is %s\n", V_BSTR(&v));
VariantClear( &v );

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemClassObject::GetPropertyQualifierSet


IWbemClassObject::Put

The IWbemClassObject::Put method sets a named property to a new value. This method always overwrites the current value with the new one. When IWbemClassObject points to a CIM class definition, Put will either create or update the property value. When IWbemClassObject points to a CIM instance, Put will update a property value only; it cannot create one.

The user may not create properties with names that begin or end with an underscore. This is reserved for system classes and properties.

HRESULT IWbemClassObject::Put(
  LPCWSTR wszName,
  LONG lFlags,
  VARIANT *pVal,
  CIMTYPE vtType
);

Parameters

wszName
[in] Must point to a valid LPCWSTR containing the property name. The pointer is treated as read-only. This cannot be NULL.
lFlags
[in] Reserved. It must be zero.
pVal
[in] Must point to a valid VARIANT, which becomes the new property value. If pVal is NULL or points to a VARIANT of type VT_NULL, the property is set to NULL, that is, no value.
vtType
[in] Type of VARIANT pointed to by pVal.

The NULL value for a property designated by a VARIANT of type VT_NULL is distinguished from a property of type VT_I4 with a zero value.

When creating new properties, if pVal is NULL or points to a VT_NULL, the type of the property is determined from the vtType parameter.

If pVal is to contain an embedded IWbemClassObject, the caller must call IWbemClassObject::QueryInterface for IID_IUNKNOWN and place the resulting pointer in the VARIANT using a type of VT_UNKNOWN. The original embedded object is copied during the Put operation, and so cannot be modified by the operation.

The pointer is treated as read-only. The caller is responsible for invoking VariantClear after this call is complete.

Use this parameter only when creating new properties in a CIM class definition and pVal is NULL or points to a VARIANT of type VT_NULL. In such a case, the vtType parameter specifies the CIM type of the property. In every other case, vtType must be zero. Also, vtType must be zero whenever the underlying object is an instance (even if pVal is NULL), since the type of the property is fixed and cannot be changed. In other words, use vtType if, and only if, pVal is NULL or points to a VT_NULL VARIANT, and the underlying object is a CIM class.

Return Values

Value | Meaning
WBEM_E_FAILED | There has been a general failure.
WBEM_E_INVALID_PARAMETER | An NULL or otherwise invalid parameter was specified.
WBEM_E_INVALID_PROPERTY_TYPE | Property type is not recognized. If creating class instances, this is returned if the class already exists.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_TYPE_MISMATCH | For instances, this error code indicates that the pVal parameter points to a VARIANT of an incorrect type for the property. For class definitions, this is returned if the property already exists in the parent class, and the new COM type is different from the old COM type. Such properties are read-only for the derived class.
WBEM_S_NO_ERROR | The call succeeded.

Remarks

If the property set by the IWbemClassObject::Put method exists in the superclass, the default value of the property is changed unless the property type does not match the superclass type. If the property does not exist and it is not a type mismatch, the property is created.

When executing this method on an instance, an overwrite always occurs. It occurs because the property always exists.

When you are creating a new class and the underlying type of the property is an object reference, a date/time string, or other special type, you might need to modify the Cimtype qualifier for the property to indicate the special new class. When modifying properties of an instance, the qualifiers are set to the correct values ahead of time.

If the variant type specified in pVal does not match the CIM type of the property, WMI attempts to change the variant to the appropriate variant type, using the normal variant coercion rules. If the variant cannot be coerced, WBEM_E_TYPE_MISMATCH is returned.

You can only write system properties when you create a new class. In that case, the name of the class you create is designated by writing it to the system property __CLASS.

Sample Code

The following code sample sets the class name for a new CIM class:

// Empty object from IWbemServices::GetObject

IWbemClassObject *pObj = …

// Set up the property value
VARIANT v;
VariantInit(&v);
V_VT(&v) = VT_BSTR;
V_BSTR(&v) = SysAllocString(L"MyClass");

// Write it
BSTR strClassProp = SysAllocString(L"__CLASS");
pObj->Put(strClassProp, 0, &v, 0);

// Cleanup
SysFreeString(strClassProp);
VariantClear(&v);

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemClassObject::Delete

The IWbemClassObject::Delete method deletes the specified property from a CIM class definition and all of its qualifiers. Since instances cannot have contents that are different from the owning class, delete operations for properties are only possible on class definitions. If you invoke Delete on a property in an instance, the operation succeeds, but rather than removing the value it is simply reset to the default value for the class.

It is not possible to delete a property that was inherited from a parent class. However, if an override default value for a property inherited from a parent class was specified, it is possible to revert to the parent's default value by invoking this method. In this case, WBEM_S_RESET_TO_DEFAULT returns.

System properties cannot be deleted.

HRESULT IWbemClassObject::Delete(
  LPCWSTR wszName
);

Parameters

wszName
[in] The property name to delete. This must point to a valid LPCWSTR. It is treated as read-only.

Return Values

Value | Meaning
WBEM_E_FAILED | There has been a general failure.
WBEM_E_INVALID_OPERATION | The user attempted to delete a property which cannot be deleted.
WBEM_E_INVALID_PARAMETER | An invalid Name was specified.
WBEM_E_NOT_FOUND | The specified property does not exist.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_PROPAGATED_PROPERTY | The user attempted to delete a property that was not owned. The property was inherited from a parent class.
WBEM_E_SYSTEM_PROPERTY | The user attempted to delete a system property.
WBEM_S_NO_ERROR | The call succeeded.
WBEM_S_RESET_TO_DEFAULT | The caller deleted an override default value for the current class. The default value for this property in the parent class has been reactivated.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

System Properties


IWbemClassObject::GetNames

The IWbemClassObject::GetNames method retrieves the names of the properties in the object. Furthermore, depending on user-supplied selection criteria, it can retrieve all or a subset of the properties. These properties can then be accessed by using IWbemClassObject::Get for each name. This method can also return system properties.

HRESULT IWbemClassObject::GetNames(
  LPCWSTR wszQualifierName,
  LONG lFlags,
  VARIANT *pQualifierValue,
  SAFEARRAY (BSTR) **pstrNames
);

Parameters

wszQualifierName
[in] Can be NULL. If not NULL, it must point to a valid LPCWSTR specifying a qualifier name which acts as part of a filter. This is treated as read-only. See Remarks.
lFlags
[in] See Remarks.
pQualifierValue
[in] Can be NULL. If not NULL, it must point to a valid VARIANT structure initialized to a filter value. See Remarks. This VARIANT is treated as read-only by the method. Thus, the caller is responsible for calling VariantClear on it, if required.
pstrNames
[out] Cannot be NULL, but on entry this parameter must point to NULL. A new SAFEARRAY is always allocated, and the pointer is set to point to it. The returned array can have zero elements, but is always allocated when WBEM_S_NO_ERROR returns. On error, a new SAFEARRAY is not returned.

Return Values

Value | Meaning
WBEM_E_FAILED | There has been a general failure.
WBEM_E_INVALID_PARAMETER | One or more parameters were invalid, or an incorrect combination of flags and parameters was specified.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the task.
WBEM_S_NO_ERROR | The call succeeded.

Remarks

The names returned are controlled by a combination of flags and parameters. For example, all names of all properties can be specified, or only the key properties can be specified, and so on. The primary filter is specified in the lFlags parameter; the other parameters vary depending upon it.

The flag values are bit fields, and can be combined. One flag from each of the following groups can be combined with a flag from each of the other groups. Flag values within a group are mutually exclusive.

GROUP 1

WBEM_FLAG_ALWAYS
Return all property names. strQualifierName and pQualifierVal are not used.
WBEM_FLAG_ONLY_IF_TRUE
Return only properties that have a qualifier of the name specified by the parameter strQualifierName. If this flag is used, you must specify strQualifierName.
WBEM_FLAG_ONLY_IF_FALSE
Return only properties that do not have a qualifier of the name specified by the parameter strQualifierName. If this flag is used, you must specify strQualifierName.
WBEM_FLAG_ONLY_IF_IDENTICAL
Return only properties that have a qualifier of the name specified by the parameter QualifierName, and also have a value identical to the value specified by the VARIANT pointed to by pQualifierVal. If this flag is used, you must specify both QualifierName and pQualifierVal.

GROUP 2

WBEM_FLAG_KEYS_ONLY
Return only the names of the property or properties that define the keys.
WBEM_FLAG_REFS_ONLY
Return only property names that are object references.

GROUP 3

WBEM_FLAG_LOCAL_ONLY
Return only property names that belong to the derived-most class. Exclude properties from the superclass or superclasses.
WBEM_FLAG_PROPAGATED_ONLY
Return only property names that belong to the superclass or superclasses.
WBEM_FLAG_SYSTEM_ONLY
Return only system properties.
WBEM_FLAG_NONSYSTEM_ONLY
Return only property names that are not system properties.

It is not an error for an empty list to be returned in cases where no properties match the specified filters.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemClassObject::Get, System Properties, IWbemClassObject::BeginEnumeration

For an example of using SAFEARRAYs of BSTRs, see Displaying Instance Properties.


IWbemClassObject::BeginEnumeration

The IWbemClassObject::BeginEnumeration method resets an enumeration back to the beginning of the enumeration. The caller must call this method prior to the first call to IWbemClassObject::Next to enumerate all of the properties on an object. The order in which properties are enumerated is guaranteed to be invariant for a given instance of IWbemClassObject.

HRESULT IWbemClassObject::BeginEnumeration(
  LONG lEnumFlags
);

Parameters

lEnumFlags
[in] A combination of flags described in Remarks.

Return Values

Value | Meaning
WBEM_E_INVALID_PARAMETER | The specified combination of flags was invalid or an invalid parameter was specified.
WBEM_E_UNEXPECTED | A second call was made to IWbemClassObject::BeginEnumeration without an intervening call to IWbemClassObject::EndEnumeration
WBEM_E_OUT_OF_MEMORY | There is not enough memory to begin a new enumeration.
WBEM_S_NO_ERROR | The call succeeded.

Remarks

You can control the properties included in the enumeration by specifying a combination of the following flags. You can combine one flag from each group with any flag from any other group. However, flags from the same group are mutually exclusive.

GROUP 1

WBEM_FLAG_KEYS_ONLY
Only include properties that constitute the key.
WBEM_FLAG_REFS_ONLY
Only include properties that are object references.

GROUP 2

WBEM_FLAG_LOCAL_ONLY
Only include properties that are defined or modified in the class itself. Exclude all properties that are inherited from superclasses. Exclude system properties from the enumeration.
WBEM_FLAG_PROPAGATED_ONLY
Only include properties that are inherited from superclasses. Exclude properties that are defined or modified in the class itself. Exclude system properties from the enumeration.
WBEM_FLAG_SYSTEM_ONLY
Limit the enumeration to system properties only.
WBEM_FLAG_NONSYSTEM_ONLY
Exclude system properties from the enumeration. Includes local and propagated properties.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemClassObject::Next, System Properties, IWbemClassObject::EndEnumeration


IWbemClassObject::Next

The IWbemClassObject::Next method retrieves the next property in an enumeration that started with IWbemClassObject::BeginEnumeration. This should be called repeatedly to enumerate all the properties until WBEM_S_NO_MORE_DATA returns. If the enumeration is to be terminated early, then IWbemClassObject::EndEnumeration should be called.

The order of the properties returned during the enumeration is not defined.

HRESULT IWbemClassObject::Next(
  LONG lFlags,
  BSTR *pstrName,
  VARIANT *pVal,
  CIMTYPE *pvtType,
  LONG *plFlavor
);

Parameters

lFlags
[in] Reserved. It must be zero.
pstrName
[out, OPTIONAL] Receives a new BSTR which contains the property name. To prevent memory leaks in the client process, the caller must call SysFreeString when the name is no longer needed. You can set this parameter to NULL if the name is not required.
pVal
[out, OPTIONAL] This VARIANT is filled with the value of the property. The method calls VariantInit on this VARIANT, so the caller should ensure that the VARIANT is not active prior to the call. The caller must use VariantClear when the value is no longer needed.

You can set this parameter to NULL if the value is not required. If an error code is returned, the VARIANT pointed to by pVal is left unmodified.

pvtType
[out, OPTIONAL] This parameter can be NULL. If it is not NULL, it must point to a CIMTYPE variable (a LONG) into which the type of the property is placed. It is possible that the value of this property can be a VT_NULL VARIANT, in which case it is necessary to determine the actual type of the property.
plFlavor
[out, OPTIONAL] Can be NULL. If not NULL, the LONG value pointed to receives information on the origin of the property as follows:
WBEM_FLAVOR_ORIGIN_LOCAL
The property belongs to the derived-most class.
WBEM_FLAVOR_ORIGIN_PROPAGATED
The property was inherited from a parent class.
WBEM_FLAVOR_ORIGIN_SYSTEM
The property is a standard system property.

Return Values

Value | Meaning
WBEM_E_FAILED | An unspecified error has occurred.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_UNEXPECTED | Did not call IWbemClassObject::BeginEnumeration.
WBEM_S_NO_ERROR | The call succeeded.
WBEM_S_NO_MORE_DATA | No more properties are left in the enumeration.
WBEM_E_TRANSPORT_FAILURE | This indicates the failure of the remote procedure call (RPC) link between the current process and Windows Management.

Remarks

If the underlying type of the property is an object path, a date/time, or another special type, then the returned type does not contain enough information. The caller must examine the CIMTYPE for the specified property, and determine if the property is an object reference, date/time, or another special type.

This method also returns system properties.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemClassObject::BeginEnumeration, IWbemClassObject::EndEnumeration, IWbemClassObject::Get, System Properties


IWbemClassObject::EndEnumeration

The IWbemClassObject::EndEnumeration method terminates an enumeration sequence started with IWbemClassObject::BeginEnumeration. This call is not required, but it is recommended to developers because it releases resources associated with the enumeration. However, the resources are deallocated automatically when the next enumeration is started or the object is released.

HRESULT IWbemClassObject::EndEnumeration( );

Parameters

None.

Return Values

Value | Meaning
WBEM_E_FAILED | There has been a general failure.
WBEM_S_NO_ERROR | The call succeeded.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemClassObject::BeginEnumeration, IWbemClassObject::Next


IWbemClassObject::GetPropertyQualifierSet

The IWbemClassObject::GetPropertyQualifierSet method gets the qualifier set for a particular property in the class object. You can use this method with properties that are a member of an instance or a class definition.

HRESULT IWbemClassObject::GetPropertyQualifierSet(
  LPCWSTR wszProperty,
  IWbemQualifierSet **ppQualSet
);

Parameters

wszProperty
[in] The property for which the qualifier set is requested. This must point to a valid LPCWSTR, which is treated as read-only. The property can be local or propagated from the superclass. Note that system properties have no qualifiers so this method returns the error code WBEM_E_SYSTEM_PROPERTY if you attempt to obtain the IWbemQualifierSet pointer for a system property.
ppQualSet
[out] Receives an interface pointer that allows access to the qualifiers for the named property. The caller must call IWbemQualifierSet::Release on the pointer when access to the object is no longer required. The property is set to point to NULL when there are error conditions. A new object is not returned.

Return Values

Value | Meaning
WBEM_E_FAILED | There has been a general failure.
WBEM_E_NOT_FOUND | The specified property does not exist.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_SYSTEM_PROPERTY | There was an attempt to get qualifiers on a system property.
WBEM_S_NO_ERROR | The call succeeded.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemQualifierSet


IWbemClassObject::Clone

The IWbemClassObject::Clone method returns a new object that is a complete clone of the current object. The new object has a COM reference count of 1.

HRESULT IWbemClassObject::Clone(
  IWbemClassObject **ppCopy
);

Parameters

ppCopy
[out] This parameter cannot be NULL. It receives the copy of the current object. You must call IWbemClassObject::Release on this object when it is no longer required.

A new object is not returned on error.

Return Values

Value | Meaning
WBEM_E_FAILED | There has been a general failure.
WBEM_E_INVALID_PARAMETER | NULL was specified as a parameter, and it is not legal in this usage.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to clone the object.
WBEM_S_NO_ERROR | The call succeeded.

Remarks

Use this method to duplicate a class definition, or to duplicate an instance. This can be useful when the original copy of the object is required for backup purposes while a new copy is modified. Likewise, you can use this method to create many new instances from a single source instance. For example, you can use IWbemClassObject::SpawnInstance to create a single starting instance, and you can use IWbemClassObject::Clone to produce 100 copies of the instance quickly. Each object can be modified subsequently to take on its particular values.

It is not possible to use this method to convert a class definition into an instance, or convert an instance into a class definition.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemClassObject::GetObjectText

The IWbemClassObject::GetObjectText method returns a textual rendering of the object in the MOF syntax. Notice that the MOF text returned does not contain all the information about the object, but only enough information for the MOF compiler to be able to re-create the original object. For instance, no propagated qualifiers or parent class properties are displayed.

HRESULT IWbemClassObject::GetObjectText(
  LONG lFlags,
  BSTR *pstrObjectText
);

Parameters

lFlags
[in] Normally zero. If WBEM_FLAG_NO_FLAVORS is specified, qualifiers will be presented without propagation or flavor information. If WBEM_FLAG_NO_SEPARATOR is specified, the trailing semicolon after a class or instance declaration will be omitted from the MOF text. These flags may be combined.
pstrObjectText
[out] This must point to NULL on entry. This parameter receives from Windows Management a newly allocated BSTR that was initialized with SysAllocString. You must call SysFreeString on the pointer when the string is no longer required. This pointer points to a MOF syntax rendering of the object upon return from the call. Since this is an OUT parameter, the pointer must not point to a string that is valid before this method is called, because the pointer will not be deallocated.

Return Values

Value | Meaning
WBEM_E_FAILED | An unspecified error has occurred.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_S_NO_ERROR | The call succeeded.

Remarks

The following algorithm is used to reconstruct the text of the parameters of a method:

  1. Parameters are resequenced in the order of their id values.
  2. Parameters that are specified as [in] and [out] will be combined into a single parameter.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemQualifierSet


IWbemClassObject::SpawnDerivedClass

Use the IWbemClassObject::SpawnDerivedClass method to create a new derived class object from the current object. The current object must be a class definition that becomes the superclass of the spawned object. The returned object becomes a subclass of the current object.

HRESULT IWbemClassObject::SpawnDerivedClass(
  LONG lFlags,
  IWbemClassObject **ppNewClass
);

Parameters

lFlags
[in] Reserved. It must be zero.
ppNewClass
[out] Must not be NULL. This receives the pointer to the new class definition object. The caller must invoke IWbemClassObject::Release when the object is no longer required, typically after you have invoked IWbemServices::PutClass to write the class definition. On error, a new object is not returned, and ppNewClass is left unmodified.

Return Values

Value | Meaning
WBEM_E_FAILED | There has been a general failure.
WBEM_E_INVALID_OPERATION | An invalid operation was requested, such as spawning a class from an instance.
WBEM_E_INCOMPLETE_CLASS | The source class was not completely defined or registered with Windows Management, so a new derived class is not permitted.
WBEM_E_INVALID_PARAMETER | ppNewClass is NULL.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_S_NO_ERROR | The call succeeded.

Remarks

The new object returned in ppNewClass automatically becomes a subclass of the current object. This behavior cannot be overridden. There is no other method by which subclasses (derived classes) can be created.

You cannot create a derived class from a class that is local to your own client process. The superclass (base class) must be created and registered with Windows Management using IWbemServices::PutClass, and then retrieved using IWbemServices::GetObject before this method can be used to create a derived class.

To create a class hierarchy, you must create the initial class with IWbemServices::PutClass, retrieve it using IWbemServices::GetObject, and use the retrieved object to create the newly derived class. Then, this new derived class must be created using IWbemServices::PutClass. To create other derived classes, you must call IWbemServices::GetObject, then call IWbemClassObject::SpawnDerivedClass, and so on, in a cycle for each new derivation level. You must follow this procedure in order to prevent version errors and concurrency conflicts. See Class Creation to create a class with no parent.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemServices::GetObject, IWbemServices::PutClass


IWbemClassObject::SpawnInstance

Use the IWbemClassObject::SpawnInstance method to create a new instance of a class. The current object must be a class definition obtained from Windows Management using IWbemServices::GetObject, IWbemServices::CreateClassEnum, or IWbemServices::CreateClassEnumAsync Then, use this class definition to create new instances.

A call to IWbemServices::PutInstance is required to actually write the instance to Windows Management. If you intend to discard the object before calling IWbemServices::PutInstance, simply make a call to IWbemClassObject::Release.

Note that spawning an instance from an instance is supported but the returned instance will be empty.

HRESULT IWbemClassObject::SpawnInstance(
  LONG lFlags,
  IWbemClassObject **ppNewInstance
);

Parameters

lFlags
[in] Reserved. It must be zero.
ppNewInstance
[out] Must not be NULL. It receives a new instance of the class. The caller must invoke IWbemClassObject::Release when the pointer is no longer required. On error, a new object is not returned and the pointer is left unmodified.

Return Values

Value | Meaning
WBEM_E_INCOMPLETE_CLASS | The current object is not a valid class definition and cannot spawn new instances. Either it is incomplete, or it has not been registered with Windows Management using PutClass.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_S_NO_ERROR | The call succeeded.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemServices::GetObject, IWbemServices::PutInstance


IWbemClassObject::CompareTo

The IWbemClassObject::CompareTo method compares an object to another Windows Management object. Note that there are certain constraints in this comparison process.

HRESULT IWbemClassObject::CompareTo(
  LONG lFlags,
  IWbemClassObject *pCompareTo
);

Parameters

lFlags
[in] Specifies the object characteristics to consider in comparison to other object. It can be WBEM_COMPARISON_INCLUDE_ALL to consider all features, or any combination of these flags:
WBEM_FLAG_IGNORE_OBJECT_SOURCE
The source of the objects, namely the server and the namespace they came from, are ignored in comparison to other objects.
WBEM_FLAG_IGNORE_QUALIFIERS
All qualifiers (including Key and Dynamic) should be ignored in comparison.
WBEM_FLAG_IGNORE_DEFAULT_VALUES
Default values of properties should be ignored. This flag is only meaningful when comparing classes.
WBEM_FLAG_IGNORE_FLAVOR
Ignore qualifier flavors. This flag still takes qualifier values into account, but ignores flavor distinctions such as propagation rules and override restrictions (see Qualifier Flavors).
WBEM_FLAG_IGNORE_CASE
Compares string values in a case-insensitive manner. This applies both to strings and to qualifier values. Property and qualifier names are always compared in a case-insensitive manner whether this flag is specified or not.
WBEM_FLAG_IGNORE_CLASS
This flag instructs the system to assume that the objects being compared are instances of the same class. Consequently, this flag compares instance-related information only. Use this flag to optimize performance. If the objects are not of the same class, the results are undefined.
pCompareTo
[in] The object in comparison. This pointer must point to a valid IWbemClassObject instance. It cannot be NULL.

Return Values

Value | Meaning
WBEM_E_FAILED | An unspecified error has occurred.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_S_DIFFERENT | The objects are different.
WBEM_S_SAME | The objects are the same, subject to comparison flags.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

Qualifier Flavors


IWbemClassObject::GetPropertyOrigin

The IWbemClassObject::GetPropertyOrigin method retrieves the name of the class in which a particular property was introduced. For classes with deep inheritance hierarchies, it is often desirable to know which properties were declared in which classes. If the object does not inherit from a parent class, as in the case of a base class, for example, then the current class name is returned.

HRESULT IWbemClassObject::GetPropertyOrigin(
  LPCWSTR wszName,
  BSTR *pstrClassName
);

Parameters

wszName
[in] The property name for which the owning class name is desired. This must point to a valid LPCWSTR, which is treated as read-only.
pstrClassName
[out] A pointer to the address of a new BSTR that receives the parent class name. To prevent memory leaks in the client process, the caller must call SysFreeString when the name is no longer needed. This parameter must not point to a valid string before the method is called because this is an output parameter, and this pointer will not be deallocated after the call is complete.

Return Values

Value | Meaning
WBEM_E_FAILED | There has been a general failure.
WBEM_E_INVALID_PARAMTER | One or more parameters was not valid.
WBEM_E_NOT_FOUND | The specified property does not exist.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_S_NO_ERROR | The call succeeded.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemClassObject::InheritsFrom


IWbemClassObject::InheritsFrom

The IWbemClassObject::InheritsFrom method determines if the current class or instance derives from a specified parent class.

HRESULT IWbemClassObject::InheritsFrom(
  LPCWSTR wszAncestor
);

Parameters

wszAncestor
[in] Cannot be NULL. It contains the class name that is being tested. If the current object has this class for one of its ancestor classes, WBEM_S_NO_ERROR returns. This must point to a valid LPCWSTR, which is treated as read-only.

Return Values

Value | Meaning
WBEM_S_NO_ERROR | The current object inherits from the specified ancestor class.
WBEM_S_FALSE | The current object does not inherit from the specified ancestor class.
WBEM_E_INVALID_PARAMETER | The strAncestor parameter is NULL.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

GetPropertyOrigin


IWbemClassObject::GetMethod

Returns information about the requested CIM method. This call is only supported if the current object is a CIM class definition. CIM method information is not available from IWbemClassObject pointers which point to CIM instances.

HRESULT IWbemClassObject::GetMethod(
  LPCWSTR wszName,
  LONG lFlags,
  IWbemClassObject **ppInSignature,
  IWbemClassObject **ppOutSignature
);

Parameters

wszName
[in] The CIM method name. Must point to a valid LPCWSTR, which is treated as read-only.
lFlags
[in] Reserved. It must be zero.
ppInSignature
[out] Receives an IWbemClassObject pointer which describes the in-parameters to the method. This parameter will be ignored if set to NULL. Note that Windows Management can set the IWbemClassObject pointer to NULL if this method has no in-parameters. For more information, see the Remarks section, below.
ppOutSignature
[out] Receives an IWbemClassObject pointer which describes the out-parameters to the method. This parameter will be ignored if set to NULL.

Return Values

Value | Meaning
WBEM_S_NO_ERROR | The requested in- and out-parameter objects were returned.
WBEM_E_NOT_FOUND | The method did not exist.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the call.

Remarks

For a CIM method, the in- and out-parameters are described as properties in IWbemClassObjects.

For example, consider the following CIM method:
Class MyClass{
    [key] string KeyVal;
    sint32 PropVal;
sint32 ExampleMethod([in] sint32 Parm1, [in] uint32 Parm2,
  [out] string Parm3);
};

In this example, the class has a single method. When the user calls IWbemClassObject::GetMethod, the ppInSignature parameter will receive an IWbemClassObject, which contains two properties: Parm1 and Parm2. The ppOutSignature will contain two properties, Parm3 and ReturnValue.

After filling in the property values of the ppInSignature object, the caller can use the object to execute the method by calling IWbemServices::ExecMethod or IWbemServices::ExecMethodAsync.

Note The caller is responsible for calling IWbemClassObject::Release on the ppInSignature and ppOutSignature pointers when these objects are no longer needed.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemClassObject::PutMethod


IWbemClassObject::PutMethod

Use this to create a CIM method. This call is only supported if the current object is a CIM class definition. CIM method manipulation is not available from IWbemClassObject pointers which point to CIM instances.

The user may not create methods with names that begin or end with an underscore. This is reserved for system classes and properties.

HRESULT IWbemClassObject::PutMethod(
  LPCWSTR wszName,
  LONG lFlags,
  IWbemClassObject *pInSignature,
  IWbemClassObject *pOutSignature
);

Parameters

wszName
[in] The method name which is being created.
lFlags
[in] Reserved. It must be zero.
pInSignature
[in] Points to an IWbemClassObject containing the in-parameters for the method. This parameter will be ignored if set to NULL.
pOutSignature
[in] Points to an IWbemClassObject containing the out-parameters for the object. This parameter will be ignored if set to NULL.

Return Values

Value | Meaning
WBEM_S_NO_ERROR | The call was successful.
WBEM_E_INVALID_DUPLICATE_PARAMETER | The [in, out] method parameter, specified in both pInSignature and pOutSignature parameter objects, have different qualifiers
WBEM_E_INVALID_PARAMETER | One or more parameters was invalid.
WBEM_E_MISSING_PARAMETER_ID | Any method parameter (in/out) missing the specification of the ID qualifier
WBEM_E_NONCONSECUTIVE_PARAMETER_IDS | The ID series, assigned to the method paramters, is not consecutive, or doesn't start at zero.
WBEM_E_PROPAGATED_METHOD | An attempt was made to reuse an existing method name from a superclass, and the signatures did not match.

Remarks

For a CIM method, the in- and out-parameters are described as properties in IWbemClassObjects.

For example, consider the following CIM method:

Class MyClass{
    [key] string KeyVal;
    sint32 PropVal;
sint32 ExampleMethod([in] sint32 Parm1, [in] uint32 Parm2,
  [out] string Parm3);
};

In this example, the class has a single method. To create the method programmatically, the user calls IWbemClassObject::PutMethod with the ppInSignature parameter pointing to an IWbemClassObject, which contains two properties: Parm1 and Parm2. The ppOutSignature points to an object containing a single property containing Parm3.

The ReturnValue property of the object pointed to by ppOutSignature determines the method return type. If ppOutSignature is set to NULL, the return type is assumed to be VOID.

Note The caller is responsible for calling IWbemClassObject::Release on the ppInSignature and ppOutSignature pointers when these objects are no longer needed.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemClassObject::GetMethod

Programmatic Access to Methods


IWbemClassObject::DeleteMethod

Use this to delete a CIM method. This call is supported only if the current object is a CIM class definition. CIM method manipulation is not available from IWbemClassObject pointers which point to CIM instances.

HRESULT IWbemClassObject::DeleteMethod(
  LPCWSTR wszName
);

Parameters

wszName
[in] The method name to be removed from the class definition.

Return Values

Value | Meaning
WBEM_S_NO_ERROR | The method was deleted from the CIM class definition.
WBEM_E_NOT_FOUND | The method did not exist.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the call.

Remarks

You may not delete methods inherited from superclasses.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemClassObject::GetMethod, IWbemClassObject::PutMethod


IWbemClassObject::BeginMethodEnumeration

Use this call to begin an enumeration of the methods available for the object.

This call is only supported if the current object is a CIM class definition. CIM method manipulation is not available from IWbemClassObject pointers which point to CIM instances. The order in which methods are enumerated is guaranteed to be invariant for a given instance of IWbemClassObject.

HRESULT IWbemClassObject::BeginMethodEnumeration(
  LONG lEnumFlags
);

Parameters

lEnumFlags
[in] Reserved. It must be zero.

Return Values

Value | Meaning
WBEM_E_INVALID_PARAMETER | A non-zero flag value was used.
WBEM_S_NO_ERROR | The call succeeded.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemClassObject::NextMethod


IWbemClassObject::NextMethod

This is used to retrieve the next method in a method enumeration sequence started with IWbemClassObject::BeginMethodEnumeration.

This call is only supported if the current object is a CIM class definition. CIM method manipulation is not available from IWbemClassObject pointers which point to CIM instances.

HRESULT IWbemClassObject::NextMethod(
  LONG lFlags,
  BSTR *pName,
  IWbemClassObject **ppInSignature,
  IWbemClassObject **ppOutSignature
);

Parameters

lFlags
[in] Reserved. It must be zero.
pName
[out, OPTIONAL] Should point to NULL prior to the call. Receives a BSTR containing the method name. The caller must release the string using SysFreeString when it is no longer required.
ppInSignature
[out, OPTIONAL] Receives a pointer to an IWbemClassObject containing the in-parameters for the method.
ppOutSignature
[out, OPTIONAL] Receives a pointer to an IWbemClassObject containing the out-parameters for the method.

Return Values

Value | Meaning
WBEM_E_UNEXPECTED | An internal error occurred.
WBEM_S_NO_ERROR | The call succeeded.
WBEM_S_NO_MORE_DATA | Returned when the enumeration sequence is complete.

Remarks

The caller begins the enumeration sequence using IWbemClassObject::BeginMethodEnumeration, and then calls IWbemClassObject::NextMethod until WBEM_S_NO_MORE_DATA returns. The caller optionally finishes the sequence with IWbemClassObject::EndMethodEnumeration. The caller may terminate the enumeration early by calling IWbemClassObject::EndMethodEnumeration at any time.

Note The caller is responsible for calling IWbemClassObject::Release on the ppInSignature and ppOutSignature pointers when these objects are no longer needed.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemClassObject::EndMethodEnumeration

This is used to terminate a method enumeration sequence started with IWbemClassObject::BeginMethodEnumeration.

This call is only supported if the current object is a CIM class definition. CIM method manipulation is not available from IWbemClassObject pointers, which point to CIM instances.

HRESULT IWbemClassObject::EndMethodEnumeration( );

Parameters

None.

Return Values

Value | Meaning
WBEM_E_UNEXPECTED | An internal error occurred.
WBEM_S_NO_ERROR | The call succeeded.

Remarks

The caller begins the enumeration sequence using IWbemClassObject::BeginMethodEnumeration, and then calls IWbemClassObject::NextMethod until WBEM_S_NO_MORE_DATA returns. The caller optionally finishes the sequence with IWbemClassObject::EndMethodEnumeration. The caller may terminate the enumeration early by calling IWbemClassObject::EndMethodEnumeration at any time.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemClassObject::GetMethodQualifierSet

The GetMethodQualifierSet is used to retrieve the qualifier set for a particular method.

This call is supported only if the current object is a CIM class definition. CIM method manipulation is not available from IWbemClassObject pointers, which point to CIM instances.

HRESULT IWbemClassObject::GetMethodQuailifierSet(
  LPCWSTR wszMethod,
  IWbemQualifierSet **ppQualSet
);

Parameters

wszMethod
[in] Must point to a valid LPCWSTR containing the method name.
ppQualSet
[out] Receives the interface pointer that allows access to the qualifiers for the method. The returned object has a positive reference count upon return from the call. The caller must call IWbemQualifierSet::Release when the object is no longer needed. This parameter cannot be NULL. On error, a new object is not returned, and the pointer is set to point to NULL.

Return Values

Value | Meaning
WBEM_E_NOT_FOUND | The method did not exist.
WBEM_E_INVALID_PARAMETER | A parameter is NULL.
WBEM_S_NO_ERROR | The call succeeded.

Remarks

Since each method may have its own qualifiers, use this call to retrieve the IWbemQualifierSet pointer, which allows the caller to add, edit, or delete such qualifiers.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemClassObject::GetMethodOrigin

This is used to determine for which class a method was declared.

This call is only supported if the current object is a CIM class definition. CIM method manipulation is not available from IWbemClassObject pointers which point to CIM instances.

HRESULT IWbemClassObject::GetMethodOrigin(
  LPCWSTR wszMethodName,
  BSTR *pstrClassName
);

Parameters

wszMethodName
[in] The name of the method for the object whose owning class is being requested.
pstrClassName
[out] Receives the name of the class which owns the method. The user must call SysFreeString on the returned BSTR when it is no longer required.

Return Values

Value | Meaning
WBEM_E_NOT_FOUND | The method did not exist.
WBEM_E_INVALID_PARAMETER | One or more parameters was not valid.
WBEM_S_NO_ERROR | The call succeeded.

Remarks

Since methods are inherited from class to class, it is often desirable to determine the owning class for a given method.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemConfigureRefresher

[This is preliminary documentation and subject to change.]

The IWbemConfigureRefresher interface is used by client code to add enumerators, objects, and nested refreshers into a refresher. By providing a native implementation of this interface, WMI allows client code to easily configure refreshers. You can access the IWbemConfigureRefresher interface by calling QueryInterface on IID_IWbemConfigureRefresher on the object returned by calling CoCreateInstance on CLSID_WbemRefresher.

Note Do not, under any circumstances, use providers or client applications to implement this interface. The implementation provided by Windows Management is the only one that is supported.

IWbemConfigureRefresher Methods | Description
AddEnum | Adds an enumerator to a refresher.
AddObjectByPath | Adds an object to a refresher based on a relative path.
AddObjectByTemplate | Adds an object to a refresher by specifying an IWbemClassObject instance template.
AddRefresher | Adds a refresher to a refresher. You can use this method to create a single refresher that contains more than one refresher, which can be updated using a single call to the Refresh method.
Remove | Removes an object, enumerator, or nested refresher from a refresher.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemConfigureRefresher::AddEnum

[This is preliminary documentation and subject to change.]

The AddEnum method adds an enumerator to the requested refresher.

HRESULT IWbemConfigureRefresher::AddEnum(
  IWbemServices *pNamespace,
  LPCWSTR wszClassName,
  long lFlags,
  IWbemContext *pCtx,
  IWbemHiPerfEnum **ppEnum,
  long *plId
);

Parameters

pNamespace
[in] An IWbemServices pointer back into Windows Management, which can service any request made by the provider. If the method must call back into Windows Management during its execution, the provider should call AddRef with the pNamespace pointer.
wszClassName
[in, string] Constant, null-terminated string of 16-bit Unicode characters that contains the name of the class that is enumerated.
lFlags
[in] A bitmask of flags that modify the behavior of this method. If this parameter is set to WBEM_FLAG_USE_AMENDED_QUALIFIERS, the returned instances will contain localized qualifiers if they are available.
pCtx
[in] Typically NULL; otherwise, this is a pointer to an IWbemContext object that is required by one or more dynamic class providers.

The values in the context object must be specified in the specific provider documentation. For more information about this parameter, see Making Calls to WMI..

ppEnum
[out] Pointer that holds the reference to a IWbemHiPerfEnum object, which will contain the enumeration. The client must call Release on this pointer when it is no longer required.
plId
[out, OPTIONAL] Pointer to an integer returned by the provider that uniquely identifies the refreshable enumeration.

Return Values

If the AddEnum method is successful, it returns WBEM_S_NO_ERROR; otherwise, this method returns an HRESULT with one of the following values.

Value | Meaning
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_INVALID_CLASS | The specified class was invalid.
WBEM_E_ACCESS_DENIED | The current user does not have permission to perform this operation.
WBEM_E_INVALID_OPERATION | The requested instance is not supplied by a high-performance provider.
WBEM_E_REFRESHER_BUSY | The refresher is busy with another operation.

Remarks

The supplied class must specify a valid class, which is provided by a HiPerf Provider. All instances of the returned enumerator can be queried after calls. On each call to refresh, the number of instances in the enumerator can vary. Only instances of the specified class name will be returned; subclasses of the specified class will not be enumerated because deep enumeration is not supported. The returned enumerator must not be touched by the client while a Refresh operation is in process. The returned ID can be used by the Remove function to remove the object. Note that it is not necessary for the user to explicitly remove added enumerators. However, the client must call Release on the returned enumerator when it is no longer required.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemConfigureRefresher


IWbemConfigureRefresher::AddObjectByPath

[This is preliminary documentation and subject to change.]

The AddObjectByPath method adds an object to a refresher by specifying an object path.

HRESULT IWbemConfigureRefresher::AddObjectByPath(
  IWbemServices *pNamespace,
  LPCWSTR wszPath,
  long lFlags,
  IWbemContext *pCtx,
  IWbemClassObject **ppRefreshable,
  long *plId
);

Parameters

pNamespace
[in] An IWbemServices pointer back into Windows Management, which can service any request made by the provider. The provider should AddRef this pointer if it is going to need to call back into Windows Management during its execution.
wszPath
[in, string] Constant, null-terminated string of 16-bit Unicode characters that contains the object path ofthe object you add to the refresher.
lFlags
[in] A bitmask of flags that modify the behavior of this method. If this parameter is set to WBEM_FLAG_USE_AMENDED_QUALIFIERS, the returned instance will contain localized qualifiers if available.
pCtx
[in] Typically NULL; otherwise, a pointer to an IWbemContext object that is required by one or more dynamic class providers.

The values in the context object must be specified in the specific provider documentation. For more information about this parameter, see Making Calls to WMI..

ppRefreshable
[out] Pointer to hold the reference to a IWbemClassObject object, which will contain the refreshable instance object. The client must call Release on the returned object when it is no longer required.
plId
[out, OPTIONAL] Pointer to an integer returned by the provider that uniquely identifies the refreshable object.

Return Values

If the AddObjectByPath method is successful, it returns WBEM_S_NO_ERROR; otherwise, this method returns an HRESULT with one of the following values.

Value | Meaning
WBEM_E_INVALID_PARAMETER | A parameter was invalid.
WBEM_E_NOT_FOUND | The requested instance could not be found.
WBEM_E_ACCESS_DENIED | The current user does not have permission to retrieve the specified instance.
WBEM_E_INVALID_OPERATION | The requested instance is not supplied by a HiPerf provider.
WBEM_E_REFRESHER_BUSY | The refresher is busy with another operation.

Remarks

The supplied path must specify a valid object, which is provided by a HiPerf Provider. The returned object must not be touched by the client while a refresh operation is in process. The returned identifier can be used by the Remove function to remove the object.

Note It is not necessary for the user to explicitly remove added objects. The client must call Release on the returned object when it is no longer required.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemConfigureRefresher


IWbemConfigureRefresher::AddObjectByTemplate

[This is preliminary documentation and subject to change.]

With the AddObjectByTemplate method, you can add an object you want refreshed to a refresher by specifying an IWbemClassObject instance template. Use this method when it is difficult to construct an object path for an object you want to add to a refresher.

Note The key properties of the instance object must be filled out before you can call the AddObjectByTemplate method.

HRESULT IWbemConfigureRefresher::AddObjectByTemplate(
  IWbemServices *pNamespace,
  IWbemClassObject *pTemplate,
  long lFlags,
  IWbemContext *pCtx,
  IWbemClassObject **ppRefreshable,
  long *plId
);

Parameters

pNamespace
An IWbemServices pointer back into Windows Management, which can service any request made by the provider. The provider should AddRef this pointer if it is going to need to call back into Windows Management during its execution.
pTemplate
[in] Pointer to a IWbemClassObject object that contains the instance template.
lFlags
[in] A bitmask of flags that modify the behavior of this method. If this parameter is set to WBEM_FLAG_USE_AMENDED_QUALIFIERS, the returned instance will contain localized qualifiers if available.
pCtx
[in] Typically NULL; otherwise, a pointer to an IWbemContext object that is required by one or more dynamic class providers.

The values in the context object must be specified in the specific provider documentation. For more information about this parameter, see Making Calls to WMI..

ppRefreshable
[out] Pointer to hold the reference to a IWbemClassObject object, which will contain the refreshable instance object. The client must call Release on the returned object when it is no longer required.
plid
[out, OPTIONAL] Pointer to an integer returned by the provider that uniquely identifies this refreshable object.

Return Values

If the AddObjectByTemplate method is successful, it returns WBEM_S_NO_ERROR; otherwise, this method returns an HRESULT with one of the following values.

Value | Meaning
WBEM_E_INVALID_PARAMETER | A parameter was invalid.
WBEM_E_NOT_FOUND | The requested instance could not be found.
WBEM_E_ACCESS_DENIED | The current user does not have permission to retrieve the specified instance.
WBEM_E_INVALID_OPERATION | The requested instance is not supplied by a high-performance provider.
WBEM_E_REFRESHER_BUSY | The refresher is busy with another operation.

Remarks

The supplied instance must specify a valid object, which is provided by a HiPerf Provider. The returned object must not be modified by the client while a refresh operation is in process. The returned identifier can be used by the Remove function to remove the object.

It is not necessary for the user to explicitly remove added objects. The client must call Release on the returned object when it is no longer required.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemConfigureRefresher


IWbemConfigureRefresher::AddRefresher

[This is preliminary documentation and subject to change.]

The AddRefresher method adds a refresher to a refresher. The newly added refresher is called a "child refresher" or "nested refresher". You can use this method to create a single refresher containing more than one refresher that can be updated using a single call to the Refresh method.

HRESULT IWbemConfigureRefresher::AddRefresher(
  IWbemRefresher *pRefresher,
  long lFlags,
  long *plId
);

Parameters

pRefresher
[in] Pointer to a IWbemRefresher object to nest in this refresher.
lFlags
Reserved; the value must be zero.
plId
[out, OPTIONAL] Pointer to an integer returned by the provider that uniquely identifies the refreshable object.

Return Values

If the AddRefresher method is successful, it returns WBEM_S_NO_ERROR; otherwise, this method returns an HRESULT with one of the following values.

Value | Meaning
WBEM_E_INVALID_PARAMETER | A parameter was invalid.
WBEM_E_REFRESHER_BUSY | The refresher is busy with another operation.

Remarks

Users should not add recursively nested refreshers. The returned identifier can be used by the Remove function to remove the refresher. Although it is not necessary for the client to explicitly remove added refreshers, the client must call Release on the refreshers when they are no longer required.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemConfigureRefresher


IWbemConfigureRefresher::Remove

[This is preliminary documentation and subject to change.]

The Remove method is used to remove an object, enumerator, or nested refresher from a refresher.

HRESULT IWbemConfigureRefresher::Remove(
  long lId,
  long lFlags
);

Parameters

lId
[in] Integer that uniquely identifies the object you want to remove. You obtain this identifier when you first add an object to the refresher by calling IWbemConfigureRefresher::AddObjectByPath, IWbemConfigureRefresher::AddObjectByTemplate, IWbemConfigureRefresher::AddEnum, or IWbemConfigureRefresher::AddRefresher.
lFlags
[in] A bitmask of flags that modify the behavior of the Remove method. If this parameter is set to. WBEM_FLAG_REFRESH_AUTO_RECONNECT, the refresher will attempt to automatically reconnect to a remote provider if the connection is broken. This is default behavior for this method. Specify WBEM_FLAG_REFRESH_NO_AUTO_RECONNECT if you do not want the refresher to attempt to reconnect to a remote provider.

Return Values

If the Remove method is successful, it returns WBEM_S_NO_ERROR; otherwise, this method returns an HRESULT with one of the following values.

Value | Meaning
WBEM_S_FALSE | The specified ID could not be removed.
WBEM_E_REFRESHER_BUSY | The refresher is busy with another operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemConfigureRefresher


IWbemContext

The IWbemContext interface communicates additional information to providers when submitting IWbemServices calls to Windows Management. All primary calls in IWbemServices take an optional parameter pointing to an object of this type.

In many cases, dynamic providers need more information than the information that is specified in the normal parameters of an IWbemServices method. For example, to manipulate any CIM schema objects it provides, a provider may need to know a Simple Network Management Protocol (SNMP) Community name, or an Structured Query Language (SQL) database and table name. A client can add this information to an IWbemContext object, and send the IWbemContext object along with the call as one of the parameters.

Note It is very important that providers make as little use of this mechanism as possible. It is preferred that they never require it. If a provider requires a large amount of highly specific context information to respond to a request, then all clients must be coded to provide this information, thus breaking the uniform access model that is the basis of WMI. Nevertheless, in some cases it cannot be avoided. Therefore, this mechanism is provided to make it possible to access such providers. Developers of such providers should provide adequate documentation so that developers of client software can successfully manipulate such CIM objects.

Providers that support the use of IWbemContext to allow clients to specify additional information in a request should restrict the types of values they support to the following:

  • VT_I4
  • VT_R8
  • VT_BOOL
  • VT_BSTR
  • VT_UNKNOWN
  • Any of the above combined with VT_ARRAY

An IWbemContext object, which is created using CoCreateInstanceEx, is a simple container of named values. You can access these methods to fill in any context information required by a dynamic provider. After the call to one of the IWbemServices methods, the IWbemContext object can be reused for another call, or it can be deallocated using Release and another object created for other calls to IWbemServices methods

The information contained in an IWbemContext object is entirely determined by the underlying provider. Windows Management makes no use of the information, but simply forwards it to the provider. Providers must publish the context information they require for these service requests.

It is expected that the client application calls CoCreateInstanceEx to create a single context object. Then, it calls SetValue one or more times to set up context values for the provider. Finally, it submits the object to one of the IWbemServices methods, which immediately calls Release on the context object after the call has returned. The other methods are for use primarily by providers that receive the context object and have to extract information.

IWbemContext Methods | Description
BeginEnumeration | Begins an enumeration of all context values in the IWbemContext object.
Clone | Makes a complete copy of the current IWbemContext object.
DeleteAll | Removes all context values, making the IWbemContext object empty.
DeleteValue | Removes the specified context value.
EndEnumeration | Ends an enumeration begun with BeginEnumeration and Next.
GetNames | Retrieves the names of all of the context values available.
GetValue | Retrieves the specified context value by name.
Next | Retrieves the next value in an enumeration of all context values beginning with BeginEnumeration.
SetValue | Sets a specific named context value.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemContext::Clone

The IWbemContext::Clone method makes a logical copy of the current IWbemContext object. This method can be useful when many calls must be made which have largely identical IWbemContext objects.

HRESULT Clone(
  IWbemContext **ppNewCopy
);

Parameters

ppNewCopy
[out] Must point to NULL on entry. It receives a pointer to the new object containing the clone of the current object. The returned pointer has a positive reference count. The caller must call IWbemServices::Release on this pointer when it is no longer needed. On error, this pointer is left unmodified, and a new object is not returned.

Return Values

Value | Meaning
WBEM_E_FAILED | There has been a general failure.
WBEM_E_INVALID_PARAMETER | NULL was specified as a parameter, which is not legal.
WBEM_E_OUT_OF_MEMORY | There is not enough memory to clone the object.
WBEM_S_NO_ERROR | The call succeeded.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemContext::GetNames

The IWbemContext::GetNames method returns a SAFEARRAY of all of the names of the named context values. After all the names are known, GetValue can be called on each name to retrieve the value. This technique is a way of accessing the context values that is different from calling the BeginEnumeration, Next, and EndEnumeration methods.

HRESULT GetNames(
  LONG lFlags,
  SAFEARRAY (BSTR) **pNames
);

Parameters

lFlags
[in] Reserved. It must be zero.
pNames
[out] This parameter cannot be NULL, but on entry it must point to NULL. If no error is returned, on exit pstrNames receives a pointer to a new SAFEARRAY of type VT_BSTR containing all the context value names. The caller must call SafeArrayDestroy on the returned pointer when the array is no longer required. If an error code is returned, the pointer is left unmodified.

Note If there are no named values in the object, the call succeeds and returns an array of length zero.

Return Values

Value | Meaning
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_S_NO_ERROR | The call succeeded.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemContext::GetValue, IWbemContext::BeginEnumeration

For an example of using SAFEARRAYs of BSTRs, see Displaying Instance Properties.


IWbemContext::BeginEnumeration

The IWbemContext::BeginEnumeration method resets the enumeration of all the context values in the object. This method must be called before the first call to IWbemContext::Next to enumerate all of the context values in the object. The order in which context values are enumerated is guaranteed to be invariant for a given instance of IWbemContext.

HRESULT BeginEnumeration(
  LONG lFlags
);

Parameters

lFlags
[in] Reserved. It must be zero.

Return Values

Value | Meaning
WBEM_E_INVALID_PARAMETER | The lFlags parameter was not valid.
WBEM_S_NO_ERROR | The call succeeded.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to begin an enumeration.
WBEM_E_UNEXPECTED | A second call was made to IWbemContext::BeginEnumeration without an intervening call to IWbemContext::EndEnumeration.
WBEM_E_FAILED | There has been a general failure.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemContext::Next, IWbemContext::EndEnumeration


IWbemContext::Next

The IWbemContext::Next method retrieves the next value in an enumeration of all context values beginning with BeginEnumeration.

HRESULT Next(
  LONG lFlags,
  BSTR *pstrName,
  VARIANT *pValue
);

Parameters

lFlags
[in] Reserved. It must be zero.
pstrName
[out] This parameter cannot be NULL. The pointer must not point to an active BSTR on entry, and ideally it should be set to point to NULL. If no error code is returned, it is set to point to a newly allocated BSTR containing the context value name.

The caller must call SysFreeString on the returned string when it is no longer required. If WBEM_S_NO_MORE_DATA returns, pstrName is set to point to NULL, in which case SysFreeString should not be called.

Note If pstrName points to a valid BSTR on entry, this BSTR is not freed, and a memory leak occurs.

pValue
[out] This parameter cannot be NULL, and it must point to an empty or uninitialized VARIANT. If no error is returned, the VARIANT is initialized using VariantInit, and then set to contain the context value. The caller must call VariantClear on this pointer when the value is no longer required. If an error code is returned, the VARIANT pointed to by pValue is left unmodified.

If WBEM_S_NO_MORE_DATA returns, this parameter is set to point to a VARIANT of type VT_NULL.

It is possible that an entire IWbemClassObject may be returned inside the VARIANT. If that is the case, then VT_UNKNOWN is the VARIANT type. The caller can take the IUnknown pointer and execute QueryInterface to obtain the IWbemClassObject pointer.

Note At the end of the enumeration, WBEM_S_NO_MORE_DATA returns. The returned VARIANT is of type VT_NULL, and the returned pstrName is NULL.

Return Values

Value | Meaning
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_UNEXPECTED | Caller did not call IWbemContext::BeginEnumeration.
WBEM_S_NO_ERROR | The call succeeded.
WBEM_S_NO_MORE_DATA | No more properties are left in the enumeration.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the call.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemContext::BeginEnumeration, IWbemContext::EndEnumeration


IWbemContext::EndEnumeration

The IWbemContext::EndEnumeration method ends an enumeration sequence that begins with IWbemContext::BeginEnumeration. This call is not required, but it releases as early as possible any system resources associated with the enumeration.

HRESULT EndEnumeration( );

Parameters

None.

Return Values

Value | Meaning
WBEM_S_NO_ERROR | The call succeeded.
WBEM_E_UNEXPECTED | This call was made without a corresponding call to IWbemContext::BeginEnumeration.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemContext::BeginEnumeration, IWbemContext::Next


IWbemContext::SetValue

The IWbemContext::SetValue method creates or overwrites a named context value.

HRESULT SetValue(
  LPCWSTR strName,
  LONG lFlags,
  VARIANT *pValue
);

Parameters

strName
[in] Cannot be NULL. It is a read-only pointer to a valid BSTR indicating the context value name.
lFlags
[in] Reserved. It must be zero.
pValue
[in] Must point to a valid VARIANT, which is treated as read-only. The value in the VARIANT becomes the named context value. An entire IWbemClassObject can be stored as well as a simple value by enclosing it in a VARIANT using the VT_UNKNOWN type. The caller must execute QueryInterface on the IWbemClassObject, asking for IID_IUnknown, and use the returned pointer in the VARIANT.

If pValue is to contain an embedded IWbemClassObject, the caller must call IWbemClassObject::QueryInterface for IID_IUNKNOWN and place the resulting pointer in the VARIANT using a type of VT_UNKNOWN. The original embedded object is copied during the Put operation, and so cannot be modified by the operation.

Return Values

Value | Meaning
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_FAILED | There has been a general failure.
WBEM_S_NO_ERROR | The call succeeded.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemContext::GetValue


IWbemContext::GetValue

The IWbemContext::GetValue method is used to retrieve a specific named context value by name.

HRESULT GetValue(
  LPCWSTR strName,
  LONG lFlags,
  VARIANT *pValue
);

Parameters

strName
[in] The name for which the value is to be retrieved. This must point to a valid BSTR. The pointer is treated as read-only.
lFlags
[in] Reserved. It must be zero.
pValue
[out] This parameter cannot be NULL and must point to an uninitialized VARIANT. If no error is returned, the VARIANT is initialized using VariantInit, and then set to contain the context value. The caller must call VariantClear on this pointer when the value is no longer required. If an error code is returned, the VARIANT pointed to by pValue is left unmodified.

It is possible that an entire IWbemClassObject can be returned inside the VARIANT. If that is the case, then VT_UNKNOWN is the VARIANT type. The caller can take the IUnknown pointer and execute QueryInterface to obtain the IWbemClassObject pointer.

Return Values

Value | Meaning
WBEM_E_NOT_FOUND | The requested value was not found.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_S_NO_ERROR | The call succeeded.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemContext::SetValue


IWbemContext::DeleteValue

The IWbemContext::DeleteValue method deletes a named context value created by IWbemContext::SetValue.

HRESULT DeleteValue(
  LPCWSTR strName,
  LONG lFlags
);

Parameters

strName
[in] A pointer to a valid BSTR containing the named context value to delete. The pointer is treated as read-only.
lFlags
[in] Reserved. It must be zero.

Return Values

Value | Meaning
WBEM_E_FAILED | There has been a general failure.
WBEM_E_INVALID_PARAMETER | An invalid Name or lFlags value was specified.
WBEM_E_NOT_FOUND | The specified named context value does not exist.
WBEM_S_NO_ERROR | The call succeeded.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemContext::SetValue, IWbemContext::GetValue


IWbemContext::DeleteAll

The IWbemContext::DeleteAll method removes all named context values from the current object, thus emptying the object.

HRESULT DeleteAll( );

Parameters

None.

Return Values

Value | Meaning
WBEM_E_FAILED | There has been a general failure.
WBEM_S_NO_ERROR | The call succeeded.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemContext::DeleteValue


IWbemEventConsumerProvider

Use the IWbemEventConsumerProvider interface to initiate communication with a consumer provider. If you are implementing a permanent event consumer, you also need to implement this interface so that Windows Management can deliver events to the consumers.

IWbemEventConsumer Provider Methods | Description
FindConsumer | Called by Windows Management to retrieve an IWbemUnboundObjectSink for a particular logical consumer.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemprov.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemEventConsumerProvider::FindConsumer

When Windows Management needs to deliver events to a particular logical consumer, it will call this method so that the consumer provider can locate the associated consumer event sink.

HRESULT IWbemEventConsumerProvider::FindConsumer(
  IWbemClassObject *pLogicalConsumer,
  IWbemUnboundObjectSink **ppConsumer
);

Parameters

pLogicalConsumer
[in] A pointer to the logical consumer object to which the event objects are to be delivered.
ppConsumer
[out] Returns an event object sink to Windows Management. Windows Management will call AddRef for this pointer and deliver the events associated with the logical consumer to this sink. Eventually, after a suitable time out, Windows Management will call Release for the pointer.

Return Values

Value | Meaning
WBEM_E_FAILED | The provider failed internally, and it cannot accept future requests.
WBEM_E_INVALID_PARAMETER | One or more parameters was not valid.
WBEM_E_NOT_FOUND | The provider was not able to locate or correlate the logical consumer internally, and it failed to return a sink.
WBEM_S_NO_ERROR | The provider succeeded and returned a sink to Windows Management.

Remarks

Windows Management delivers events in the form of IWbemClassObject to logical consumers registered within the schema. This interface is implemented by an event consumer provider to provide an event sink to Windows Management whenever events need to be delivered to the logical consumer.

Windows Management knows the logical consumer object and has the event objects ready for delivery. It then calls FindConsumer. The consumer provider must create an event sink object (a pointer to IWbemUnboundObjectSink), and return the pointer to Windows Management so that the events can be delivered.

Using this technique, a single event consumer provider can handle delivery of events to many different logical consumers by returning different IWbemUnboundObjectSink pointers for each.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemprov.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

Temporary Event Consumers, Permanent Event Consumers


IWbemEventProvider

Use the IWbemEventProvider interface to initiate communication with an event provider. Windows Management calls the provider's implementation of this interface when a consumer has indicated interest in receiving events generated by the provider.

IWbemEventProvider Methods | Description
ProvideEvents | Called by WMI to command the provider to start delivering its events to WMI.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemprov.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemEventProvider::ProvideEvents

Windows Management calls this method to signal an event provider to begin delivery of its events.

HRESULT IWbemEventProvider::ProvideEvents(
  IWbemObjectSink *pSink,
  long lFlags
);

Parameters

pSink
[in] A pointer to the object sink to which the provider will deliver its events.
lFlags
[in] Reserved. It must be zero.

Return Values

Value | Meaning
WBEM_E_FAILED | The provider failed internally, and it cannot accept future requests.
WBEM_S_NO_ERROR | The provider received the sink, and it will begin delivery of events.

Remarks

Windows Management calls this method to activate the provider. Windows Management gives an IWbemObjectSink pointer to the event provider. The provider must call the AddRef method using this pointer to increment the reference count, and then return from the call.

Typically, the provider will create an independent thread, and deliver the events as they occur to the provided sink interface.

The provider is not permitted to block this call for more than a few seconds, but it must return as quickly as possible to Windows Management.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemprov.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemEventProviderQuerySink

The IWbemEventProviderQuerySink interface is optionally implemented by event providers who want to know what kinds of event query filters are currently active in order to optimize performance.

IWbemEventProviderQuerySink Methods | Description
CancelQuery | Called whenever a consumer query is canceled or unregistered.
NewQuery | Called whenever a new consumer query is registered with WMI.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemprov.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemEventProviderQuerySink::NewQuery

Call this method whenever a logical event consumer registers a relevant event query filter with Windows Management.

HRESULT IWbemEventProviderQuerySink::NewQuery(
  unsigned long dwId,
  WBEM_WSTR wszQueryLanguage,
  WBEM_WSTR wszQuery
);

Parameters

dwId
[in] A Windows Management-generated ID for the query. The provider can track this so that during a later cancellation it will know which query was canceled.
wszQueryLanguage
[in] The language of the following query filter. For this version of WMI, it will always be "WQL."
wszQuery
[in] The text of the event query filter, which was registered by a logical consumer.

Return Values

Value | Meaning
WBEM_E_FAILED | The provider failed internally, and it cannot accept future requests.
WBEM_S_NO_ERROR | The provider received the sink, and it will begin delivery of events.

Remarks

If a consumer registers an event filter query with Windows Management and the query contains references to events provided by the current event provider, Windows Management can notify the event provider of the query.

If the provider implements the IWbemEventProviderQuerySink interface, Windows Management will provide a copy of the query text to the provider. The provider should parse the query, and determine if it can perform any internal optimization.

Windows Management does not expect a provider to alter its behavior in any way. Rather, this is an advisory call to assist the provider with internal optimization.

For example, if the provider is capable of providing many hundreds of events, but the required overhead for providing all of them is very great, the provider can achieve substantial savings if it knows that most of these events are not required by the current set of event consumers. If the provider implements IWbemEventProviderQuerySink, it will know about the current set of events requested by all consumers. It may be able to avoid setting up the mechanisms for delivering most of the event types that it supports until such time as consumers actually begin requesting such events.

For each new consumer query filter, a separate call to this method with a unique dwId will be made. Note that Windows Management reserves the right to call NewQuery more than once for the same dwId, for example, if there is a schema change elsewhere in the system. For this version of WMI, the query language is always "WQL".

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemprov.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemEventProviderQuerySink::CancelQuery


IWbemEventProviderQuerySink::CancelQuery

Call this method whenever a logical event consumer cancels a relevant event query filter with Windows Management.

HRESULT IWbemEventProviderQuerySink::CancelQuery(
  unsigned long dwId
);

Parameters

dwId
[in] The ID of the query which was canceled. This ID was originally delivered to the provider by the NewQuery method of this interface.

Return Values

Value | Meaning
WBEM_S_NO_ERROR | The provider should return this result.

Remarks

Whenever a consumer registers a new event query filter, Windows Management calls the IWbemEventProviderQuerySink::NewQuery method with the query ID. Later on, when that query is unregistered, this method is called indicating which query is no longer outstanding.

Providers use this to help optimize the generation of events internally.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemprov.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemEventProviderQuerySink::NewQuery


IWbemEventProviderSecurity Interface

The IWbemEventProviderSecurity interface is optionally implemented by event providers who want to restrict consumer access to their event.

Methods

Method | Description
AccessCheck | Checks a consumer's access permission when the consumer attempts to subscribe to an event.

Remarks

This method is automatically called by Windows Management whenever a new consumer attempts to subscribe to an event where the event provider has implemented IWbemEventProviderSecurity. If the consumer has access permission for the event the consumer is subscribed to the event, otherwise the subscription is denied.


IWbemEventProviderSecurity::AccessCheck

The AccessCheck method checks the access permissions when a consumer attempts to subscribe to the event specified in wszQuery. The consumer is permitted to subscribe to the event if it has access permission for the event, otherwise subscription is prevented.

Definition

HRESULT IWbemEventProviderSecurity::AccessCheck(
  WBEM_CWSTR wszQueryLanguage,
  WBEM_CWSTR wszQuery,
  long lSidLength,
  const BYTE* pSid
);

Parameters

wszQueryLanguage
[in] The language of the following query filter. For this version of WMI, it will always be "WQL".
wszQuery
[in] The text of the event query filter, which was registered by a logical consumer.
lSidLength
[in] Integer that contains the sid length, or zero if the subscription builder's token is available.
pSid
[in, size_is(lSidLength), unique] Pointer to the constant byte integer type that contains the sid, or NULL if the subscription builder's token is available.

Event consumer identity can be conveyed to event providers in one of two ways: using subscription builder's SID, or using subscription builder's token. Tokens are easier to deal with for the purposes of conducting an access check, so WMI will convey the subscription builder's token whenever possible. However, in the case of permanent consumers, the token is not usually available, since by the time a permanent subscription is activates (say, after a system restart), the subscription builder is long gone. In those cases, a securely stored SID is used instead.

When a token is used to convey the subscription builder's identity, event provider can use the standard DCOM mechanisms to impersonate the caller (see CoImpersonateClient, IServerSecurity). In those cases, the pSid parameter is set to NULL and lSidLength is set to 0.

When no token is available, pSid is set to point to the subscription builder's SID (in the form of the self-referential SID structure). Use standard Microsoft® Windows NT® APIs to examine the SID (such as GetLengthSid and LookupAccountName).

Note The ASSOCIATORS OF and REFERENCES OF syntax is not supported for events.

Return Values

This method returns an HRESULT with one of the following values.

Value | Meaning
WBEM_S_NO_ERROR | The user has permission to subscribe to the event.
WBEM_E_ACCESS_DENIED | The user does not have permission to access the event.
WBEM_E_FAILED | Indicates a provider failure.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemprov.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemEventProvider, SELECT Statement for Event Queries


IWbemHiPerfProvider

[This is preliminary documentation and subject to change.]

The IWbemHiPerfProvider interface is commonly implemented by providers that supply refreshable objects and enumerators. HiPerf providers can be loaded either in-process to WMI or in-process to a client process. When the provider is loaded in-process to a client process, the CLSID it specifies as a ClientLoadableCLSID in its __Win32Provider instance definition will be used.

IWbemHiPerfProvider methods | Description
CreateRefreshableEnum | Creates a refreshable enumerator.
CreateRefreshableObject | Creates a refreshable instance object.
CreateRefresher | Creates a refresher.
GetObjects | Retrieves the specified objects.
QueryInstances | Returns instances of the specified class by using the supplied IWbemObjectSink.
StopRefreshing | Stops refreshing an enumerator or instance object.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemprov.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemHiPerfProvider::CreateRefreshableEnum

[This is preliminary documentation and subject to change.]

The CreateRefreshableEnum method creates a new refreshable enumeration.The provider associates the supplied IWbemHiPerfEnum object with the supplied refresher. On each call to the supplied refresher's Refresh method, the provider ensures that the enumerator contains a set of all the instances of the class listed in the wszClass parameter and that these instances contain updated information.

Note If a provider does not implement this method, it must return WBEM_E_PROVIDER_NOT_CAPABLE.

HRESULT IWbemHiPerfProvider::CreateRefreshableEnum(
  IWbemServices *pNamespace,
  LPCWSTR wszClass,
  IWbemRefresher *pRefresher,
  long lFlags,
  IWbemContext *pCtx,
  IWbemHiPerfEnum *pHiPerfEnum,
  long *plId
);

Parameters

pNamespace
[in] IWbemServices pointer back into Windows Management, which can service any requests made by the provider. If pNamespace must call back into Windows Management during its execution, the provider should call AddRef on this pointer.
wszClass
[in] Constant, null-terminated string of 16-bit, Unicode characters that contains the name of the class, whose instances should be refreshed in the pHiPerfEnum parameter.
pRefresher
[in] Pointer to a IWbemRefresher object that contains a refresher obtained by calling IWbemHiPerfProvider::CreateRefresher.
lFlags
[in] Reserved; the value must be zero.
pCtx
[in] Typically NULL; otherwise, a pointer to an IWbemContext object required by one or more dynamic class providers. The values in the context object must be specified in the specific provider's documentation. For more information about this parameter, see "Making Calls to WMI.".
pHiPerfEnum
[in] Pointer to a IWbemHiPerfEnum object that contains the high-performance enumeration.
plId
[out] Pointer to an integer returned by the provider that uniquely identifies the refreshable enumeration.

Return Values

If The CreateRefreshableEnum method is successful, it returns WBEM_S_NO_ERROR; otherwise, this method returns an HRESULT with one of the following values.

Value | Meaning
WBEM_E_PROVIDER_NOT_CAPABLE | The provider does not implement this method.
WBEM_E_INVALID_CLASS | The provider does not support the requested class.
WBEM_E_ACCESS_DENIED | The current user does not have permission to retrieve instances of the specified class.
WBEM_E_NOT_FOUND | The requested instance could not be found.
WBEM_E_INVALID_OBJECT_PATH | The specified path was invalid.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_OUT_OF_MEMORY | Memory could not be allocated.
WBEM_E_FAILED | This indicates other unspecified errors.

Remarks

The provider must not modify the refreshable enumerator except during a refresh operation. The enumeration is shallow, so all instances placed in the enumerator should be of the class specified by wszClass.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemprov.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemHiPerfProvider


IWbemHiPerfProvider::CreateRefreshableObject

[This is preliminary documentation and subject to change.]

The CreateRefreshableObject method requests a refreshable instance object. The provider reads the key from the supplied template object and supplies an object in the ppRefreshable parameter that will be refreshed whenever the refresh method on pRefresher is called. The provider associates the refreshable object with the supplied refresher.

Note If a provider does not implement this method, it must return WBEM_E_PROVIDER_NOT_CAPABLE.

HRESULT IWbemHiPerfProvider::CreateRefreshableObject(
  IWbemServices *pNamespace,
  IWbemObjectAccess *pTemplate,
  IWbemRefresher *pRefresher,
  long lFlags,
  IWbemContext *pCtx,
  IWbemObjectAccess **ppRefreshable,
  long *Plid
);

Parameters

pNamespace
[in] An IWbemServices pointer back into Windows Management, which can service any request made by the provider. If the pointer must call back into Windows Management during its execution, the provider should AddRef.
pTemplate
[in] Pointer to a IWbemObjectAccess object that contains the template.
pRefresher
[in] Pointer to a IWbemRefresher object that contains a refresher obtained by calling IWbemHiPerfProvider::CreateRefresher.
lFlags
[in] Reserved; the value must be zero.
pCtx
[in] Typically NULL; otherwise, a pointer to an IWbemContext object that is required by one or more dynamic class providers.

The values in the context object must be specified in the specific provider documentation. For more information about this parameter, see Making Calls to WMI..

ppRefreshable
[out] Pointer that holds the reference to a IWbemObjectAccess object, which will contain the refreshable object.
plId
[out] Pointer to an integer returned by the provider that uniquely identifies this refreshable object.

Return Values

If the CreateRefreshableObject method is successful, it returns WBEM_S_NO_ERROR; otherwise, this method returns an HRESULT with one of the following values.

WBEM_E_ACCESS_DENIED | The current user does not have permission to retrieve instances of the specified class.
WBEM_E_INVALID_OBJECT_PATH | The specified path was invalid.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_OUT_OF_MEMORY | Memory could not be allocated.
WBEM_E_FAILED | This indicates other unspecified errors.

Remarks

The supplied instance template will contain an object with the key properties filled out. The returned object should be a unique, refreshable object. The provider must not touch the refreshable object except during a refresh operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemprov.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemHiPerfProvider


IWbemHiPerfProvider::CreateRefresher

[This is preliminary documentation and subject to change.]

The CreateRefresher method creates a refresher. The returned refresher will be used in subsequent calls to CreateRefreshableEnum, CreateRefreshableObject, and StopRefreshing.

Note If a provider does not implement this method, it must return WBEM_E_PROVIDER_NOT_CAPABLE. A provider must implement this method in order to support refresher operations.

HRESULT IWbemHiPerfProvider::CreateRefresher(
  IWbemServices *pNamespace,
  long lFlags,
  IWbemRefresher **ppRefresher
);

Parameters

pNamespace
An IWbemServices pointer back into Windows Management, which can service any request made by the provider. The provider should call AddRef on this pointer if it is going to need to call back into Windows Management during its execution.
lFlags
Reserved; the value must be zero.
ppRefresher
[out] Pointer to hold the reference to the provider's implementation of the IWbemRefresher interface.

Return Values

If the CreateRefresher method is successful, it returns WBEM_S_NO_ERROR.

Remarks

The provider must supply its own implementation of the IWbemRefresher interface. It is valid for WMI to request multiple refreshers, each of which will be used for its own refresh operations.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemprov.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemHiPerfProvider


IWbemHiPerfProvider::GetObjects

[This is preliminary documentation and subject to change.]

The GetObjects method fills out the non-key properties of the objects in the supplied array.

Note If a provider does not implement this method, it should return WBEM_E_PROVIDER_NOT_CAPABLE.

HRESULT IWbemHiPerfProvider::GetObjects(
  IWbemServices *pNamespace,
  long lNumObjects,
  IWbemObjectAccess *apObj,
  long lFlags,
  IWbemContext *pCtx
);

Parameters

pNamespace
An IWbemServices pointer back into Windows Management, which can service any request made by the provider. The provider should call AddRef on this pointer if it is going to need to call back into Windows Management during its execution.
lNumObjects
[in] Integer that contains the number of objects you are retrieving.
apObj
[in,out,size_is(lNumObjects)] A pointer to an array of IWbemObjectAccess objects. The key properties of each object will be filled out.
lFlags
Reserved; the value must be zero.
pCtx
Typically NULL; otherwise, a pointer to an IWbemContext object that is required by one or more dynamic class providers

The values in the context object must be specified in specific provider documentation. For more information about this parameter, see Making Calls to WMI..

Return Values

If the GetObjects method is successful, it returns WBEM_S_NO_ERROR; otherwise, this method returns an HRESULT with one of the following values.

Value | Meaning
WBEM_E_PROVIDER_NOT_CAPABLE | The provider does not implement this method.
WBEM_E_NOT_FOUND | The requested instance could not be found.
WBEM_E_ACCESS_DENIED | The current user does not have permission to retrieve the specified instance.

Remarks

The requested objects will have their key properties filled out.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemprov.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemHiPerfProvider


IWbemHiPerfProvider::QueryInstances

[This is preliminary documentation and subject to change.]

The QueryInstances method returns instances of the specified class using the supplied IWbemObjectSink. The method should return immediately; the IWbemObjectSink interface is used to specify results.

If a provider does not implement this method, it must return WBEM_E_PROVIDER_NOT_CAPABLE.

HRESULT IWbemHiPerfProvider::QueryInstances(
  IWbemServices *pNamespace,
  WCHAR *wszClass,
  long lFlags,
  IWbemContext *pCtx,
  IWbemObjectSink *pSink
);

Parameters

pNamespace
[in] An IWbemServices pointer back into Windows Management, which can service any request made by the provider. The provider should AddRef this pointer if it is going to need to call back into Windows Management during its execution.
wszClass
[in, string] Pointer to a WCHAR string that specifies the class whose instances will be returned.
lFlags
[in] Integer that contains the flags.
pCtx
[in] Typically NULL; otherwise, a pointer to an IWbemContext object that is required by one or more dynamic class providers

The values in the context object must be specified in the specific provider documentation. For more information about this parameter, see Making Calls to WMI..

pSink
[in] The pointer to the IWbemObjectSink implementation that is provided by the client to any of the asynchronous methods of IWbemServices.

Return Values

If the QueryInstances method is successful, it returns WBEM_S_NO_ERROR; otherwise, this method returns an HRESULT with one of the following values.

Value | Meaning
WBEM_E_PROVIDER_NOT_CAPABLE | The provider does not implement this method.
WBEM_E_NOT_FOUND | The requested instance could not be found.
WBEM_E_ACCESS_DENIED | The current user does not have permission to retrieve the specified instance.

Remarks

IWbemObjectSink::SetStatus is called to indicate the end of the result set. When error conditions occur, IWbemObjectSink::SetStatus may also be called with no intervening calls to IWbemObjectSink::Indicate.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemprov.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemHiPerfProvider


IWbemHiPerfProvider::StopRefreshing

[This is preliminary documentation and subject to change.]

The StopRefreshing method stops refreshing the object or enumerator corresponding to the supplied identifier.

Note If a provider does not implement this method, it must return WBEM_E_PROVIDER_NOT_CAPABLE. A provider should implement the StopRefreshing method if it implements IWbemHiPerfProvider::CreateRefreshableEnum or IWbemHiPerfProvider::CreateRefreshableObject.

HRESULT IWbemHiPerfProvider::StopRefreshing(
  IWbemRefresher *pRefresher,
  long lId,
  long lFlags
);

Parameters

pRefresher
[in] Pointer to a IWbemRefresher object that contains a refresher obtained by calling IWbemHiPerfProvider::CreateRefresher.
lId
[in] Integer containing a refresher identifier that uniquely identifies the object you want to stop refreshing.
lFlags
[in] Integer that contains the flags.

Return Values

If the StopRefreshing method is successful, it returns WBEM_S_NO_ERROR; otherwise, StopRefreshing returns an HRESULT with one of the following values.

Value | Meaning
WBEM_E_PROVIDER_NOT_CAPABLE | The provider does not implement this method.
WBEM_S_FALSE | The requested object or enumerator could not be found.

Remarks

It is not necessary to call StopRefreshing to cleanup a refresher. It is sufficient to simply delete the refresher, that is, to release all references to it. Deleting the refresher causes the cleanup of all objects and enumerators within it.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemprov.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemHiPerfProvider


IWbemHiPerfEnum

[This is preliminary documentation and subject to change.]

The IWbemHiPerfEnum interface is used in refresher operations to provide rapid access to enumerations of instance objects. WMI provides an implementation of this interface, which it passes to providers when IWbemHiPerfProvider::CreateRefreshableEnum is called, and it returns to clients when IWbemConfigureRefresher::AddEnum is called.

Client applications can call only the GetObjects method of this interface. Attempts by client applications to call the other IWbemHiPerfEnum methods will return WBEM_E_ACCESS_DENIED. Providers call these other methods to update the enumerators whenever a client calls Refresh.

Note Do not, under any circumstances, use the client application or a provider to implement this interface. The implementation provided by WMI is the only one that is supported.

IWbemHiPerfEnum Methods | Description
AddObjects | Adds objects with assigned identifiers.
GetObjects | Retrieves objects from the enumerator.
RemoveAll | Removes all objects from the enumerator.
RemoveObjects | Remove objects with the specified identifiers.


IWbemHiPerfEnum::AddObjects

[This is preliminary documentation and subject to change.]

The AddObjects method adds the supplied instance objects to the enumerator.

HRESULT IWbemHiPerfEnum::AddObjects(
  long lFlags,
  ULONG uNumObjects,
  long *apIds,
  IWbemObjectAccess *apObj
);

Parameters

lFlags
Reserved; the value must be zero.
uNumObjects
[in] ULONG that contains the number of items in the object and the number of identifiers in the parameter.
apIds
[in, size_is(uNumObjects)] Pointer to an array of integers that contains a unique identifier for each object in the object array.
apObj
[in, size_is(uNumObjects)] Pointer to an array of instance objects to add to the enumerator.

Return Values

If the AddObjects method is successful, it returns WBEM_S_NO_ERROR; otherwise, this method returns an HRESULT with one of the following values.

Value | Meaning
WBEM_E_FAILED | A specified index already exists.
WBEM_E_OUT_OF_MEMORY | Memory could not be allocated.
WBEM_E_ACCESS_DENIED | Insufficient access to perform the operation.
WBEM_S_TIMED_OUT | The enumerator was busy with another operation.

Remarks

If an identifier already exists, WBEM_E_FAILED will be returned. The refresher identifiers can be used to remove objects later.

See Also

IWbemHiPerfEnum


IWbemHiPerfEnum::GetObjects

[This is preliminary documentation and subject to change.]

The GetObjects method retrieves objects currently residing in the enumerator.

HRESULT IWbemHiPerfEnum::GetObjects(
  long lFlags,
  ULONG uNumObjects,
  IWbemObjectAccess *apObj,
  ULONG *puReturned
);

Parameters

lFlags
[in] Integer that contains the flags.
uNumObjects
[in] ULONG that specifies the size of the array passed to this method in the apObj parameter.
apObj
[out,size_is(uNumObjects),length_is(*puReturned)] Pointer that holds the reference to an array of IWbemObjectAccess objects, which will contain the returned objects. The array must be big enough to hold all objects in the enumerator.
puReturned
[out] Pointer to a ULONG used to return the number of objects placed in the array.

Return Values

If the GetObjects method is successful, it returns WBEM_S_NO_ERROR; otherwise, this method returns an HRESULT with one of the following values.

Value | Meaning
WBEM_E_BUFFER_TOO_SMALL | The supplied buffer was too small to hold all the objects in the enumerator.
WBEM_S_TIMED_OUT | The enumerator was busy with another operation.

Remarks

The array must be large enough to hold all objects, or puReturned will be filled with the number of returned objects, and WBEM_E_BUFFER_TOO_SMALL will be returned.

See Also

IWbemHiPerfEnum


IWbemHiPerfEnum::RemoveAll

[This is preliminary documentation and subject to change.]

The RemoveAll method empties all objects from the enumerator.

HRESULT IWbemHiPerfEnum::RemoveAll(
  long lFlags
);

Parameters

lFlags
Reserved; the value must be zero.

Return Values

If the RemoveAll method is successful, it returns WBEM_S_NO_ERROR.


IWbemHiPerfEnum::RemoveObjects

[This is preliminary documentation and subject to change.]

The RemoveObjects method removes objects (identified by their refresher identifiers) from a refresher.

HRESULT IWbemHiPerfEnum::RemoveObjects(
  long lFlags,
  ULONG uNumObjects,
  long *apIds
);

Parameters

lFlags
Reserved; the value must be zero.
uNumObjects
[in] ULONG that contains the number of objects to remove.
apIds
[in, size_is(uNumObjects)] Pointer to an array of integers that contain the refresher IDs of the objects to remove.

Return Values

If the RemoveObjects method is successful, it returns WBEM_S_NO_ERROR; otherwise, this method returns an HRESULT with one of the following values.

Value | Meaning
WBEM_E_OUT_OF_MEMORY | Memory could not be allocated.
WBEM_E_ACCESS_DENIED | Insufficient access to perform the operation.
WBEM_S_TIMED_OUT | The enumerator was busy with another operation.

See Also

IWbemHiPerfEnum


IWbemLocator

Use the IWbemLocator interface to obtain the initial namespace pointer to the Windows Management on a particular host machine. You can access Windows Management itself using the IWbemServices pointer, which is returned by the ConnectServer method on this interface.

A client or provider that needs Windows Management services first obtains a pointer to the locator using CoCreateInstance or CoCreateInstanceEx, as specified in COM documentation in the Microsoft Platform SDK. The IWbemLocator object is always an in-process COM server. The interface pointer to the desired namespace on the desired target machine is then obtained through the IWbemLocator::ConnectServer method, which is the only method on this interface.

IWbemLocator Methods | Description
ConnectServer | Connects to Windows Management on the specified machine.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemLocator::ConnectServer

The IWbemLocator::ConnectServer method connects to Windows Management on the machine specified in the strNetworkResource parameter. This is typically a Windows NT/Microsoft® Windows® 2000 machine, or a Windows 95/98 target with WMI installed.

HRESULT IWbemLocator::ConnectServer(
  const BSTR strNetworkResource,
  const BSTR strUser,
  [in] const BSTR strPassword,
  const BSTR strLocale,
  LONG lSecurityFlags,
  const BSTR strAuthority,
  IWbemContext *pCtx,
  IWbemServices **ppNamespace
);

Parameters

strNetworkResource
[in] A pointer to a valid BSTR containing the object path of the desired Windows Management and namespace.

For local machine access to the default namespace, use a simple object path: "root\default" or "\\.\root\default."

For access to the default namespace on a remote machine using Distributed COM (DCOM) or Microsoft-compatible networking, include the machine name: "\\myserver\root\default". The machine name can also be a DNS name or IP address.

See Object Paths.

strUser
[in] A pointer to a valid BSTR, which contains the user name you need for a connection. A NULL value indicates the currently logged on user.

If the user name is from a domain other than the current domain, the string may contain the domain name and user name, separated by a backslash:

StrUserName = SysAllocString(L"Domain\\UserName");

The strUser parameter can't be an empty string.

strPassword
[in] A pointer to a valid BSTR, which contains the password you need for a connection. A NULL value indicates the currently logged on user's current password, while a blank string, "", specifies a valid zero length password.
strLocale
[in] If NULL, the current locale is used. If not NULL, this parameter must be a valid BSTR, which indicates the desired locale for information retrieval. For Microsoft locale identifiers, the format of the string is "MS_xxxx", where xxxx is a string in hexadecimal form that indicates the LCID.

For example, American English would appear as "MS_409"

The string format is required since WMI accommodates other localization schemes besides Microsoft 32-bit LCIDs, such as ISO 639 or RFC 1766.

lSecurityFlags
[in] Reserved. This must be zero.
strAuthority
[in] If not NULL this parameter can contain the name of the Windows NT/Windows 2000 domain in which to obtain the user to authenticate. This parameter must be passed as follows: If the strAuthority parameter begins with the string "Kerberos:", Kerberos authentication will be used and this parameter should contain a Kerberos principal name. For example, Kerberos:<principal name>. If the strAuthority parameter begins with the string "NTLMDOMAIN:", NTLM authentication will be used and this parameter should contain a NTLM domain name. For example, NTLMDOMAIN:<domain name>. If you leave this parameter blank, NTLM authentication will be used and the NTLM domain of the current user will be used.
pCtx
[in] Typically NULL. Otherwise, this is a pointer to an IWbemContext object required by one or more dynamic class providers The values in the context object must be specified in the documentation for the providers in question. See Making Calls to WMI for more information about this parameter.
ppNamespace
[out] Receives a pointer to an IWbemServices object bound to the specified namespace. This pointer has a positive reference count. The caller must call IWbemServices::Release on the pointer when it is no longer required. This pointer is set to point to NULL when there is an error.

Return Values

Value | Meaning
WBEM_E_ACCESS_DENIED | The current or specified user name and password were not valid or authorized to make the connection.
WBEM_E_FAILED | This indicates other unspecified errors.
WBEM_E_INVALID_NAMESPACE | The specified namespace did not exist on the server.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_TRANSPORT_FAILURE | This indicates the failure of the remote procedure call (RPC) link between the current process and Windows Management.
WBEM_E_LOCAL_CREDENTIALS | WMI is passing the user credential on local connection.
WBEM_S_NO_ERROR | The call succeeded.

Note DCOM-specific error codes also may be returned if network problems cause you to lose the remote connection to Windows Management.

These error return codes are defined in the Wbemcli.h file in the WMI SDK \Include folder.

Remarks

When connecting to WMI on a remote Windows 95 system from a Windows NT/Windows 2000 system, there are two issues to consider.

  • If the local system is supplying credentials (your user name and password) of a domain that it is not a member of, you may notice that synchronous enumerations and queries may take much longer to process.
  • If you provide credentials in the process of connecting to WMI, the logon will fail and you will get an RPC Server is unavailable error.
  • Neither strUser , strPassword, nor strAuthoritycan be specified when making a connection to a local namespace.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemServices


IWbemObjectAccess

[This is preliminary documentation and subject to change.]

The IWbemObjectAccess interface provides access to the methods and properties of an object. IWbemObjectAccess objects are a container for instances updated by a refresher. With the IWbemObjectAccess interface, you can get and set properties by using property handles instead of object property names. The methods of IWbemObjectAccess objects can read and write properties of refreshable objects much faster than equivalent calls to IWbemClassObject::Get and IWbemClassObject::Put.

Property handles are the same for all instances of a class. Therefore, it is only necessary to retrieve a handle once.

Note To maximize its speed, IWbemObjectAccess is completely unchecked. It is the responsibility of the user to ensure that all handles are proper, and that write buffers are correctly sized. Read and write operations are not intrinsically thread-safe. You should call the IWbemObjectAccess::Lock and IWbemObjectAccess::Unlock methods to prevent IWbemObjectAccess objects from concurrent access on multiple threads.

This interface is not implemented by client applications or providers under any circumstances. The implementation provided by WMI is the only one that is supported. A pointer to the interface can be retrieved by calling IWbemClassObject::QueryInterface.

IWbemObjectAccess Methods | Description
GetPropertyHandle | Returns a unique handle that identifies a property. You can use this handle to identify properties when using IWbemObjectAccess methods to read or write property values.
GetPropertyInfoByHandle | Returns the name and data type of the property that is associated with a property handle.
Lock | Prevents other processes from updating an IWbemObjectAccess object until it is unlocked.
ReadDWORD | Reads 32 bits of property data.
ReadPropertyValue | Reads a specified number of bytes of property data.
ReadQWORD | Reads 64 bits of property data.
Unlock | Allows other processes to update the property values of an IWbemObjectAccess object.
WriteDWORD | Writes 32 bits of property data.
WritePropertyValue | Writes a specified number of bytes of property data.
WriteQWORD | Writes 64 bits of property data.

Remarks

The IWbemObjectAccess methods that read and write data perform very little data validation.

Because IWbemObjectAccess methods directly access properties, you can get and set properties much more rapidly than you can using standard object access techniques such as IWbemClassObject::Get and IWbemClassObject::Put.

The IWbemObjectAccess interface is not inherently thread-safe. You must manually lock and unlock threads as needed.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemObjectAccess::GetPropertyHandle

[This is preliminary documentation and subject to change.]

The GetPropertyHandle method returns a unique handle that identifies a property. You can use this handle to identify properties when using IWbemObjectAccess methods to read or write property values.

HRESULT IWbemObjectAccess::GetPropertyHandle(
  LPCWSTR wszPropertyName,
  CIMTYPE *pType,
  long *plHandle
);

Parameters

wszPropertyName
[in, string] Constant, null-terminated string of 16-bit Unicode characters that contains the property name.
pType
[out] Pointer to a CIMTYPE used to return the CIM type of the property.
plHandle
[out] Pointer to an integer used to return the property handle.

Return Values

Value | Meaning
WBEM_E_NOT_SUPPORTED | The request properties are type : CIM_OBJECT or CIM_ARRAY
WBEM_E_NOT_FOUND | The property name specified doesn't exist
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_S_NO_ERROR | The call succeeded.

Remarks

Handles can be retrieved for all data types other than CIM_OBJECT and CIM_ARRAY. Returned handles will work across all instances of a class.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemObjectAccess


IWbemObjectAccess::GetPropertyInfoByHandle

[This is preliminary documentation and subject to change.]

The GetPropertyInfoByHandle method returns the name and data type of the property that is associated with a property handle.

HRESULT IWbemObjectAccess::GetPropertyInfoByHandle(
  long lHandle,
  BSTR *pstrName,
  CIMTYPE *pType
);

Parameters

lHandle
[in] Integer that contains the handle that identifies the property.
pstrName
[out] Pointer to a string used to return the name of the specified property.
pType
[out] Pointer to a CIMTYPE used to return the type of the property.

Return Values

If the GetPropertyInfoByHandle method is successful, it returns WBEM_S_NO_ERROR; otherwise, this method returns an HRESULT with one of the following values.

Value | Meaning
WBEM_E_NOT_FOUND | Handle was not found.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemObjectAccess


IWbemObjectAccess::Lock

[This is preliminary documentation and subject to change.]

The Lock method prevents other threads from updating an IWbemObjectAccess object until it is unlocked.

HRESULT IWbemObjectAccess::Lock(
  long lFlags
);

Parameters

lFlags
Reserved. This parameter is currently ignored and reserved for future use.

Return Values

If the Lock method is successful, it returns WBEM_S_NO_ERROR.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemObjectAccess


IWbemObjectAccess::ReadDWORD

[This is preliminary documentation and subject to change.]

The ReadDWORD method reads 32 bits of property data using a property handle.

HRESULT IWbemObjectAccess::ReadDWORD(
  long lHandle,
  DWORD *pdw
);

Parameters

lHandle
[in] Integer that contains the handle that identifies this property.
pdw
[out] Pointer to a 32-bit unsigned integer used to return the data.

Return Values

If the ReadDWORD method is successful, it returns WBEM_S_NO_ERROR; otherwise, this method returns an HRESULT with one of the following values.

Value | Meaning
WBEM_S_FALSE | The property was NULL.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemObjectAccess


IWbemObjectAccess::ReadPropertyValue

[This is preliminary documentation and subject to change.]

The ReadPropertyValue method returns a specified number of bytes of a property associated with a property handle. Use this method to read the value of a property that contains a string or to read a property that contains a value that is not 32 (DWORD) or 64 (QWORD) bits long.

HRESULT IWbemObjectAccess::ReadPropertyValue(
  long lHandle,
  long lBufferSize,
  long *plNumBytes,
  byte *aData
);

Parameters

lHandle
[in] Integer that contains the handle that identifies this property.
lBufferSize
[in] Integer that contains the buffer size.
plNumBytes
[out] Pointer to an integer used to return the number of bytes read.
aData
[out, size_is(lBufferSize), length_is(*plNumBytes)] Pointer to an array used to return the property data.

Return Values

If the ReadPropertyValue methodis successful, it returns WBEM_S_NO_ERROR; otherwise this method returns an HRESULT with one of the following values.

Value | Meaning
WBEM_E_BUFFER_TOO_SMALL | The supplied buffer was too small to read a string property.
WBEM_S_FALSE | The property was NULL.

Remarks

String data is returned as WCHAR data and NULL-terminated.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemObjectAccess Interface


IWbemObjectAccess::ReadQWORD

[This is preliminary documentation and subject to change.]

The ReadQWORD method reads 64 bits of property data identified by a property handle.

HRESULT IWbemObjectAccess::ReadQWORD(
  long lHandle,
  unsigned __int64 *pqw
);

Parameters

lHandle
[in] Integer that contains the handle that identifies the property.
pqw
[out] Pointer to a unsigned 64-bit integer used to return the data being read.

Return Values

If the ReadQWORD method is successful, it returns WBEM_S_NO_ERROR. If the property was NULL, then the method returns WBEM_S_FALSE.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemObjectAccess Interface


IWbemObjectAccess::Unlock

[This is preliminary documentation and subject to change.]

The Unlock method allows other threads to update the property values of an IWbemObjectAccess object.

HRESULT IWbemObjectAccess::Unlock(
  long lFlags
);

Parameters

lFlags
Reserved. This parameter is currently ignored and reserved for future use.

Return Values

If the Unlock method is successful, it returns WBEM_S_NO_ERROR.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemObjectAccess Interface


IWbemObjectAccess::WriteDWORD

[This is preliminary documentation and subject to change.]

The WriteDWORD method writes 32 bits of data to a property identified by a property handle.

HRESULT IWbemObjectAccess::WriteDWORD(
  long lHandle,
  DWORD dw
);

Parameters

lHandle
[in] Integer that contains the handle that identifies this property.
dw
[in] 32-bit unsigned integer that contains the data being written.

Return Values

If the WriteDWORD method is successful, it returns WBEM_S_NO_ERROR.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemObjectAccess Interface


IWbemObjectAccess::WritePropertyValue

[This is preliminary documentation and subject to change.]

The WritePropertyValue method writes a specified number of bytes to a property identified by a property handle. Use this method to set string and all other non-DWORD or non-QWORD data.

HRESULT IWbemObjectAccess::WritePropertyValue(
  long lHandle,
  long lNumBytes,
  const byte *aData
);

Parameters

lHandle
[in] Integer that contains the handle that identifies this property.
lNumBytes
[in] Integer that contains the number of bytes being written to the property. For non-string property values, lNumBytes must be the correct data size of the property type specified. For string property values such as reference, string, and datetime, lNumBytes must be the length of the specified string in bytes, and the string itself must be of an even length in bytes and be followed with a null-termination character.
aData
[in, size_is(lNumBytes)] Pointer to the constant byte type array that contains the data.

Return Values

If the WritePropertyValue method is successful, it returns WBEM_S_NO_ERROR. otherwise,this method returns an HRESULT with one of the following values.

Value | Meaning
WBEM_E_TYPE_MISMATCH | A type mismatch occurred.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemObjectAccess Interface


IWbemObjectAccess::WriteQWORD

[This is preliminary documentation and subject to change.]

The WriteQWORD method writes 64 bits of data to a property by using a property handle.

HRESULT IWbemObjectAccess::WriteQWORD(
  long lHandle,
  unsigned __int64 pw
);

Parameters

lHandle
[in] Integer that contains the handle that identifies this property.
pw
[in] Unsigned 64-bit integer that contains the data written to the specified property.

Return Values

If the WriteQWORD method is successful, it returns WBEM_S_NO_ERROR.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemObjectAccess Interface


IWbemObjectSink

The IWbemObjectSink interface is a sink interface used for all types of notifications within the Windows Management programming model. Clients must implement this interface to receive both the results of the asynchronous methods of IWbemServices and certain types of event notifications. Providers use, but do not implement, this interface to provide events and objects to Windows Management.

Typically, providers call an implementation provided to them by Windows Management. In these cases, you call Indicate to provide objects to CIMOM. After that, call SetStatus to indicate the end of the notification sequence. You can also call SetStatus to indicate errors when the sink does not have any objects.

When programming asynchronous clients of Windows Management, the user provides the implementation. Windows Management calls the methods to deliver objects and set the status of the result.

Note If a client application passes the same sink interface in two different overlapping asynchronous calls, Windows Management does not guarantee the order of the callback. Client applications making overlapping asynchronous calls should either pass different sink objects, or else serialize their calls.

IWbemObjectSink Methods | Description
Indicate | Receives notification objects.
SetStatus | Receives notification status.

Sample Code

The following is a simple implementation of an object sink. This sample could be used in conjunction with IWbemServices::ExecQueryAsync or IWbemServices::CreateInstanceEnumAsync to receive the returned instances:

class QuerySink : public IWbemObjectSink
{
    LONG m_lRef;
    Bool bDone;

public:
    QuerySink() { m_lRef = 0; }
   ~QuerySink() { bDone = TRUE; }

    virtual ULONG STDMETHODCALLTYPE AddRef();
    virtual ULONG STDMETHODCALLTYPE Release();
    virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv);

    virtual HRESULT STDMETHODCALLTYPE Indicate(
            /* [in] */ LONG lObjectCount,
            /* [size_is][in] */ IWbemClassObject __RPC_FAR *__RPC_FAR *apObjArray
            );

    virtual HRESULT STDMETHODCALLTYPE SetStatus(
            /* [in] */ LONG lFlags,
            /* [in] */ HRESULT hResult,
            /* [in] */ BSTR strParam,
            /* [in] */ IWbemClassObject __RPC_FAR *pObjParam
            );
};

ULONG QuerySink::AddRef()
{
    return InterlockedIncrement(&m_lRef);
}

ULONG QuerySink::Release()
{
    LONG lRef = InterlockedDecrement(&m_lRef);
    if(lRef == 0)
        delete this;
    return lRef;
}

HRESULT QuerySink::QueryInterface(REFIID riid, void** ppv)
{
    if (riid == IID_IUnknown || riid == IID_IWbemObjectSink)
    {
        *ppv = (IWbemObjectSink *) this;
        AddRef();
        return WBEM_S_NO_ERROR;
    }
    else return E_NOINTERFACE;
}

HRESULT QuerySink::Indicate(long lObjCount, IWbemClassObject **pArray)
{
    for (long i = 0; i < lObjCount; i++)
    {
        IWbemClassObject *pObj = pArray[i];

        // ... use the object

        // AddRef() only required if the object will be held after
        // the return to the caller.
    }

    return WBEM_S_NO_ERROR;
}

HRESULT QuerySink::SetStatus(
            /* [in] */ LONG lFlags,
            /* [in] */ HRESULT hResult,
            /* [in] */ BSTR strParam,
            /* [in] */ IWbemClassObject __RPC_FAR *pObjParam
        )
{
    printf("QuerySink::SetStatus hResult = 0x%X\n", hResult);
    return WBEM_S_NO_ERROR;
}

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemObjectSink::Indicate

The IWbemObjectSink::Indicate method is called by a source to provide a notification. Typically, Windows Management calls the client's implementation of this interface after the client executes one of the asynchronous methods of IWbemServices. In other cases, various types of providers call an implementation exported by Windows Management in order to deliver events. Therefore, client code may have to implement this interface in some cases, and use a different component's implementation in other cases.

Use this interface and method in conjunction with the asynchronous methods of the IWbemServices interface.

Clients and providers must implement this interface to receive notifications or to execute the asynchronous methods of IWbemServices. For more information, see Making an Asynchronous Call.

HRESULT IWbemObjectSink::Indicate(
  LONG lObjectCount,
  IWbemClassObject **ppObjArray
);

Parameters

lObjectCount
[in] The number of objects in the following array of pointers.
ppObjArray
[in, size_is(lObjectCount)] An array of pointers to IWbemClassObject interfaces. The array memory itself is read-only, and is owned by the caller of the method. Since this is an in-parameter, the implementation has the option of calling IWbemClassObject::AddRef on any object pointer in the array and holding it before returning if the objects will be used after the method has returned, in accordance with COM rules. If the objects will only be used for the duration of the Indicate call, then you do not need to call AddRef on each object pointer. For more information on the IUnknown interface, see IUnknown Interface Basics.

Return Values

Value | Meaning
WBEM_E_FAILED | The receiver was not able to process the notification properly.
WBEM_E_CALL_CANCELLED | The operation has been cancelled and the provider should stop executing it.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified, such as a NULL ppObjArray pointer.
WBEM_S_NO_ERROR | The call succeeded; the receiver acknowledges the notification.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemObjectSink::SetStatus

The IWbemObjectSink::SetStatus method is called by sources either to indicate the end of a notification sequence or to send other status codes to the sink. IWbemObjectSink::Indicate may or may not have been called before the call to SetStatus.

Normally, a client implements the IWbemObjectSink interface, and executes IWbemServices methods that return their results using the IWbemObjectSink interface. During this operation, Windows Management calls Indicate as many times as required, followed by a final call to SetStatus, and in many cases, Release.

HRESULT IWbemObjectSink::SetStatus(
  LONG lFlags,
  HRESULT hResult,
  BSTR strParam,
  IWbemClassObject *pObjParam
);

Parameters

lFlags
[in] The lFlags parameter is a bitmask of status information. WBEM_STATUS_COMPLETE indicates the operation has completed.

WBEM_STATUS_PROGRESS indicates the operation is still in progress. The status of the operation can be obtained by examining the hResult parameter.

hResult
[in] This parameter is set to the HRESULT of the asynchronous operation or notification. This will be either an error code, if an error occurred, or the amount of progress that has been made on an asynchronous call.

Only callers that requested status reports by specifying WBEM_FLAG_SEND_STATUS as an lFlags parameter will receive intermediate status updates. The exact status can be determined by examining the HIWORD and LOWORD of the hResult separately. The LOWORD (hResult) contains the amount of progress that has been made so far and the HIWORD (hResult) contains the total.

If you do not specify WBEM_FLAG_SEND_STATUS, you are guaranteed to receive one and only one call to SetStatus.

strParam
[in] Receives a pointer to a read-only BSTR, if the original asynchronous operation returns a string. For example, when using PutInstanceAsync, IWbemObjectSink::SetStatus is called with this parameter set to the object path of the newly created instance.
pObjParam
[in] In cases where a complex error or status object is returned, this contains a pointer to the error object. If the object is required after SetStatus returns, the called object must use the AddRef method on the pointer before the called object returns.

Return Values

Value | Meaning
WBEM_E_FAILED | The receiver was not able to process the notification properly.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_S_NO_ERROR | The call succeeded; the receiver acknowledges the notification.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemPropertyProvider

The IWbemPropertyProvider interface is the primary interface of property providers. Property providers implement IWbemPropertyProvider to support retrieving and updating individual properties in an instance of a CIM class. Windows Management is the only client of this interface, and it calls the methods whenever the properties are required by a client application.

IWbemPropertyProvider Methods | Description
GetProperty | Called by Windows Management to retrieve a property value.
PutProperty | Called by Windows Management to write a property value.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemprov.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemPropertyProvider::GetProperty

The IWbemPropertyProvider::GetProperty method is called by Windows Management to retrieve an individual property value.

HRESULT IWbemPropertyProvider::GetProperty(
  long lFlags,
  const BSTR strLocale,
  const BSTR strClassMapping,
  const BSTR strInstMapping,
  const BSTR strPropMapping,
  VARIANT *pvValue
);

Parameters

lFlags
[in] Reserved. It must be zero.
strLocale
[in] A string indicating the desired locale in cases where the returned property value can be localized. If the property cannot be localized, the implementation can ignore this value.
strClassMapping
[in] A literal copy of the string value for the CLASSCONTEXT qualifier for the class. This points to a valid BSTR, which is treated as read-only, or NULL if the qualifier does not exist.
strInstMapping
[in] A literal copy of the string value for the INSTANCECONTEXT qualifier for the instance. This must point to a valid BSTR, which is treated as read-only, or NULL if the qualifier does not exist.
strPropMapping
[in] A literal copy of the value of the PROPERTYCONTEXT qualifier for the property. This must point to a valid BSTR, which is treated as read-only, or NULL if the qualifier does not exist.
pvValue
[out] Points to an uninitialized VARIANT that receives the value for the property. The implementation must call VariantInit and return the value. If an error occurs, the implementation is expected to ignore the pointer.

Return Values

Must return WBEM_S_NO_ERROR if the call succeeds. If the call fails, the method must return WBEM_S_FALSE.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemprov.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

Implementing IWbemPropertyProvider::GetProperty, PutProperty, Constructing Property Providers


IWbemPropertyProvider::PutProperty

The IWbemPropertyProvider::PutProperty method is called by Windows Management to update a property value supported by a property provider.

HRESULT IWbemPropertyProvider::PutProperty(
  long lFlags,
  const BSTR strLocale,
  const BSTR strClassMapping,
  const BSTR strInstMapping,
  const BSTR strPropMapping,
  VARIANT *pvValue
);

Parameters

lFlags
[in] Reserved. It must be zero.
strLocale
[in] A string indicating the desired locale in cases where the returned property value can be localized. If the property cannot be localized, the implementation can ignore this value.
strClassMapping
[in] A literal copy of the string value for the CLASSCONTEXT qualifier for the class. This points to a valid BSTR, which is treated as read-only, or NULL if the qualifier does not exist.
strInstMapping
[in] A literal copy of the string value for the INSTANCECONTEXT qualifier for the instance. This must point to a valid BSTR, which is treated as read-only, or NULL if the qualifier does not exist.
strPropMapping
[in] A literal copy of the value of the PROPERTYCONTEXT qualifier for the property. This must point to a valid BSTR, which is treated as read-only, or NULL if the qualifier does not exist.
pvValue
[in] Points to an existing VARIANT that contains the value to be written.

Return Values

The implementation must return WBEM_S_NO_ERROR if the operation succeeds, or WBEM_S_FALSE if the operation fails.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemprov.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

GetProperty


IWbemProviderIdentity Interface

The IWbemProviderIdentity interface is implemented by an event provider if the provider registers itself using more than one Name (multiple instances of __Win32Provider) with the same CLSID. The class provides a mechanism for distinguishing which named provider should be used.

The IWbemProviderIdentity interface defines the following methods:

Method | Description
SetRegistrationObject | Sets the provider object for this registration.


IWbemProviderIdentity::SetRegistrationObject

The SetRegistrationObject method is called by WinMgmt.exe prior to initializing an event provider (if the provider implements IWbemProviderIdentity). The method is used to pass to the provider the __Win32Provider instance by which the provider is being initialized. This method is only used if you have more than one provider sharing the same CLSID.

Definition

HRESULT IWbemProviderIdentity::SetRegistrationObject(
  long lFlags,
  IWbemClassObject* pProvReg
);

Parameters

lFlags
[in] Reserved, must be 0.
pProvReg
[in] The instance of __Win32Provider that announces the provider's name and CLSID.

Return Values

This method returns an HRESULT with one of the following values.

Value | Meaning
WBEM_S_NO_ERROR | Method succeeded.

Remarks

Any HRESULT return code other than WBEM_S_NO_ERROR indicates a provider failure.

Example

myWbemProviderIdentity.SetRegistrationObject(0, pProvReg);

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemprov.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemProviderIdentity Interface


IWbemProviderInit

The IWbemProviderInit interface is called by Windows Management to initialize providers. All providers are required to implement IWbemProviderInit.

IWbemProviderInit Methods | Description
Initialize | Called by Windows Management to initialize a provider.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemprov.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemProviderInit::Initialize

The IWbemProviderInit::Initialize method is called by Windows Management to initialize a provider and deem it ready to receive client requests. All types of providers must implement this method.

HRESULT IWbemProviderInit::Initialize(
  LPWSTR wszUser,
  LONG lFlags,
  LPWSTR wszNamespace,
  LPWSTR wszLocale,
  IWbemServices *pNamespace,
  IWbemContext *pCtx,
  IWbemProviderInitSink *pInitSink
);

Parameters

wszUser
[in, unique, string] Pointer to the user name, if per-user initialization was requested in the __Win32Provider registration instance for this provider. Otherwise, this will be NULL.
lFlags
[in] Reserved. It must be zero.
wszNamespace
[in, string] The namespace name for which the provider is being initialized.
wszLocale
[in, unique, string] The locale name for which the provider is being initialized. This is typically a string of the following format, where the hex value is a Microsoft standard LCID value:

"MS_409"

This parameter may be NULL.

pNamespace
[in] An IWbemServices pointer back into Windows Management. This pointer is capable of servicing any requests made by the provider. The provider should use the IWbemProviderInit::AddRef method on this pointer if it is going to need to call back into Windows Management during its execution.
pCtx
[in] An IWbemContext pointer associated with initialization. This parameter may be NULL.

If the provider needs to make requests back into Windows Management before completing initialization, it should use the IWbemProviderInit::AddRef method on this pointer. For more information, see Making Calls to WMI.

In the event that a Provider needs to make a dependant request on another Provider, you must pass this context string back to WMI to avoid potential lockups. However, in the case of an independent request, this is not necessary, and WMI will generate a new context string for it.

pInitSink

[in] An IWbemProviderInitSink pointer that is used by the provider to report initialization status.

Return Values

The provider should return WBEM_S_NO_ERROR and indicate its status using the supplied object sink in the pInitSink parameter. However, if a provider returns WBEM_E_FAILED and does not use the sink, then the provider initialization will be considered as failed.

Remarks

Typically, the provider will implement a COM object using multiple inheritance in order to support both the IWbemProviderInit interface as well as its primary interface, such as IWbemServices or IWbemEventProvider.

Initialization status is reported by calling IWbemProviderInitSink::SetStatus. This method can be called repeatedly to report incremental status if necessary. The provider must increment the reference count on this pointer by calling its IWbemProviderInit::AddRef method before using it to communicate status to Windows Management.

The provider may use the IWbemProviderInitSink pointer synchronously as in the following example:

HRESULT SampleProvider::Initialize(
    /* [unique][in] */  LPWSTR wszUser,
    /* [in] */          LONG lFlags,
    /* [in] */          LPWSTR wszNamespace,
    /* [unique][in] */  LPWSTR wszLocale,
    /* [in] */          IWbemServices __RPC_FAR *pNamespace,
    /* [in] */          IWbemContext __RPC_FAR *pCtx,
    /* [in] */          IWbemProviderInitSink __RPC_FAR *pInitSink
    )
{
    // AddRef the pNamespace pointer, if required

    // Analyze other parameters

    // Tell Windows Management that we are initialized
    pInitSink->SetStatus(WBEM_S_INITIALIZED, 0);
    return WBEM_S_NO_ERROR;
}

The provider may also use the AddRef method on the pointer and create a separate thread to complete its initialization and immediately return from the call.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemprov.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

Initializing a Provider


IWbemProviderInitSink

The IWbemProviderInitSink interface is exported by Windows Management and called by the provider during the initialization sequence.

IWbemProviderInitSink Methods | Description
SetStatus | Called by the provider to indicate success or failure of initialization.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemprov.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemProviderInitSink::SetStatus

The IWbemProviderInitSink::SetStatus method indicates to Windows Management whether a provider is fully or partially initialized.

HRESULT IWbemProviderInitSink::SetStatus(
  LONG lStatus,
  LONG lFlags
);

Parameters

lStatus
[in] Indicates to Windows Management a provider's initialization status. One of the following values can be set:
Value | Description
WBEM_S_INITIALIZED | Indicates that the provider is fully initialized and ready to accept requests.
WBEM_E_FAILED | Indicates that the provider has failed to initialize and is not functional.

lFlags
[in] Reserved. It must be zero.

Return Values

Windows Management always returns WBEM_S_NO_ERROR.

Remarks

All types of providers calls IWbemProviderInitSink::SetStatus to indicate its initialization status to Windows Management.

If lStatus is set to WBEM_S_INITIALIZED, Windows Management expects the provider to be fully capable of immediately servicing requests.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemprov.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

Initializing a Provider


IWbemQualifierSet

The object that exports the IWbemQualifierSet interface acts as a container for the entire set of named qualifiers for a single property, Also, it can act as a container for an entire class object, instance, or class definition, depending on how the pointer was obtained. If the pointer was obtained from IWbemClassObject::GetQualifierSet, the object consists of the set of qualifiers for an entire object (a class or instance). If the pointer was obtained from IWbemClassObject::GetPropertyQualifierSet, then the object represents the qualifiers for a particular property.

Within WMI, this interface is always in-process. Put operations only affect the local copy of the object. Get operations retrieve values from the local copy. Updates are performed only when entire objects are read or written using methods on the IWbemServices interface.

It is strongly recommended that Windows Management dynamic providers never implement this interface. See IWbemClassObject for details.

IWbemQualifierSet Methods | Description
BeginEnumeration | Resets prior to an enumeration of all qualifiers.
Delete | Deletes the specified named qualifier.
EndEnumeration | Ends an enumeration of qualifiers.
Get | Reads a particular named qualifier.
GetNames | Gets the names of qualifiers subject to certain filters.
Next | Gets the next qualifier during an enumeration of all qualifiers.
Put | Writes a particular named qualifier.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemQualifierSet::Get

The IWbemQualifierSet::Get method gets the specified named qualifier, if found.

HRESULT IWbemQualifierSet::Get(
  LPCWSTR wszName,
  LONG lFlags,
  VARIANT *pVal,
  LONG *plFlavor
);

Parameters

wszName
[in] Name of the qualifier for which the value is being requested. The pointer is treated as read-only.
lFlags
[in] Reserved. It must be zero.
pVal
[out, OPTIONAL] When successful, VARIANT is assigned to the correct type and value for the qualifier. VariantInit is called on this VARIANT.

It is the responsibility of the caller to call VariantClear on the pointer when the value is no longer required. If there is an error code, the VARIANT pointed to by pVal is not modified.

If this parameter is NULL, the parameter is ignored.

plFlavor
[out, OPTIONAL] Can be NULL. If not NULL, this must point to a LONG that receives the qualifier flavor bits for the requested qualifier. See Qualifier Flavors.

Return Values

Value | Meaning
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_NOT_FOUND | The specified qualifier did not exist.
WBEM_S_NO_ERROR | The call succeeded.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

Qualifier Flavors


IWbemQualifierSet::Put

The IWbemQualifierSet::Put method writes the named qualifier and value. If the qualifier does not exist, it is created. The new qualifier overwrites the previously existing value of the same name.

In some cases, it is not possible to write the value of a qualifier if it was propagated from another object. Propagated qualifiers are generally read-only, but they can be overridden in some cases. See Qualifier Flavors.

When writing the Key qualifier, it is not necessary to specify any flavors or propagation rules.

The user may not create qualifiers with names that begin or end with an underscore. This is reserved for system classes and properties.

HRESULT IWbemQualifierSet::Put(
  LPCWSTR wszName,
  VARIANT *pVal,
  LONG lFlavor
);

Parameters

wszName
[in] The name of the qualifier that is being written. The pointer is treated as read-only.
pVal
[in] Cannot be NULL. This must point to a valid VARIANT that contains the qualifier value to be written. The pointer is treated as read-only. It is the caller's responsibility to call VariantClear on this pointer after the value is no longer needed.

Only variants of type VT_I4, VT_R8, VT_BSTR, VT_BOOL and arrays of types VT_BSTR, VT_I4, VT_R8, and VT_BOOL are supported.

lFlavor
[in] The desired qualifier flavor for this qualifier. See Qualifier Flavors.

Not required if the qualifier is the Key qualifier.

Return Values

Value | Meaning
WBEM_E_CANNOT_BE_KEY | There was an illegal attempt to specify the Key qualifier on a property that cannot be a key. The keys are specified in the class definition for an object, and cannot be altered on a per-instance basis.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_INVALID_QUALIFIER_TYPE | The pVal parameter is not of a legal qualifier type.
WBEM_E_OVERRIDE_NOT_ALLOWED | It is not possible to perform the IWbemQualifierSet::Put operation on this qualifier because the owning object does not permit overrides.
WBEM_S_NO_ERROR | The call succeeded.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

Qualifier Flavors


IWbemQualifierSet::Delete

The IWbemQualifierSet::Delete method deletes the specified qualifier by name. Due to qualifier propagation rules, a particular qualifier may have been inherited from another object and merely overridden in the current class or instance. In this case, use the Delete method to reset the qualifier to the original inherited value.

HRESULT IWbemQualifierSet::Delete(
  LPCWSTR wszName
);

Parameters

wszName
[in] The name of the qualifier to delete. The pointer is treated as read-only.

Return Values

Value | Meaning
WBEM_E_INVALID_OPERATION | Deleting this qualifier is illegal.
WBEM_E_INVALID_PARAMETER | The Name parameter was not valid.
WBEM_E_NOT_FOUND | The specified qualifier was not found.
WBEM_S_NO_ERROR | The call succeeded.
WBEM_S_RESET_TO_DEFAULT | When deleting an overridden qualifier, this status code (a non-error code) indicates that the local override was deleted, and that the original qualifier from the parent object has resumed scope. A subsequent attempt to get the qualifier will succeed, returning the parent's value.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

Qualifier Flavors


IWbemQualifierSet::GetNames

The IWbemQualifierSet::GetNames method retrieves the names of all of the qualifiers available from the current object or property. Alternately, depending on the filter value of IFlags, this method retrieves the names of certain qualifiers.

You can access these qualifiers by name, using IWbemQualifierSet::Get for each name. It is not an error for any given object to have zero qualifiers, so the number of strings in pstrNames on return can be zero, even though WBEM_S_NO_ERROR returns.

HRESULT IWbemQualifierSet::GetNames(
  LONG lFlags,
  SAFEARRAY (BSTR) **pstrNames
);

Parameters

lFlags
[in] One of the following constants.
Constant | Meaning
0 (Zero) | Return the names of all qualifiers.
WBEM_FLAG_LOCAL_ONLY | Return only the names of qualifiers specific to the current property or object. If the current qualifiers set refers to a property, return only the qualifiers specific to the property (including overrides), and not those qualifiers propagated from the class definition. If the current qualifiers set refers to an instance, return only instance-specific qualifier names. If the current qualifiers set refers to a class, return only qualifiers specific to the derived-most class.
WBEM_FLAG_PROPAGATED_ONLY | Return only the names of qualifiers propagated from another object. For example, if the current qualifier set refers to a property, return only the qualifiers propagated to this property from the class definition, and not those from the property itself. If the current qualifier set refers to an instance, return only those qualifiers propagated from the class definition. If the current qualifier set refers to a class, return only those qualifier names inherited from the superclasses.

pstrNames
[out] A new SAFEARRAY is created that contains the requested names.

In all cases where no error is returned, a new array is created and pstrNames is set to point to it. This occurs even though the resulting array has zero elements. On error, a new SAFEARRAY is not returned.

Return Values

Value | Meaning
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_S_NO_ERROR | The call succeeded.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemQualifierSet::Get, IWbemQualifierSet::BeginEnumeration

For an example of using SAFEARRAYs of BSTRs, see Displaying Instance Properties.


IWbemQualifierSet::BeginEnumeration

The IWbemQualifierSet::BeginEnumeration method resets before there is an enumeration of all the qualifiers in the object. To enumerate all of the qualifiers on an object, this method must be called before the first call to IWbemQualifierSet::Next. The order in which qualifiers are enumerated is guaranteed to be invariant for a given instance of IWbemQualifierSet.

HRESULT IWbemQualifierSet::BeginEnumeration(
  LONG lFlags
);

Parameters

lFlags
[in] Specifies the qualifiers to include in the enumeration. It must be one of the following constants.
Constant | Meaning
0 (Zero) | Return the names of all qualifiers.
WBEM_FLAG_LOCAL_ONLY | Return only the names of qualifiers specific to the current property or object. If the current qualifiers set refers to a property, return only the qualifiers specific to the property (including overrides), and not those qualifiers propagated from the class definition. If the current qualifiers set refers to an instance, return only instance-specific qualifier names. If the current qualifiers set refers to a class, return only qualifiers specific to the derived-most class.
WBEM_FLAG_PROPAGATED_ONLY | Return only the names of qualifiers propagated from another object. For example, if the current qualifier set refers to a property, return only the qualifiers propagated to this property from the class definition, and not those from the property itself. If the current qualifier set refers to an instance, only return those qualifiers propagated from the class definition. If the current qualifier set refers to a class, only return those qualifier names inherited from the superclasses.

Return Values

Value | Meaning
WBEM_E_INVALID_PARAMETER | The lFlags parameter was not valid.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_UNEXPECTED | A second call was made to IWbemQualifierSet::BeginEnumeration without an intervening call to IWbemQualifierSet::EndEnumeration.
WBEM_S_NO_ERROR | The call succeeded.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemQualifierSet::Next


IWbemQualifierSet::Next

The IWbemQualifierSet::Next method retrieves the next qualifier in an enumeration that started with IWbemQualifierSet::BeginEnumeration. This method is called repeatedly to enumerate all the qualifiers until WBEM_S_NO_MORE_DATA returns. To terminate the enumeration early, call IWbemQualifierSet::EndEnumeration.

The order of the qualifiers returned during the enumeration is not defined.

HRESULT IWbemQualifierSet::Next(
  LONG lFlags,
  BSTR *pstrName,
  VARIANT *pVal,
  LONG *plFlavor
);

Parameters

lFlags
[in] Reserved. It must be zero.
pstrName
[out, OPTIONAL] This parameter receives the name of the qualifier. A new BSTR is always allocated whenever WBEM_S_NO_ERROR returns.

If pstrName is NULL, it is ignored; otherwise the caller must ensure that this parameter does not point to a valid BSTR on entry, or else there will be a memory leak. Also, the caller must remember to call SysFreeString on the returned string when it is no longer required.

pVal
[out, OPTIONAL] This parameter receives the value for the qualifier. VariantInit is called on the VARIANT by this method. The caller must call VariantClear on this pointer when the value is no longer required. If an error code is returned, the VARIANT pointed to by pVal is left unmodified. This parameter will be ignored if set to NULL.
plFlavor
[out, OPTIONAL] If not NULL, the value pointed to is set to the qualifier flavor. See Qualifier Flavors.

Return Values

Value | Meaning
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_UNEXPECTED | Caller did not call IWbemQualifierSet::BeginEnumeration.
WBEM_S_NO_ERROR | The call succeeded.
WBEM_S_NO_MORE_DATA | No more qualifiers are left in the enumeration.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemQualifierSet::BeginEnumeration, IWbemQualifierSet::EndEnumeration, Qualifier Flavors


IWbemQualifierSet::EndEnumeration

Call the IWbemQualifierSet::EndEnumeration method when you plan to terminate enumerations which were initiated with IWbemQualifierSet::BeginEnumeration and IWbemQualifierSet::Next. This call is recommended, but not required. It immediately releases resources associated with the enumeration.

HRESULT IWbemQualifierSet::EndEnumeration( );

Parameters

None.

Return Values

Value | Meaning
WBEM_S_NO_ERROR | The call succeeded.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemQualifierSet::BeginEnumeration, IWbemQualifierSet::Next


IWbemRefresher

[This is preliminary documentation and subject to change.]

The IWbemRefresher interface provides an entry point through which refreshable objects, enumerators, and other refreshers can be refreshed. Implementers of IWbemHiPerfProvider must provide an implementation of this interface.

WMI supplies a client-side implementation of this interface. Clients can access this interface by calling CoCreateInstance on CLSID_WbemRefresher. This is the only supported implementation on the client side.

IWbemRefresher Method | Description
Refresh | Updates information in this refresher.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemRefresher::Refresh

[This is preliminary documentation and subject to change.] The Refresh method updates all refreshable objects, enumerators, and nested refreshers.

HRESULT IWbemRefresher::Refresh(
  long lFlags
);

Parameters

lFlags
[in] A bitmask of flags that modify the behavior of this method.

If WBEM_FLAG_REFRESH_AUTO_RECONNECT is specified and if the connection is broken, the refresher attempts to reconnect to the provider automatically. This is the default behavior for this method.

If you do not want the refresher to attempt to reconnect to the provider, specify WBEM_FLAG_REFRESH_NO_AUTO_RECONNECT.

Return Values

If the Refresh method is successful, it returns WBEM_S_NO_ERROR; otherwise, this method returns an HRESULT with one of the following values.

Value | Meaning
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_S_PARTIAL_RESULTS | Not all of the objects, enumerators, or nested refreshers were successfully updated.
WBEM_E_REFRESHER_BUSY | The refresher is busy with another operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemRefresher Interface


IWbemServices

Windows Management implements the IWbemServices interface. It is used by clients and providers to access WMI services. It is also used by class and instance dynamic providers. This interface provides management services to client processes and to other providers.

Note Providers implementing this interface must follow the documented semantics of each method that they implement. Also, providers must support the specified error return codes. While Windows Management implements all of the methods, each provider usually implements a small subset of the available functionality on this interface. A provider must return WBEM_E_PROVIDER_NOT_CAPABLE for any method that it does not implement.

All outbound interface pointers from any IWbemServices method should be initialized to NULL before calling the interface method. For example, IWbemServices::GetObject returns an IWbemClassObject interface pointer. This pointer should be pre-initialized to NULL (or zero) before making the call:

    IWbemClassObject *pObj = 0;
    pWbemSvc->GetObject(strPath, 0, 0, &pObj, 0);
IWbemServices Methods | Description
CancelAsyncCall | Cancels a currently executing asynchronous call.
CreateClassEnum | Creates a class enumerator.
CreateClassEnumAsync | Creates a class enumerator that executes asynchronously.
CreateInstanceEnum | Creates an instance enumerator.
CreateInstanceEnumAsync | Creates an instance enumerator that executes asynchronously.
DeleteClass | Deletes a class.
DeleteClassAsync | Deletes a class and receives confirmation asynchronously.
DeleteInstance | Deletes a particular instance of a class.
DeleteInstanceAsync | Deletes an instance and provides confirmation asynchronously.
ExecMethod | Executes an object method.
ExecMethodAsync | Executes an object method asynchronously.
ExecNotificationQuery | Executes a query to receive events.
ExecNotificationQueryAsync | Executes a query to receive events asynchronously.
ExecQuery | Executes a query to retrieve classes or instances.
ExecQueryAsync | Executes a query to retrieve classes or instances asynchronously.
GetObject | Retrieves an object, whether an instance or class definition.
GetObjectAsync | Asynchronously retrieves an object (an instance or class definition).
OpenNamespace | Opens a particular child namespace for operations.
PutClass | Creates or updates a class definition.
PutClassAsync | Asynchronously creates or updates a class definition.
PutInstance | Creates or updates an instance of a particular class.
PutInstanceAsync | Asynchronously creates or updates an instance of a particular class.
QueryObjectSink | Allows the caller to obtain a notification handler sink.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemServices::OpenNamespace

The IWbemServices::OpenNamespace method provides the caller with a new IWbemServices pointer that has the specified child namespace as its operating context. All operations through the new pointer, such as class or instance creation, only affect that namespace. The namespace must be a child namespace of the current object through which this method is called.

HRESULT IWbemServices::OpenNamespace(
  const BSTR strNamespace,
  LONG lFlags,
  IWbemContext *pCtx,
  IWbemServices **ppWorkingNamespace,
  IWbemCallResult **ppResult
);

Parameters

strNamespace
[in] The object path to the target namespace. See Namespaces. This namespace can only be relative to the current namespace associated with the IWbemServices interface pointer. This parameter cannot be an absolute path or NULL.
lFlags
[in] This parameter can be set to zero to make this a synchronous call. Otherwise, to make this a semisynchronous call set lFlags to WBEM_FLAG_RETURN_IMMEDIATELY, provide a valid pointer for the ppResult parameter and this call will return immediately. See Making a Semisynchronous Call for more information on semisynchronous calls.
pCtx
[in] Reserved. It must be NULL.
ppWorkingNamespace
[out, OPTIONAL] Receives the object representing the new namespace context. The returned pointer has a positive reference count. The caller must call Release on this pointer when it is no longer needed. This pointer is set to NULL when there are errors. If this parameter is specified, then ppResult must be NULL.
ppResult
[out, OPTIONAL] Typically NULL. If not NULL, then ppWorkingNamespace must be NULL. In this case, the parameter receives a pointer to a new IWbemCallResult object. If the lFlags parameter is set to WBEM_FLAG_RETURN_IMMEDIATELY this call will return immediately. Then the caller can periodically poll the IWbemCallResult::GetResultServices method until the pointer for the requested namespace becomes available. This parameter is set to point to NULL when there is an error and a new object is not returned.

Note It is important to note that when you use this parameter, you must set ppResult to point to NULL before calling the method. This is a DCOM rule.

Return Values

Value | Meaning
WBEM_E_ACCESS_DENIED | The user does not have permission to access the requested namespace.
WBEM_E_FAILED | This indicates other unspecified errors.
WBEM_E_INVALID_NAMESPACE | The specified namespace does not exist.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified or the namespace could not be parsed.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_TRANSPORT_FAILURE | The communications link between the current process and Windows Management has failed.
WBEM_S_NO_ERROR | The call succeeded.

On failure, you can obtain any available information from the COM function GetErrorInfo.

DCOM-specific error codes may also be returned if network problems cause you to lose the remote connection to Windows Management.

Remarks

IWbemLocator::ConnectServer can also be used to open the same namespace. The only difference is that the OpenNamespace method allows you to place relative object paths in the Namespace parameter to open child namespaces recursively. IWbemLocator::ConnectServer requires a full object path. See Object Paths.

For example, if the current namespace associated with the IWbemServices interface pointer is Root, then using Default in the Namespace parameter yields a new pointer bound to the Root\Default namespace.

The namespace is closed when Release is called and the reference count reaches zero.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

Error Objects, IWbemLocator::ConnectServer, Namespaces


IWbemServices::CancelAsyncCall

The IWbemServices::CancelAsyncCall method cancels any currently pending asynchronous call based on the IWbemObjectSink pointer originally passed to the asynchronous method. Before this method returns, it calls the Release method on the outstanding IWbemObjectSink pointer that was passed to the original asynchronous call. CancelAsyncCall is not operational from within a sink.

HRESULT IWbemServices::CancelAsyncCall(
  IWbemObjectSink *pSink
);

Parameters

pSink
[in] The pointer to the IWbemObjectSink implementation provided by the client to any of the asynchronous methods of IWbemServices.

Return Values

Value | Meaning
WBEM_E_FAILED | This is an unspecified error.
WBEM_E_INVALID_PARAMETER | The supplied interface in pSink did not correspond to a pending asynchronous request
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_TRANSPORT_FAILURE | This indicates the failure of the remote procedure call (RPC) link between the current process and Windows Management.
WBEM_S_NO_ERROR | The call succeeded.

On failure, you can obtain any available information from the COM function GetErrorInfo.

DCOM-specific error codes also may be returned if network problems cause you to lose the remote connection to Windows Management.

Note It is possible to make numerous asynchronous calls using the same object sink. In this case, the IWbemServices::CancelAsyncCall method will cancel all asynchronous calls sharing this object sink. It is strongly recommend that there is one instance of the of an object sink for each asynchronous call outstanding.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

Asynchronous Methods, IWbemObjectSink


IWbemServices::QueryObjectSink

The IWbemServices::QueryObjectSink method allows the caller to obtain a notification handler that is exported by Windows Management. This allows the caller to write notifications and events directly to Windows Management. The caller should only write extrinsic events to Windows Management. See Event Notification.

HRESULT IWbemServices::QueryObjectSink(
  LONG lFlags,
  IWbemObjectSink **ppResponseHandler
);

Parameters

lFlags
[in] Reserved. It must be zero.
ppResponseHandler
[out] Receives the interface pointer to the notification handler. This is set to point to NULL when there is an error. The returned pointer has a positive reference count, and the caller must call IWbemServices::Release on the pointer when it is no longer needed. A NULL value can be returned if no notification handler is available. This is not an error.

Note The value of the ppResponseHandler parameter must not be NULL when it is passed to this method.

Return Values

Value | Meaning
WBEM_E_ACCESS_DENIED | The caller does not have permission to provide notifications to Windows Management.
WBEM_E_FAILED | This is an unspecified error.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_TRANSPORT_FAILURE | This indicates the failure of the remote procedure call (RPC) link between the current process and Windows Management.
WBEM_S_NO_ERROR | The call succeeded.

DCOM-specific error codes also may be returned if network problems cause you to lose the remote connection to Windows Management.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

Event Notification, IWbemObjectSink


IWbemServices::GetObject

The IWbemServices::GetObject method retrieves a class or instance.

This method only retrieves objects from the namespace associated with the current IWbemServices object.

HRESULT IWbemServices::GetObject(
  const BSTR strObjectPath,
  LONG lFlags,
  IWbemContext *pCtx,
  IWbemClassObject **ppObject,
  IWbemCallResult **ppCallResult
);

PEarameters

strObjectPath
[in] The object path of the object to retrieve. If this is NULL, an empty object is returned that can become a new class. See Class Creation.
lFlags
[in] The following flags affect the behavior of this method
Flag | Description
WBEM_FLAG_USE_AMENDED_QUALIFIERS | If this flag is set, WMI will retrieve the amended qualifiers stored in the localized namespace of the current connection's locale. If not set, only the qualifiers stored in the immediate namespace will be retrieved.
WBEM_FLAG_RETURN_WBEM_COMPLETE | This flag makes this a synchronous call.
WBEM_FLAG_RETURN_IMMEDIATELY | This flag makes this a semisynchronous call. You must provide a valie pointer for the ppCallResult parameter. See Making a Semisynchronous Call for more information on semisynchronous calls.
WBEM_FLAG_DIRECT_READ | This flag causes direct access to the provider (or repository) for the class specified without any regard to its superclass or subclasses.
pCtx
[in] Typically NULL. Otherwise, this is a pointer to an IWbemContext object that may be used by the provider that is producing the requested class or instance. The values in the context object must be specified in the documentation for the provider in question. See Making Calls to WMI for more information about this parameter.
ppObject
[out, OPTIONAL] If not NULL, this receives the object, if it is found. The returned object has a positive reference count. The caller must use Release when the object is no longer needed. In all cases of error, this parameter is set to point to NULL.
ppCallResult
[out, OPTIONAL] If NULL, this parameter is not used. If the lFlags parameter contains WBEM_FLAG_RETURN_IMMEDIATELY, this call will return immediately with WBEM_S_NO_ERROR. The ppCallResult parameter will receive a pointer to a new IWbemCallResult object, which can then be polled to obtain the result using the GetCallStatus method. The caller can call IWbemCallResult::GetResultObject to retrieve the object when it becomes available.

Return Values

Value | Meaning
WBEM_E_ACCESS_DENIED | The current user does not have permission to access the object.
WBEM_E_FAILED | This indicates other unspecified errors.
WBEM_E_INVALID_CLASS | The specified class does not exist.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_INVALID_OBJECT_PATH | The specified path was invalid.
WBEM_E_NOT_FOUND | The requested object could not be found.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_TRANSPORT_FAILURE | This indicates the failure of the remote procedure call (RPC) link between the current process and Windows Management.
WBEM_S_NO_ERROR | The call succeeded.

On failure, you can obtain any available information from the COM function GetErrorInfo.

DCOM-specific error codes also may be returned if network problems cause you to lose the remote connection to Windows Management.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

Class Creation, Error Handling for Applications, IWbemCallResult, IWbemServices::GetObjectAsync, Object Paths


IWbemServices::GetObjectAsync

The IWbemServices::GetObjectAsync method retrieves an object, either a class definition or instance, based on its path. This is similar to IWbemServices::GetObject except that the call returns immediately, and the object is provided to the supplied object sink.

Currently, this method retrieves objects only from the namespace associated with the IWbemServices pointer.

HRESULT IWbemServices::GetObjectAsync(
  const BSTR strObjectPath,
  LONG lFlags,
  IWbemContext *pCtx,
  IWbemObjectSink *pResponseHandler
);

Parameters

strObjectPath
[in] The object path of the object to retrieve. If this is NULL, an empty object, which can become a new class, is returned. See Class Creation.
lFlags
[in] The following flags affect the behavior of this method
Flag | Description
WBEM_FLAG_USE_AMENDED_QUALIFIERS | If this flag is set, WMI will retrieve the amended qualifiers stored in the localized namespace of the current connection's locale. If not set, only the qualifiers stored in the immediate namespace will be retrieved.
WBEM_FLAG_DIRECT_READ | This flag causes direct access to the provider (or repository) for the class specified without any regard to its superclass or subclasses.
WBEM_FLAG_SEND_STATUS | Registers a request to receive intermediate status reports through the client's implementation of IWbemObjectSink::SetStatus.
pCtx
[in] Typically NULL. Otherwise, this is a pointer to an IWbemContext object that may be used by the provider that is producing the requested class or instance. The values in the context object must be specified in the documentation for the provider in question. See Making Calls to WMI for more information about this parameter.
pResponseHandler
[in] Points to the caller's implementation of IWbemObjectSink. This handler receives the requested object when it becomes available through the IWbemObjectSink::Indicate method. The pObjParam parameter contains the object. If any error code is returned, then the supplied IWbemObjectSink pointer will not be used. If WBEM_S_NO_ERROR is returned, then the user's IWbemObjectSink implementation will be called to indicate the result of the operation. Windows Management only calls AddRef to the pointer in cases where WBEM_S_NO_ERROR returns. In cases where an error code returns, the reference count is the same as on entry. For a detailed explanation of this parameter, see also Asynchronous Methods.

Return Values

Value | Meaning
WBEM_E_FAILED | Other error codes are returned asynchronously to the IWbemObjectSink.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_INVALID_CLASS | The specified class does not exist.
WBEM_E_INVALID_OBJECT_PATH | The specified object path was invalid.
WBEM_S_NO_ERROR | The call succeeded.

On failure, you can obtain any available information from the COM function GetErrorInfo.

DCOM-specific error codes also may be returned if network problems cause you to lose the remote connection to Windows Management.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

Making an Asynchronous Call, Class Creation, IWbemServices::GetObject, Object Paths


IWbemServices::PutClass

The IWbemServices::PutClass method creates a new class or updates an existing one. The class specified by the pObject parameter must have been correctly initialized with all of the required property values.

The user may not create classes with names that begin or end with an underscore. This is reserved for system classes.

HRESULT IWbemServices::PutClass(
  IWbemClassObject *pObject,
  LONG lFlags,
  IWbemContext *pCtx,
  IWbemCallResult **ppCallResult
);

Parameters

pObject
[in] Must point to a valid class definition. The reference count is not changed.
lFlags
[in] The following flags affect the behavior of this method.
Flag | Description
WBEM_FLAG_USE_AMENDED_QUALIFIERS | If this flag is set, WMI will not store any qualifiers with the amended flavor. If this flag is not set, it is assumed that this object is not localized, and all qualifiers are stored with this instance.
WBEM_FLAG_CREATE_OR_UPDATE | This flag causes the class to be created if it does not exist, or overwritten if it exists already.
WBEM_FLAG_UPDATE_ONLY | This flag causes this call to update. The class must exist for the call to be successful.
WBEM_FLAG_CREATE_ONLY | This flag is used for creation only. The call will fail if the class already exists.
WBEM_FLAG_RETURN_IMMEDIATELY | This flag causes this to be a semisychronous call. See Making a Semisynchronous Call for more information on semisynchronous calls.
WBEM_FLAG_OWNER_UPDATE | Push providers must specify this flag when calling PutClass, to indicate that this class has changed.
WBEM_FLAG_UPDATE_COMPATIBLE | This flag allows a class to be updated if there are no derived classes and there are no instances for that class. It also allows updates in all cases if the change is just to non-important qualifiers (for example, the Description qualifier). This is the default behavior for this call and is used for compatibility with previous versions of Windows Management. If the class has instances and changes are to important qualifiers, the update will fail.
WBEM_FLAG_UPDATE_SAFE_MODE | This flag allows updates of classes even if there are child classes as long as the change does not cause any conflicts with child classes. An example of an update this flag would allow would be to add a new property to the base class that was not previously mentioned in any of the child classes. If the class has instances, the update will fail.
WBEM_FLAG_UPDATE_FORCE_MODE | This flag forces updates of classes when conflicting child classes exist. An example of an update this flag would force would be if a class qualifier was defined in a child class, and the base class tried to add the same qualifier and it conflicted with the existing one. In force mode, this conflict would be resolved by deleting the conflicting qualifier in the child class.

pCtx
[in] Typically NULL. Otherwise, this is a pointer to an IWbemContext object required by the dynamic class provider that is producing the class instances. The values in the context object must be specified in the documentation for the provider in question. See Making Calls to WMI for more information about this parameter.
ppCallResult
[out, OPTIONAL] If NULL, this parameter is not used. If the lFlags parameter contains WBEM_FLAG_RETURN_IMMEDIATELY, this call will return immediately with WBEM_S_NO_ERROR. The ppCallResult parameter will receive a pointer to a new IWbemCallResult object, which can then be polled to obtain the result using the IWbemCallResult::GetCallStatus method.

Return Values

Value | Meaning
WBEM_E_ACCESS_DENIED | The current user is not permitted to create or modify classes.
WBEM_E_FAILED | This indicates other unspecified errors.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_INVALID_CLASS | The class specified is invalid. You will see this error if a instance object is specified in the pObject parameter.
WBEM_E_INVALID_OPERATION | The class name specified is not valid.
WBEM_E_CLASS_HAS_CHILDREN | An attempt was made to make a change that would invalidate a subclass.
WBEM_E_INCOMPLETE_CLASS | The required properties for classes have not all been set.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_TRANSPORT_FAILURE | This indicates the failure of the remote procedure call (RPC) link between the current process and Windows Management.
WBEM_S_NO_ERROR | The call succeeded.
WBEM_E_ALREADY_EXISTS | WBEM_FLAG_CREATE_ONLY flag was specified, but the class already exists.
WBEM_E_NOT_FOUND | WBEM_FLAG_UPDATE_ONLY was specified in lFlags, and the class was not found.

On failure, you can obtain any available information from the COM function GetErrorInfo.

DCOM-specific error codes also may be returned if network problems cause you to lose the remote connection to Windows Management.

Note Unpredictable behavior will result if you change class definitions while they are in use by clients or providers. IWbemServices::PutClass should only be used to create or update a class when there are no clients or providers currently using the class.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

Class Creation and Modification Rules, Error Handling for Applications, IWbemCallResult


IWbemServices::PutClassAsync

The IWbemServices::PutClassAsync method creates a new class, or it updates an existing one. The class specified by the pObject parameter must be correctly initialized with all of the required property values. The call immediately returns. Success or failure is supplied to the object sink specified by the pResponseHandler parameter.

HRESULT IWbemServices::PutClassAsync(
  IWbemClassObject *pObject,
  LONG lFlags,
  IWbemContext *pCtx,
  IWbemObjectSink *pResponseHandler
);

Parameters

pObject
[in] Points to the object containing the class definition.
lFlags
[in]
Flag | Description
WBEM_FLAG_USE_AMENDED_QUALIFIERS | If this flag is set, WMI does not store any qualifiers with the amended flavor. If this flag is not set, it is assumed that this object is not localized, and all qualifiers are stored with this instance.
WBEM_FLAG_CREATE_OR_UPDATE | This flag causes this class to be created if it does not exist or be overwritten if it exists already.
WBEM_FLAG_UPDATE_ONLY | Updates an existing class.
WBEM_FLAG_CREATE_ONLY | This flag is for class creation only. The call will fail if the class already exists.
WBEM_FLAG_SEND_STATUS | This flag registers with Windows Management a request to receive intermediate status reports through the clients implementation of IWbemObjectSink::SetStatus.
WBEM_FLAG_OWNER_UPDATE | Push providers must specify this flag when calling PutClassAsync to indicate that this class has changed.
WBEM_FLAG_UPDATE_COMPATIBLE | This flag allows a class to be updated if there are no derived classes and there are on instances for that class. It also allows updates in all cases if the change is just to non-important qualifiers (for example, the Description qualifier). This is the default behavior for this call and is used for compatibility with previous versions of Windows Management. If the class has instances and changes are to important qualifiers, the update will fail.
WBEM_FLAG_UPDATE_SAFE_MODE | This flag allows updates of classes even if there are child classes, as long as the change does not cause any conflicts with child classes. An example of an update this flag would allow would be to add a new property to the base class that was not previously mentioned in any of the child classes. If the class has instances, the update will fail.
WBEM_FLAG_UPDATE_FORCE_MODE | This flag forces updates of classes when conflicting child classes exist. An example of an update this flag would force would be if a class qualifier was defined in a child class, and the base class tried to add the same qualifier and it conflicted with the existing one. In force mode, this conflict would be resolved by deleting the conflicting qualifier in the child class.

pCtx
[in] Typically NULL. Otherwise, this is a pointer to an IWbemContext object that may be used by the provider that is receiving the requested class. The values in the context object must be specified in the documentation for the provider in question. See Making Calls to WMI for more information about this parameter.
pResponseHandler
[in] Points to the caller's implementation of IWbemObjectSink. This handler receives the status of the Put request when the status becomes available using the SetStatus method. If any error code is returned, then the supplied IWbemObjectSink pointer will not be used. If WBEM_S_NO_ERROR is returned, then the user's IWbemObjectSink implementation will be called to indicate the result of the operation. Windows Management only calls AddRef to the pointer in cases where WBEM_S_NO_ERROR returns. In cases where an error code returns, the reference count is the same as on entry. For a detailed explanation of this parameter, see Making an Asynchronous Call.

Return Values

Value | Meaning
WBEM_E_ACCESS_DENIED | The current user does not have permission to create classes.
WBEM_E_ALREADY_EXISTS | WBEM_FLAG_CREATE_ONLY flag was specified, but the class already exists.
WBEM_E_FAILED | This is an unspecified failure.
WBEM_E_INVALID_CLASS | The class specified is invalid. You will see this error if a instance object is specified in the pObject parameter.
WBEM_E_INVALID_OPERATION | The class name specified is not valid.
WBEM_E_CLASS_HAS_CHILDREN | An attempt was made to make a change that would invalidate a subclass.
WBEM_E_INCOMPLETE_CLASS | The required properties for classes have not all been set.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_NOT_FOUND | WBEM_FLAG_UPDATE_ONLY flag was specified, but the class does not exist.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_TRANSPORT_FAILURE | This indicates the failure of the remote procedure call (RPC) link between the current process and Windows Management.
WBEM_S_NO_ERROR | The call succeeded.

Other status or error codes are reported to the object sink specified by the pReponseHandler parameter.

DCOM-specific error codes also may be returned if network problems cause you to lose the remote connection to Windows Management.

Note Unpredictable behavior will result if you change class definitions while they are in use by clients or providers. IWbemServices::PutClass should only be used to create or update a class when there are no clients or providers currently using the class.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

Making an Asynchronous Call, Class Creation and Modification Rules, IWbemServices::PutClass


IWbemServices::DeleteClass

The IWbemServices::DeleteClass method deletes the specified class from the current namespace. If a dynamic instance provider is associated with the class, the provider is unregistered, and it is no longer called for by that class. Any classes that derive from the deleted class are also deleted, and their associated providers are unregistered. All outstanding static instances of the specified class and its subclasses are also deleted when the class is deleted.

If a dynamic class provider provides the class, the success of the deletion depends on whether the provider supports class deletion.

Note System classes cannot be deleted.

HRESULT IWbemServices::DeleteClass(
  const BSTR strClass,
  LONG lFlags,
  IWbemContext *pCtx,
  IWbemCallResult **ppCallResult
);

Parameters

strClass
[in] The name of the class targeted for deletion.
lFlags
[in] One of the following values can be set.
Flag | Description
WBEM_FLAG_RETURN_IMMEDIATELY | This flag causes this to be a semisychronous call. See Making a Semisynchronous Call for more information on semisynchronous calls.
WBEM_FLAG_OWNER_UPDATE | Indicates that the caller is a push provider.

pCtx
[in] Typically NULL. Otherwise, this is a pointer to an IWbemContext object that may be used by the provider that is deleting the class. The values in the context object must be specified in the documentation for the provider in question. See Making Calls to WMI for more information about this parameter.
ppCallResult
[out, OPTIONAL] If NULL, this parameter is not used. If ppCallResult is specified, it must be set to point to NULL on entry. If the lFlags parameter contains WBEM_FLAG_RETURN_IMMEDIATELY, this call will return immediately with WBEM_S_NO_ERROR. The ppCallResult parameter will receive a pointer to a new IWbemCallResult object, which can then be polled to obtain the result using the GetCallStatus method.

Return Values

Value | Meaning
WBEM_E_ACCESS_DENIED | The current user does not have permission to delete classes.
WBEM_E_FAILED | This indicates other unspecified errors.
WBEM_E_INVALID_CLASS | The specified class does not exist.
WBEM_E_CLASS_HAS_CHILDREN | Deleting this class would invalidate a subclass.
WBEM_E_INVALID_OPERATION | Deletion is not supported for the specified class. It may have been a system class or a class supplied by a dynamic provider that does not support class deletion.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_TRANSPORT_FAILURE | This indicates the failure of the remote procedure call (RPC) link between the current process and Windows Management.
WBEM_S_NO_ERROR | The call succeeded.

On failure, you can obtain any available information from the COM function GetErrorInfo.

DCOM-specific error codes may also be returned if network problems cause you to lose the remote connection to Windows Management.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

Error Handling for Applications, IWbemServices::DeleteClassAsync


IWbemServices::DeleteClassAsync

The IWbemServices::DeleteClassAsync method deletes the specified class from the current namespace. This method is identical to IWbemServices::DeleteClass except that the call returns immediately. Confirmation or failure is asynchronously reported to the specified object sink using the IWbemObjectSink::SetStatus method after the operation is complete.

HRESULT IWbemServices::DeleteClassAsync(
  const BSTR strClass,
  LONG lFlags,
  IWbemContext *pCtx,
  IWbemObjectSink *pResponseHandler
);

Parameters

strClass
[in] The name of the class targeted for deletion.
lFlags
[in]
Flag | Description
WBEM_FLAG_SEND_STATUS | This flag registers with Windows Management a request to receive intermediate status reports through the clients implementation of IWbemObjectSink::SetStatus.
WBEM_FLAG_OWNER_UPDATE | Push providers must specify this flag when calling DeleteClassAsync to indicate that this class has changed.

pCtx
[in] Typically NULL. Otherwise, this is a pointer to an IWbemContext object that may be used by the provider that is deleting the class. The values in the context object must be specified in the documentation for the provider in question. See Making Calls to WMI for more information about this parameter.
pResponseHandler
[in] Points to an implementation of IWbemObjectSink implemented by the caller. This handler receives the status of the deletion request when it becomes available through the IWbemObjectSink::SetStatus method. If any error code is returned, then the supplied IWbemObjectSink pointer will not be used. If WBEM_S_NO_ERROR is returned, then the user's IWbemObjectSink implementation will be called to indicate the result of the operation. Windows Management only calls AddRef on the pointer in cases where WBEM_S_NO_ERROR returns. In cases where an error code returns, the reference count is the same as on entry. For a detailed explanation of this parameter, see Making an Asynchronous Call.

Return Values

Value | Meaning
WBEM_E_FAILED | This indicates other unspecified failures.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_CLASS_HAS_CHILDREN | Deleting this class would invalidate a subclass.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_TRANSPORT_FAILURE | This indicates the failure of the remote procedure call (RPC) link between the current process and Windows Management.
WBEM_S_NO_ERROR | The call succeeded.

All other return codes are provided to the object sink specified by the pReponseHandler parameter through the SetStatus method. Error conditions, such as when the class does not exist or the user does not have permission to delete classes, are reported to the handler. They are not reported in the return code of this method.

DCOM-specific error codes also may be returned if network problems cause you to lose the remote connection to Windows Management.

Remarks

If a dynamic instance provider is associated with the class, the provider is unregistered, and is no longer called for that class. Any classes that derive from the deleted class are also deleted, and their associated providers become unregistered. All outstanding static instances of the specified class and its subclasses are also deleted when the class is deleted.

If the class is provided by a dynamic class provider, the success of the deletion depends on whether class deletion is supported by that provider.

Note Standard system classes cannot be deleted.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

Error Handling for Applications, Making an Asynchronous Call, IWbemServices::DeleteClass


IWbemServices::CreateClassEnum

The IWbemServices::CreateClassEnum method returns an enumerator for all classes satisfying the selection criteria.

The caller must then use the returned enumerator to retrieve the class definitions, calling IEnumWbemClassObject::Next to obtain each class or blocks of classes. It finishes by calling IEnumWbemClassObject::Release.

Note It is not an error for the returned enumerator to have zero elements.

HRESULT IWbemServices::CreateClassEnum(
  const BSTR strSuperclass,
  LONG lFlags,
  IWbemContext *pCtx,
  IEnumWbemClassObject **ppEnum
);

Parameters

strSuperclass
[in] If not NULL or blank, specifies a superclass name. Only classes that are subclasses of this class are returned in the enumerator. If it is NULL or blank, and lFlags is WBEM_FLAG_SHALLOW, only the top-level classes, that is, classes that have no parent class or superclass, are returned. If it is NULL or blank and lFlags is WBEM_FLAG_DEEP, all classes within the namespace are returned.
lFlags
[in] The following flags affect the behavior of this method. The suggested value for this parameter is WBEM_FLAG_RETURN_IMMEDIATELY and WBEM_FLAG_FORWARD_ONLY for best performance.
Flag | Description
WBEM_FLAG_USE_AMENDED_QUALIFIERS | If this flag is set, WMI will retrieve the amended qualifiers stored in the localized namespace of the current connection's locale. If not set, only the qualifiers stored in the immediate namespace will be retrieved.
WBEM_FLAG_DEEP | This flag forces the enumeration to include all classes in the hierarchy.
WBEM_FLAG_SHALLOW | This flag forces the enumeration to include only immediate subclasses of the specified superclass.
WBEM_FLAG_RETURN_IMMEDIATELY | This flag causes this to be a semisychronous call. See Making a Semisynchronous Call for more information on semisynchronous calls.
WBEM_FLAG_FORWARD_ONLY | This flag causes a forward-only enumerator to be returned. Forward-only enumerators are generally much faster and use less memory than conventional enumerators but do not allow calls to Clone or Reset.
WBEM_FLAG_BIDIRECTIONAL | This flag causes Windows Management to retain pointers to objects of the enumeration until the client releases the enumerator. Because object pointers are not released immediately, this method may fail with a hResult of WBEM_E_OUT_OF_MEMORY if the client attempts to enumerate a large number of objects. This flag is implied by default if you set the lFlags parameter to 0.

pCtx
[in] Typically NULL. Otherwise, this is a pointer to an IWbemContext object that may be used by the provider that is providing the requested classes. The values in the context object must be specified in the documentation for the provider in question. See Making Calls to WMI for more information about this parameter.
ppEnum
[out] Receives the pointer to the enumerator. The returned object has a positive reference count. The caller must call Release on the pointer when it is no longer required.

Return Values

Value | Meaning
WBEM_E_ACCESS_DENIED | The current user does not have permission to view one or more of the classes that the call can return.
WBEM_E_FAILED | This indicates other unspecified errors.
WBEM_E_INVALID_CLASS | The specified class does not exist.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_TRANSPORT_FAILURE | This indicates the failure of the remote procedure call (RPC) link between the current process and Windows Management.
WBEM_S_NO_ERROR | The call succeeded.

On failure, you can obtain any available information from the COM function GetErrorInfo.

DCOM-specific error codes also may be returned if network problems cause you to lose the remote connection to Windows Management.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

Error Handling for Applications, IWbemServices::CreateClassEnumAsync, IEnumWbemClassObject


IWbemServices::CreateClassEnumAsync

The IWbemServices::CreateClassEnumAsync method performs the same function as IWbemServices::CreateClassEnum except that the classes are asynchronously provided to the specified response handler.

In cases where the call succeeds, Windows Management calls AddRef on the pointer pResponseHandler, and then returns immediately. It then asynchronously calls pResponseHandler – >Indicate from another thread with class definitions until the query has been satisfied.

HRESULT IWbemServices::CreateClassEnumAsync(
  const BSTR strSuperclass,
  LONG lFlags,
  IWbemContext *pCtx,
  IWbemObjectSink *pResponseHandler
);

Parameters

strSuperclass
[in] If not NULL or blank, this parameter specifies a superclass name. Only classes that are subclasses of this class are returned in the enumerator. If NULL or blank, and lFlags is WBEM_FLAG_SHALLOW, only top-level classes, that is, those which have no parent class or superclass, are returned. If it is NULL or blank and lFlags is WBEM_FLAG_DEEP, all classes within the namespace are returned.
lFlags
[in]
Flag | Description
WBEM_FLAG_USE_AMENDED_QUALIFIERS | If this flag is set, WMI will retrieve the amended qualifiers stored in the localized namespace of the current connection's locale. If not set, only the qualifiers stored in the immediate namespace will be retrieved.
WBEM_FLAG_FORWARD_ONLY | This flag causes a forward-only enumerator to be returned. Forward-only enumerators are generally much faster and use less memory than conventional enumerators but do not allow calls to Clone or Reset.
WBEM_FLAG_BIDIRECTIONAL | This flag causes Windows Management to retain pointers to objects of the enumeration until the client releases the enumerator.
WBEM_FLAG_DEEP | This flag forces recursive enumeration into all subclasses derived from the specified superclass
WBEM_FLAG_SHALLOW | This flag forces the enumeration to include only immediate subclasses of the specified superclass.
WBEM_FLAG_SEND_STATUS | This flag registers with Windows Management a request to receive intermediate status reports through the clients implementation of IWbemObjectSink::SetStatus.

Note If strSuperclass is NULL or blank and WBEM_FLAG_DEEP is specified, all classes are returned.

pCtx
[in] Typically NULL. Otherwise, this is a pointer to an IWbemContext object that may be used by the provider that is returning the requested classes. The values in the context object must be specified in the documentation for the provider in question. See Making Calls to WMI for more information about this parameter.
pResponseHandler
[in] Points to the caller's implementation of IWbemObjectSink. This handler receives the objects as they become available using the IWbemObjectSink::Indicate method. When no more objects are available, the IWbemObjectSink::SetStatus method is called by Windows Management. If any error code is returned, then the supplied IWbemObjectSink pointer will not be used. If WBEM_S_NO_ERROR is returned, then the user's IWbemObjectSink implementation will be called to indicate the result of the operation. Windows Management only calls AddRef on the pointer in cases where WBEM_S_NO_ERROR returns. In cases where an error code returns, the reference count is the same as on entry. For a detailed explanation of this parameter, see Asynchronous Methods.

Return Values

Value | Meaning
WBEM_E_FAILED | This is an unspecified error.
WBEM_E_INVALID_CLASS | The specified class does not exist.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_TRANSPORT_FAILURE | This indicates the failure of the remote procedure call (RPC) link between the current process and Windows Management.
WBEM_S_NO_ERROR | The call succeeded.

On failure, you can obtain available information from the COM function GetErrorInfo.

DCOM-specific error codes also may be returned if network problems cause you to lose the remote connection to Windows Management.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

Error Handling for Applications,Making an Asynchronous Call, IWbemServices::CreateClassEnum, IWbemObjectSink


IWbemServices::PutInstance

The IWbemServices::PutInstance method creates or updates an instance of an existing class. The instance is written to the CIM repository.

HRESULT IWbemServices::PutInstance(
  IWbemClassObject *pInst,
  LONG lFlags,
  IWbemContext *pCtx,
  IWbemCallResult **ppCallResult
);

Parameters

pInst
[in] Points to the instance to be written. The caller cannot make assumptions about the reference count at the completion of this call.
lFlags
[in] One or more of the following values can be set.
Flag | Description
WBEM_FLAG_CREATE_OR_UPDATE | This flag causes the instance to be created if it does not exist or overwritten if it exists already.
WBEM_FLAG_UPDATE_ONLY | This flag causes this call to update. The instance must exist for the call to be successful.
WBEM_FLAG_CREATE_ONLY | This flag is used for creation only. The call will fail if the instance already exists.
WBEM_FLAG_RETURN_IMMEDIATELY | This flag causes this to be a semisychronous call. See Making a Semisynchronous Call for more information on semisynchronous calls.

pCtx
[in] Typically NULL, indicating that every property in the instance is to be updated. Otherwise, this is a pointer to an IWbemContext object containing additional information about the instance. The data in the context object must be documented by the provider responsible for the instance. A non-NULL IWbemContext object can indicate whether supports exists for partial instance updates.

For more information about how to support full and partial instance updates, see Implementing IWbemServices::PutInstanceAsync.

For more information about requesting a partial or full instance update operation, see Updating an Instance.

ppCallResult
[out, OPTIONAL] If NULL, this parameter is not used. If the lFlags parameter contains WBEM_FLAG_RETURN_IMMEDIATELY, this call will return immediately with WBEM_S_NO_ERROR. The ppCallResult parameter will then receive a pointer to a new IWbemCallResult object, which can then be polled to obtain the result using the IWbemCallResult::GetCallStatus method.

Return Values

Value | Meaning
WBEM_E_ACCESS_DENIED | The current user does not have permission to update an instance of the specified class.
WBEM_E_ALREADY_EXISTS | WBEM_FLAG_CREATE_ONLY flag was specified, but the instance already exists.
WBEM_E_INVALID_CLASS | The class supporting this instance is invalid.
WBEM_E_FAILED | This indicates other unspecified errors.
WBEM_E_ILLEGAL_NULL | A NULL value was specified for a property that may not be NULL, such as one that is marked by an indexed, or not_null qualifier.
WBEM_E_INVALID_OBJECT | The specified instance is invalid (for example, PutInstance with a class will invoke this return).
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_NOT_FOUND | WBEM_FLAG_UPDATE_ONLY flag was specified, but the instance does not exist.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_TRANSPORT_FAILURE | This indicates the failure of the remote procedure call (RPC) link between the current process and Windows Management.
WBEM_S_NO_ERROR | The call succeeded.

DCOM-specific error codes also may be returned if network problems cause you to lose the remote connection to Windows Management.

Remarks

Applications and providers call PutInstance to create or update an instance of an existing class. Depending on how the pCtx parameter is set, either some or all of the properties of the instance are updated. For information about how to support partial instance updating, see Implementing IWbemServices::PutInstanceAsync. For information about requesting a partial instance update, see Updating an Instance.

PutInstance supports creating instances and updating instances only. It does not support moving instances. That is, a caller cannot set the pInst parameter to an instance that has a key that is the same as another instance in a sibling class. For example, suppose ClassA is the base class to ClassB and ClassC. ClassA defines the KeyProp property as its key and ClassB has an instance that has KeyProp set to 1. To create an instance of ClassC with KeyProp set to 1, an application must first delete the ClassB instance by calling DeleteInstance and then save it with PutInstance.

When the instance pointed to by pInst belongs to a subclass, Windows Management calls all of the providers responsible for the classes from which the subclass derives. All of these providers must succeed in order for the original PutInstance request to succeed. The provider supporting the topmost class in the hierarchy is called first. The calling order continues with the subclass of the topmost class and proceeds from top to bottom until Windows Management reaches the provider for the class owning the instance pointed to by pInst.

Windows Management does not call the providers for any of the child classes of an instance. Therefore, if an application wants to change the values of inherited properties, the application must call PutInstance on the full instance of the child class rather than a corresponding instance of the parent class.

Calling PutInstance on an instance of an abstract class is not allowed.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

Error Handling for Applications, IWbemCallResult, IWbemServices::PutInstanceAsync, Creating an Instance


IWbemServices::PutInstanceAsync

The IWbemServices::PutInstanceAsync method asynchronously creates or updates an instance of an existing class. Update confirmation or error reporting is provided through the IWbemObjectSink interface implemented by the caller.

HRESULT IWbemServices::PutInstanceAsync(
  IWbemClassObject *pInst,
  LONG lFlags,
  IWbemContext *pCtx,
  IWbemObjectSink *pResponseHandler
);

Parameters

pInst
[in] Points to the instance to be written to the CIM repository. The caller cannot make assumptions about the reference count at the completion of this call.
lFlags
[in] One or more of the following values can be specified.
Flag | Description
WBEM_FLAG_CREATE_OR_UPDATE | This flag causes this instance to be created if it does not exist or be overwritten if it exists already.
WBEM_FLAG_UPDATE_ONLY | Updates an existing instance.
WBEM_FLAG_CREATE_ONLY | This flag is for instance creation only. The call will fail if the class already exists.
WBEM_FLAG_SEND_STATUS | This flag registers with Windows Management a request to receive intermediate status reports through the clients implementation of IWbemObjectSink::SetStatus.

pCtx
[in] Typically NULL. Otherwise, this is a pointer to an IWbemContext object required by the dynamic class provider that is producing the class instances. The values in the context object must be specified in the documentation for the provider in question. See Making Calls to WMI for more information about this parameter.
pResponseHandler
[in] Points to the caller's implementation of IWbemObjectSink. This handler receives the status of this call when it becomes available using the IWbemObjectSink::SetStatus method. If any error code is returned, then the supplied IWbemObjectSink pointer will not be used. If WBEM_S_NO_ERROR is returned, then the user's IWbemObjectSink implementation will be called to indicate the result of the operation. Windows Management only calls AddRef on the pointer in cases where WBEM_S_NO_ERROR returns. In cases where an error code returns, the reference count is the same as on entry. For a detailed explanation of how to make asynchronous calls, see Making an Asynchronous Call.

Return Values

Value | Meaning
WBEM_E_ALREADY_EXISTS | WBEM_FLAG_CREATE_ONLY flag was specified, but the instance already exists.
WBEM_E_FAILED | This indicates other unspecified errors.
WBEM_E_ACCESS_DENIED | The user does not have permission to add or update the instance specified.
WBEM_E_INVALID_OBJECT | The specified instance is invalid. You will see this error if the supplied object is not an instance object.
WBEM_E_ILLEGAL_NULL | A NULL value was specified for a property that is not NULL, such as one marked by a key, indexed, or not_null qualifier.
WBEM_E_INVALID_CLASS | The specified class was invalid.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_NOT_FOUND | WBEM_FLAG_UPDATE_ONLY flag was specified, but the instance does not exist.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_TRANSPORT_FAILURE | This indicates the failure of the remote procedure call (RPC) link between the current process and Windows Management.
WBEM_S_NO_ERROR | The call succeeded.

DCOM-specific error codes also may be returned if network problems cause you to lose the remote connection to Windows Management.

Remarks

Clients that call PutInstanceAsync must always expect the results of the call to be reported using their IWbemObjectSink::Indicate method.

When the instance pointed to by pInst belongs to a class that is derived from other classes, the success of PutInstanceAsync depends on the success of the providers responsible for the superclasses. For example, if pInst belongs to ClassB and ClassB derives from ClassA, a call to the PutInstanceAsync method implemented by the provider for ClassA must succeed in order for the update operation on ClassB to succeed. For more information, see the Remarks section for IWbemServices::PutInstance.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

Making an Asynchronous Call, IWbemContext, Creating an Instance


IWbemServices::DeleteInstance

The IWbemServices::DeleteInstance method deletes an instance of an existing class in the current namespace.

HRESULT IWbemServices::DeleteInstance(
  const BSTR strObjectPath,
  LONG lFlags,
  IWbemContext *pCtx,
  IWbemCallResult **ppCallResult
);

Parameters

strObjectPath
[in] A valid BSTR containing the object path to the instance to be deleted.
lFlags
[in] One of the following values are valid.
Flag | Description
WBEM_FLAG_RETURN_IMMEDIATELY | This flag causes this to be a semisychronous call. See Making a Semisynchronous Call for more information on semisynchronous calls.

pCtx
[in] Typically NULL. Otherwise, this is a pointer to an IWbemContext object that may be used by the provider that is deleting the instance. The values in the context object must be specified in the documentation for the provider in question.
ppCallResult
[out, OPTIONAL] If NULL, this parameter is not used. If ppCallResult is specified, it must be set to point to NULL on entry. If the lFlags parameter contains WBEM_FLAG_RETURN_IMMEDIATELY, this call will return immediately with WBEM_S_NO_ERROR. The ppCallResult parameter will receive a pointer to a new IWbemCallResult object, which can then be polled to obtain the result using the GetCallStatus method.

Return Values

Value | Meaning
WBEM_E_ACCESS_DENIED | The current context does not have adequate rights to delete the object.
WBEM_E_FAILED | This indicates other unspecified errors.
WBEM_E_INVALID_CLASS | The specified class does not exist.
WBEM_E_INVALID_PARAMETER | One of the parameters was not valid.
WBEM_E_NOT_FOUND | The object did not exist.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_TRANSPORT_FAILURE | This indicates the failure of the remote procedure call (RPC) link between the current process and Windows Management.
WBEM_S_NO_ERROR | The call succeeded.

On failure, you can obtain any available information from the COM function GetErrorInfo.

DCOM-specific error codes also may be returned if network problems cause you to lose the remote connection to Windows Management.

Remarks

IWbemServices::DeleteInstance is called to delete an existing instance in the current namespace. Instances in other namespaces cannot be deleted. When DeleteInstance is called to delete an instance that belongs to a class in a hierarchy, Windows Management calls the DeleteInstanceAsync method for all of the providers responsible for non-abstract classes in the hierarchy. That is, if the strObjectPath parameter identifies an instance of ClassB, and ClassB derives from ClassA, a non-abstract class, and is the parent class of ClassC and ClassD, also non-abstract classes, the providers for all four classes are called.

Windows Management calls each provider with an object path that is modified to point to their class. For example, if strObjectPath for the original call is set to "ClassB.k=1", the call to the provider of ClassA would set strObjectPath to "ClassA.k=1".

The success of a DeleteInstance call depends only on the success of a DeleteInstanceAsync call to the provider of the topmost non-abstract class. A non-abstract class has an abstract class as its parent. If the provider for any one of such classes succeeds, the operation succeeds, if all such classes fail, the operation fails.

For example, assume that ClassX is the base class for the following hierarchy:

  1. ClassA derives from ClassX.
  2. ClassB derives from ClassA.
  3. ClassC and ClassD derive from ClassB.

If ClassX is the only abstract class in the hierarchy and the strObjectPath parameter in DeleteInstance points to an instance of ClassB, only the provider for ClassA needs to succeed in its DeleteInstanceAsync call.

If ClassX, ClassA, and ClassB are all abstract and the strObjectPath parameter in DeleteInstance again points to an instance of ClassB, either the provider for ClassC or the provider for ClassD must succeed.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

Error Handling for Applications, IWbemCallResult, IWbemServices::DeleteInstanceAsync, Object Paths


IWbemServices::DeleteInstanceAsync

The IWbemServices::DeleteInstanceAsync method asynchronously deletes an instance of an existing class in the current namespace. The confirmation or failure of the operation is reported through the IWbemObjectSink interface implemented by the caller.

HRESULT IWbemServices::DeleteInstanceAsync(
  const BSTR strObjectPath,
  LONG lFlags,
  IWbemContext *pCtx,
  IWbemObjectSink *pResponseHandler
);

Parameters

strObjectPath
[in] A valid BSTR containing the object path of the object to be deleted.
lFlags
[in]
Flag | Description
WBEM_FLAG_SEND_STATUS | This flag registers with Windows Management a request to receive intermediate status reports through the client's implementation of IWbemObjectSink::SetStatus.
WBEM_E_INVALID_OBJECT_PATH | If the object path specified is invalid or is a class object path.
WBEM_E_INVALID_OPERATION | If the instance specified can't be deleted.

pCtx
[in] Typically NULL. Otherwise, this is a pointer to an IWbemContext object that may be used by the provider that is deleting the instance. The values in the context object must be specified in the documentation for the provider in question.
pResponseHandler
[in] Points to the caller's implementation of IWbemObjectSink. This handler receives the status of the delete operation as it becomes available through the SetStatus method. If any error code is returned, then the supplied IWbemObjectSink pointer will not be used. If WBEM_S_NO_ERROR is returned, then the user's IWbemObjectSink implementation will be called to indicate the result of the operation. Windows Management only calls AddRef on the pointer in cases where WBEM_S_NO_ERROR returns. In cases where an error code returns, the reference count is the same as on entry. For a detailed explanation of making a call asynchronously, see Making an Asynchronous Call.

Return Values

Value | Meaning
WBEM_E_FAILED | This indicates other unspecified errors.
WBEM_E_INVALID_CLASS | The specified class was invalid.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_TRANSPORT_FAILURE | This indicates the failure of the remote procedure call (RPC) link between the current process and Windows Management.
WBEM_S_NO_ERROR | The call succeeded.

On failure, you can obtain any available information from the COM function GetErrorInfo.

Other error conditions are reported asynchronously to the object sink supplied by the pResponseHandler parameter.

DCOM-specific error codes also may be returned if network problems cause you to lose the remote connection to Windows Management.

Note Clients that call DeleteInstanceAsync must always expect the results of the call to be reported using their IWbemObjectSink::Indicate method.

When the instance pointed to by strObjectPath belongs to a class that is a member of a class hierarchy, the success of DeleteInstanceAsync depends on the topmost non-abstract provider. For a detailed explanation of the dependencies involved that determine the success of this operation, see the Remarks section for IWbemServices::DeleteInstance.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

Making an Asynchronous Call, IWbemServices::DeleteInstance, Object Paths


IWbemServices::CreateInstanceEnum

The IWbemServices::CreateInstanceEnum method creates an enumerator that returns the instances of a specified class according to user-specified selection criteria. This method supports simple WQL queries; more complex queries can be processed using the IWbemServices::ExecQuery method.

HRESULT IWbemServices::CreateInstanceEnum(
  const BSTR strClass,
  LONG lFlags,
  IWbemContext *pCtx,
  IEnumWbemClassObject **ppEnum
);

Parameters

strClass
[in] A valid BSTR containing the name of the class for which instances are desired. This parameter cannot be NULL.
lFlags
[in] The following flags affect the behavior of this method. The suggested value for this parameter is WBEM_FLAG_RETURN_IMMEDIATELY and WBEM_FLAG_FORWARD_ONLY for best performance.
Flag | Description
WBEM_FLAG_USE_AMENDED_QUALIFIERS | If this flag is set, WMI will retrieve the amended qualifiers stored in the localized namespace of the current connection's locale. If not set, only the qualifiers stored in the immediate namespace will be retrieved.
WBEM_FLAG_DEEP | This flag forces the enumeration to include all classes in the hierarchy.
WBEM_FLAG_SHALLOW | This flag forces the enumeration to include only immediate subclasses of the specified superclass.
WBEM_FLAG_RETURN_IMMEDIATELY | This flag causes this to be a semisychronous call. See Making a Semisynchronous Call for more information on semisynchronous calls.
WBEM_FLAG_FORWARD_ONLY | This flag causes a forward-only enumerator to be returned. Forward-only enumerators are generally much faster and use less memory than conventional enumerators but do not allow calls to Clone or Reset.
WBEM_FLAG_BIDIRECTIONAL | This flag causes Windows Management to retain pointers to objects of the enumeration until the client releases the enumerator. Because object pointers are not released immediately, this method may fail with a hResult of WBEM_E_OUT_OF_MEMORY if the client attempts to enumerate a large number of objects. This flag is implied by default if you set the lFlags parameter to 0
WBEM_FLAG_DIRECT_READ | This flag causes direct access to the provider (or repository) for the class specified without any regard to its superclass or subclasses.

pCtx
[in] Typically NULL. Otherwise, this is a pointer to an IWbemContext object that may be used by the provider that is providing the requested instances. The values in the context object must be specified in the documentation for the provider in question. See Making Calls to WMI for more information about this parameter.
ppEnum
[out] Receives the pointer to the enumerator, which has a positive reference count. The caller must call IUnknown::Release on the pointer after it is no longer required.

Return Values

Value | Meaning
WBEM_E_ACCESS_DENIED | The current user does not have permission to view instances of the specified class.
WBEM_E_FAILED | This indicates other unspecified errors.
WBEM_E_INVALID_CLASS | The specified class does not exist or is invalid.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_TRANSPORT_FAILURE | This indicates the failure of the remote procedure call (RPC) link between the current process and Windows Management.
WBEM_S_NO_ERROR | The call succeeded.

On failure, you can obtain any available information from the COM function GetErrorInfo.

DCOM-specific error codes also may be returned if network problems cause you to lose the remote connection to Windows Management.

Remarks

It is not an error for the returned enumerator to have zero elements.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

Error Handling for Applications, IWbemServices::CreateInstanceEnumAsync


IWbemServices::CreateInstanceEnumAsync

The IWbemServices::CreateInstanceEnumAsync method creates an enumerator that asynchronously returns the instances of a specified class according to user-specified selection criteria. This method supports simple WQL queries; more complex queries can be processed using the IWbemServices::ExecQueryAsync method.

HRESULT IWbemServices::CreateInstanceEnumAsync(
  const BSTR strClass,
  LONG lFlags,
  IWbemContext *pCtx,
  IWbemObjectSink *pResponseHandler
);

Parameters

strClass
[in] A valid BSTR containing the name of the class for which instances are desired. This parameter cannot be NULL.
lFlags
[in]
Flag | Description
WBEM_FLAG_USE_AMENDED_QUALIFIERS | If this flag is set, WMI will retrieve the amended qualifiers stored in the localized namespace of the current connection's locale. If not set, only the qualifiers stored in the immediate namespace will be retrieved.
WBEM_FLAG_DEEP | This flag forces the enumeration to include all classes in the hierarchy.
WBEM_FLAG_SHALLOW | This flag forces the enumeration to include only immediate subclasses of the specified superclass.
WBEM_FLAG_SEND_STATUS | This flag registers with Windows Management a request to receive intermediate status reports through the clients implementation of IWbemObjectSink::SetStatus.
WBEM_FLAG_FORWARD_ONLY | This flag causes a forward-only enumerator to be returned. Forward-only enumerators are generally much faster and use less memory than conventional enumerators but do not allow calls to Clone or Reset.
WBEM_FLAG_BIDIRECTIONAL | This flag causes Windows Management to retain pointers to objects of the enumeration until the client releases the enumerator.
WBEM_FLAG_DIRECT_READ | This flag causes direct access to the provider (or repository) for the class specified without any regard to its superclass or subclasses.
pCtx
[in] Typically NULL. Otherwise, this is a pointer to an IWbemContext object that may be used by the provider that is returning the requested instances. The values in the context object must be specified in the documentation for the provider in question. See Making Calls to WMI for more information about this parameter.
pResponseHandler
[in] Points to the caller's implementation of IWbemObjectSink. This handler receives the objects as they become available. If any error code is returned, then the supplied IWbemObjectSink pointer will not be used. If any error code is returned, then the supplied IWbemObjectSink pointer will not be used. If WBEM_S_NO_ERROR is returned, then the user's IWbemObjectSink implementation will be called to indicate the result of the operation. Windows Management only calls AddRef on the pointer in cases where WBEM_S_NO_ERROR returns. In cases where an error code returns, the reference count is the same as on entry. For a detailed explanation of this parameter, see Making an Asynchronous Call.

Return Values

Value | Meaning
WBEM_E_FAILED | This indicates other unspecified errors.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_INVALID_CLASS | The specified class does not exist or is invalid.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_TRANSPORT_FAILURE | This indicates the failure of the remote procedure call (RPC) link between the current process and Windows Management.
WBEM_S_NO_ERROR | The call succeeded.

On failure, you can obtain additional information from the COM function GetErrorInfo.

DCOM-specific error codes also may be returned if network problems cause you to lose the remote connection to Windows Management.

Remarks

IWbemObjectSink::SetStatus is called to indicate the end of the result set. It may also be called with no intervening calls to IWbemObjectSink::Indicate if error conditions occur.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemServices::CreateInstanceEnum


IWbemServices::ExecQuery

The IWbemServices::ExecQuery method executes a query to retrieve objects.

For the valid types of queries that can be performed, see Queries.

HRESULT IWbemServices::ExecQuery(
  const BSTR strQueryLanguage,
  const BSTR strQuery,
  LONG lFlags,
  IWbemContext *pCtx,
  IEnumWbemClassObject **ppEnum
);

Parameters

strQueryLanguage
[in] A valid BSTR containing one of the query languages supported by Windows Management. This must be the "WQL", the acronym for WMI Query Language.
strQuery
[in] A valid BSTR containing the text of the query. This parameter cannot be NULL.
lFlags
[in] The following flags affect the behavior of this method. The suggested value for this parameter is WBEM_FLAG_RETURN_IMMEDIATELY and WBEM_FLAG_FORWARD_ONLY for best performance.
Flag | Value
WBEM_FLAG_USE_AMENDED_QUALIFIERS | If this flag is set, WMI will retrieve the amended qualifiers stored in the localized namespace of the current connection's locale. If not set, only the qualifiers stored in the immediate namespace will be retrieved.
WBEM_FLAG_FORWARD_ONLY | This flag causes a forward-only enumerator to be returned. Forward-only enumerators are generally much faster and use less memory than conventional enumerators but do not allow calls to Clone or Reset.
WBEM_FLAG_BIDIRECTIONAL | This flag causes Windows Management to retain pointers to objects of the enumeration until the client releases the enumerator.
WBEM_FLAG_RETURN_IMMEDIATELY | This flag causes this to be a semisychronous call. See Making a Semisynchronous Call for more information on semisynchronous calls.
WBEM_FLAG_ENSURE_LOCATABLE | This flag ensures that any returned objects have enough information in them so that the system properties such as __PATH, __RELPATH, and __SERVER are non-NULL.
WBEM_FLAG_PROTOTYPE | This flag is used for prototyping. It does not execute the query and instead returns an object that looks like a typical result object.
WBEM_FLAG_DIRECT_READ | This flag causes direct access to the provider (or repository) for the class specified without any regard to its superclass or subclasses.

pCtx
[in] Typically NULL. Otherwise, this is a pointer to an IWbemContext object that may be used by the provider that is providing the requested classes or instances. The values in the context object must be specified in the documentation for the provider in question. See Making Calls to WMI for more information about this parameter.
ppEnum
[out] If no error occurs, this receives the enumerator that allows the caller to retrieve the instances in the result set of the query. It is not an error for the query to have a result set with zero instances. This is determined only by attempting to iterate through the instances. This object returns with a positive reference count. The caller must call Release when the object is no longer needed.

Return Values

Value | Meaning
WBEM_E_ACCESS_DENIED | The current user does not have permission to view the result set.
WBEM_E_FAILED | This indicates other unspecified errors.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_INVALID_QUERY | The query was not syntactically valid.
WBEM_E_INVALID_QUERY_TYPE | The requested query language is not supported.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_TRANSPORT_FAILURE | This indicates the failure of the remote procedure call (RPC) link between the current process and Windows Management.
WBEM_E_NOT_FOUND | The query specifies a class that does not exist.
WBEM_S_NO_ERROR | The call succeeded.

On failure, you can obtain any available information from the COM function GetErrorInfo.

DCOM-specific error codes also may be returned if network problems cause you to lose the remote connection to Windows Management.

Remarks

IWbemServices::ExecQuery processes the query specified in the strQuery parameter and creates an enumerator through which the caller can access the query results. The enumerator is a pointer to an IEnumWbemClassObject interface; the query results are instances of class objects made available through the IWbemClassObject interface.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemServices::ExecQueryAsync, WMI Query Language, Data Queries, Event Queries, Schema Queries


IWbemServices::ExecQueryAsync

The IWbemServices::ExecQueryAsync method executes a query to retrieve objects asynchronously.

HRESULT IWbemServices::ExecQueryAsync(
  const BSTR strQueryLanguage,
  const BSTR strQuery,
  long lFlags,
  IWbemContext *pCtx,
  IWbemObjectSink *pResponseHandler
);

Parameters

strQueryLanguage
[in] A valid BSTR containing one of the query languages supported by Windows Management. This must be "WQL".
strQuery
[in] A valid BSTR containing the text of the query. This cannot be NULL.
lFlags
[in]
Flag | Description
WBEM_FLAG_USE_AMENDED_QUALIFIERS | If this flag is set, WMI will retrieve the amended qualifiers stored in the localized namespace of the current connection's locale. If not set, only the qualifiers stored in the immediate namespace will be retrieved.
WBEM_FLAG_BIDIRECTIONAL | This flag causes Windows Management to retain pointers to objects of the enumeration until the client releases the enumerator.
WBEM_FLAG_SEND_STATUS | This flag registers with Windows Management a request to receive intermediate status reports through the client's implementation of IWbemObjectSink::SetStatus.
WBEM_FLAG_ENSURE_LOCATABLE | This flag ensures that any returned objects have enough information in them so that the system properties such as __PATH, __RELPATH, and __SERVER are non-NULL.
WBEM_FLAG_PROTOTYPE | This flag is used for prototyping. It does not execute the query and instead returns an object that looks like a typical result object.
WBEM_FLAG_DIRECT_READ | This flag causes direct access to the provider (or repository) for the class specified without any regard to its superclass or subclasses.

pCtx
[in] Typically NULL. Otherwise, this is a pointer to an IWbemContext object that may be used by the provider that is returning the requested classes or instances. The values in the context object must be specified in the documentation for the provider in question. See Making Calls to WMI for more information about this parameter.
pResponseHandler
[in] Points to the caller's implementation of IWbemObjectSink. This handler receives the objects in the query result set as they become available. If any error code is returned, then the supplied IWbemObjectSink pointer will not be used. If WBEM_S_NO_ERROR is returned, then the user's IWbemObjectSink implementation will be called to indicate the result of the operation. Windows Management calls IWbemObjectSink::Indicate with the objects any number of times, followed by a single call to IWbemObjectSink::SetStatus to indicate the final status.

Windows Management only calls AddRef to the pointer in cases where WBEM_S_NO_ERROR returns. In cases where an error code returns, the reference count is the same as on entry. For a detailed explanation of call methods asynchronously, see Making an Asynchronous Call.

Return Values

Value | Meaning
WBEM_E_FAILED | This indicates other unspecified errors.
WBEM_E_NOT_FOUND | The query specifies a class that does not exist.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_TRANSPORT_FAILURE | This indicates the failure of the remote procedure call (RPC) link between the current process and Windows Management.
WBEM_S_NO_ERROR | The call succeeded.

On failure, you can obtain any available information from the COM function GetErrorInfo.

Other error codes are returned to the object sink specified by the pResponseHandler parameter.

DCOM-specific error codes also may be returned if network problems cause you to lose the remote connection to Windows Management.

Remarks

The caller's IWbemObjectSink::Indicate method may be called to report intermittent status. IWbemObjectSink::SetStatus is called to indicate the end of the result set.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

Making an Asynchronous Call, IWbemServices::ExecQuery, Queries


IWbemServices::ExecNotificationQuery

The IWbemServices::ExecNotificationQuery method executes a query to receive events. The call returns immediately, and the user can poll the returned enumerator for events as they arrive. Releasing the returned enumerator cancels the query.

HRESULT IWbemServices::ExecNotificationQuery(
  const BSTR strQueryLanguage,
  const BSTR strQuery,
  long lFlags,
  IWbemContext *pCtx,
  IEnumWbemClassObject **ppEnum
);

Parameters

strQueryLanguage
[in] A valid BSTR containing one of the query languages supported by Windows Management. This cannot be NULL. Currently, only the WMI Query Language (WQL) is supported.
strQuery
[in] A valid BSTR containing the text of the event-related query. This cannot be NULL.
lFlags
[in] This parameter must be set to both WBEM_FLAG_RETURN_IMMEDIATELY and WBEM_FLAG_FORWARD_ONLY or the call will fail.
Flag | Description
WBEM_FLAG_FORWARD_ONLY | This flag causes a forward-only enumerator to be returned. Forward-only enumerators are generally much faster and use less memory than conventional enumerators but do not allow calls to Clone or Reset.
WBEM_FLAG_RETURN_IMMEDIATELY | The user must specify this flag or the call will fail. This is because events are received continuously, which means the user must poll the returned enumerator. Blocking this call indefinitely while waiting for a possible event would block the thread for an indefinite amount of time. See Making a Semisynchronous Call for more information on semisynchronous calls.
pCtx
[in] Typically NULL. Otherwise, this is a pointer to an IWbemContext object that may be used by the provider that is providing the requested events. The values in the context object must be specified in the documentation for the provider in question. See Making Calls to WMI for more information about this parameter.
ppEnum
[out] If no error occurs, this receives the enumerator that allows the caller to retrieve the instances in the result set of the query. The caller periodically calls IEnumWbemClassObject::Next to see if any events are available. Notice that in this usage, Reset does not move the enumerator back to the beginning of the event sequence; it has no effect. The parameter can continue to receive events until Release is called on the returned enumerator.

Return Values

Value | Meaning
WBEM_E_ACCESS_DENIED | The current user is not authorized to view the result set.
WBEM_E_FAILED | This indicates other unspecified errors.
WBEM_E_INVALID_CLASS | The query specifies a class that does not exist.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_REGISTRATION_TOO_PRECISE | Too much precision in delivery of events has been requested. A larger polling tolerance should be specified.
WBEM_E_REGISTRATION_TOO_BROAD | The query requests more information than CIMOM can reasonably provide. This message is returned when an event query results in a request to poll all objects in a namespace.
WBEM_E_INVALID_QUERY | The query was not syntactically valid.
WBEM_E_INVALID_QUERY_TYPE | The requested query language is not supported.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_TRANSPORT_FAILURE | This indicates the failure of the remote procedure call (RPC) link between the current process and Windows Management.
WBEM_E_UNPARSABLE_QUERY | The query could not be parsed.
WBEM_S_NO_ERROR | The call succeeded.

On failure, you can obtain any available information from the COM function GetErrorInfo.

DCOM-specific error codes also may be returned if network problems cause you to lose the remote connection to Windows Management.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

Temporary Event Consumers, Error Handling for Applications, IWbemServices::ExecNotificationQueryAsync, Queries


IWbemServices::ExecNotificationQueryAsync

The IWbemServices::ExecNotificationQueryAsync method performs the same task as IWbemServices::ExecNotificationQuery except that events are supplied to the specified response handler until CancelAsyncCall is called to stop the event notification.

HRESULT IWbemServices::ExecNotificationQueryAsync(
  const BSTR strQueryLanguage,
  const BSTR strQuery,
  long lFlags,
  IWbemContext *pCtx,
  IWbemObjectSink *pResponseHandler
);

Parameters

strQueryLanguage
[in] A valid BSTR containing one of the query languages supported by Windows Management. This must be "WQL".
strQuery
[in] A valid BSTR containing the text of the event-related query. This cannot be NULL.
lFlags
[in]
Flag | Description
WBEM_FLAG_SEND_STATUS | This flag registers with Windows Management a request to receive intermediate status reports through the client's implementation of IWbemObjectSink::SetStatus.

pCtx
[in] Typically NULL. Otherwise, this is a pointer to an IWbemContext object that may be used by the provider that is returning the requested events. The values in the context object must be specified in the documentation for the provider in question. See Making Calls to WMI for more information about this parameter.
pResponseHandler
[in] Points to a the caller's implementation of IWbemObjectSink. This handler receives the objects in the query result set as they become available. To cease receiving events, the caller must call IWbemServices::CancelAsyncCall using the same pointer value for pResponseHandler. As events become available, the supplied IWbemObjectSink::Indicate implementation is called to deliver the event objects. IWbemObjectSink::SetStatus is not called at any time, since there is no final or terminating condition. The call executes indefinitely until canceled. If any error code is returned, then the supplied IWbemObjectSink pointer will not be used. If WBEM_S_NO_ERROR is returned, then the user's IWbemObjectSink implementation will be called to indicate the result of the operation. Windows Management only calls AddRef on the pointer in cases where WBEM_S_NO_ERROR returns. In cases where an error code returns, the reference count is the same as on entry. For a detailed explanation of this parameter, see Making an Asynchronous Call.

Return Values

Value | Meaning
WBEM_E_FAILED | This indicates other unspecified errors.
WBEM_E_INVALID_CLASS | The query specifies a class that does not exist.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_REGISTRATION_TOO_PRECISE | Too much precision in delivery of events has been requested. A larger polling tolerance should be specified.
WBEM_E_REGISTRATION_TOO_BROAD | The query requests more information than CIMOM can reasonably provide. This message is returned when an event query results in a request to poll all objects in a namespace.
WBEM_E_INVALID_QUERY | The query was not syntactically valid.
WBEM_E_INVALID_QUERY_TYPE | The requested query language is not supported.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_TRANSPORT_FAILURE | This indicates the failure of the remote procedure call (RPC) link between the current process and Windows Management.
WBEM_E_UNPARSABLE_QUERY | The query could not be parsed.
WBEM_S_NO_ERROR | The call succeeded.

On failure, you can obtain any available information from the COM function GetErrorInfo.

Other error codes are returned to the object sink specified by the pResponseHandler parameter.

DCOM-specific error codes also may be returned if network problems cause you to lose the remote connection to Windows Management.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

Temporary Event Consumers, Making an Asynchronous Call, Event Queries, IWbemServices::ExecQuery


IWbemServices::ExecMethod

The IWbemServices::ExecMethod method executes a method exported by a CIM object. The method call is forwarded to the appropriate provider where it executes. Information and status are returned to the caller, which blocks until the call is complete.

Methods are not directly implemented by Windows Management, but are exported by method providers. For any given CIM class, the available methods and their parameters must be specified in the documentation for the provider in question.

See Calling a Method for additional information about executing methods.

HRESULT IWbemServices::ExecMethod(
  const BSTR strObjectPath,
  const BSTR MethodName,
  long lFlags,
  IWbemContext *pCtx,
  IWbemClassObject *pInParams,
  IWbemClassObject **ppOutParams,
  IWbemCallResult **ppCallResult
);

Parameters

strObjectPath
[in] A valid BSTR containing the object path of the object for which the method is executed.
MethodName
[in] The name of the method for the object.
lFlags
[in] This parameter can be set to zero to make this a synchronous call. Otherwise, to make this a semisynchronous call set lFlags to WBEM_FLAG_RETURN_IMMEDIATELY, provide a valid pointer for the ppCallResult parameter and this call will return immediately. See Making a Semisynchronous Call for more information on semisynchronous calls.
pCtx
[in] Typically NULL. Otherwise, this is a pointer to an IWbemContext object that may be used by the provider that is executing the method. The values in the context object must be specified in the documentation for the provider in question. See Making Calls to WMI for more information about this parameter.
pInParams
[in] May be NULL if no in-parameters are required to execute the method. Otherwise, this points to an IWbemClassObject that contains the properties acting as inbound parameters for the method execution. The contents of the object are method-specific, and are part of the specification for the provider in question.
ppOutParams
[out, OPTIONAL] If not NULL, receives a pointer to the outbound parameters and return values for the method execution. The contents of this object are method-specific, and are part of the specification for the provider in question. The caller must call Release on the returned object when it is no longer required.
ppCallResult
[out, OPTIONAL] If NULL, this is not used. If ppCallResult is specified it must be set to point to NULL on entry. In this case, the call returns immediately with WBEM_S_NO_ERROR. ppCallResult receives a pointer to a new IWbemCallResult object, which must be polled to obtain the result of the method execution using the GetCallStatus method. The out-parameters for the call are available by calling IWbemCallResult::GetResultObject

Return Values

Value | Meaning
WBEM_E_FAILED | This indicates other unspecified errors.
WBEM_E_INVALID_CLASS | The specified class was invalid.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_METHOD_DISABLED | An attempt was made to execute a method marked with [disabled].
WBEM_E_METHOD_NOT_IMPLEMENTED | An attempt was made to execute a method not marked with [implemented] in any relevant class.
WBEM_E_PROVIDER_NOT_CAPABLE | The provider does not support method calls.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_TRANSPORT_FAILURE | This indicates the failure of the remote procedure call (RPC) link between the current process and Windows Management.
WBEM_E_INVALID_METHOD | The requested method was not available.
WBEM_E_ACCESS_DENIED | The current user was not authorized to execute the method.
WBEM_E_INVALID_METHOD_PARAMETERS This error results from one of two causes.
  • The supplied pInParams object was determined by the provider to be invalid.
  • The strObjPath specifies a class without the [static] qualifier on the method.
WBEM_S_NO_ERROR | The call succeeded.

On failure, you can obtain any available information from the COM function GetErrorInfo.

DCOM-specific error codes also may be returned if network problems cause you to lose the remote connection to Windows Management.

Remarks

If ppOutParams is not NULL, the client can determine the method's return value type by examining the ReturnValue property of the object pointed to by ppOutParams.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

Calling a Method, IWbemServices::ExecMethodAsync, IWbemCallResult::GetResultObject


IWbemServices::ExecMethodAsync

The IWbemServices::ExecMethodAsync method asynchronously executes a method exported by a CIM object. The call immediately returns to the client while the inbound parameters are forwarded to the appropriate provider where it executes. Information and status are returned to the caller through the supplied object sink.

Methods are not directly implemented by Windows Management, but are exported by method providers. For any given CIM class, the available methods and their parameters are part of the documentation for the provider in question.

HRESULT IWbemServices::ExecMethodAsync(
  const BSTR strObjectPath,
  const BSTR strMethodName,
  LONG lFlags,
  IWbemContext *pCtx,
  IWbemClassObject *pInParams,
  IWbemObjectSink *pResponseHandler
);

Parameters

strObjectPath
[in] A valid BSTR containing the object path of the object for which the method is to be executed.
strMethodName
[in] The name of the method for the object.
lFlags
[in] WBEM_FLAG_SEND_STATUS registers with Windows Management a request to receive intermediate status reports through the clients implementation of IWbemObjectSink::SetStatus.
pCtx
[in] Typically NULL. Otherwise, this is a pointer to an IWbemContext object that may be used by the provider that is executing the method. The values in the context object must be specified in the documentation for the provider in question. See Making Calls to WMI for more information about this parameter.
pInParams
[in] Can be NULL if no inbound parameters are required to execute the method. Otherwise, this points to an IWbemClassObject that contains the properties acting as inbound parameters for the method execution. The contents of the object are method-specific, and are part of the specification for the provider in question.
pResponseHandler
[in] Must not be NULL. The object sink receives the result of the method call. The outbound parameters are sent to IWbemObjectSink::Indicate. The result of the call mechanism itself will be sent to IWbemObjectSink::SetStatus. Notice that IWbemObjectSink::SetStatus does not receive the return code of the CIM method. However, it receives the return code of the actual call-return mechanism, and is only useful for verifying that the call occurred or that it failed for mechanical reasons. The result code returned from the CIM method is returned in the outbound parameter object supplied to IWbemObjectSink::Indicate. If any error code is returned, then the supplied IWbemObjectSink pointer will not be used. If WBEM_S_NO_ERROR is returned, then the user's IWbemObjectSink implementation will be called to indicate the result of the operation.

Return Values

Value | Meaning
WBEM_E_FAILED | This indicates other unspecified errors.
WBEM_E_INVALID_METHOD_PARAMETERS This error results from one of two causes.
  • The supplied pInParams object was determined by the provider to be invalid.
  • The strObjPath specifies a class without the [static] qualifier on the method.
WBEM_E_INVALID_PARAMETER | An invalid parameter was specified.
WBEM_E_METHOD_DISABLED | An attempt was made to execute a method marked with [disabled].
WBEM_E_METHOD_NOT_IMPLEMENTED | An attempt was made to execute a method not marked with [implemented] in any relevant class.
WBEM_E_OUT_OF_MEMORY | There was not enough memory to complete the operation.
WBEM_E_TRANSPORT_FAILURE | This indicates the failure of the remote procedure call (RPC) link between the current process and Windows Management.
WBEM_E_ACCESS_DENIED | The current user was not authorized to execute the method.
WBEM_S_NO_ERROR | The call succeeded.

On failure, you can obtain any available information from the COM function GetErrorInfo.

Other errors will be reported asynchronously to the object sink supplied in the pReponseHandler parameter

DCOM-specific error codes also may be returned if network problems cause you to lose the remote connection to Windows Management.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

Making an Asynchronous Call, IWbemServices::ExecMethod


IWbemStatusCodeText

[This is preliminary documentation and subject to change.]

The IWbemStatusCodeText interface extracts text string descriptions of error codes or the name of the subsystem where the error occurred.

Method | Description
GetErrorCodeText | Returns the text string description associated with the error code.
GetFacilityCodeText | Returns the name of the subsystem where the error occurred.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemStatusCodeText::GetErrorCodeText

[This is preliminary documentation and subject to change.]

The GetErrorCodeText method returns the text string description associated with the error code.

HRESULT IWbemStatusCodeText::GetErrorCodeText(
  HRESULT hRes,
  LCID LocaleId,
  long lFlags,
  BSTR *MessageText
);

Parameters

hRes
[in] Handle to the error code for which you want a description.
LocaleId
[in] Specifies which locale to use when retrieving the string.
lFlags
[in] Reserved. This parameter must be set to zero.
MessageText
[out] Pointer to a string containing the descriptive text of the error code.

Return Values

If the GetErrorCodeText method is successful, it returns WBEM_S_NO_ERROR.

Remarks

To enable the GetErrorCodeText method to return the text string description, the caller must free the pointer in the MessageText parameter.

Example

The following example shows how to use the GetErrorCodeText method.

IWbemStatusCodeText * pStatus = NULL;

    SCODE sc = CoCreateInstance(CLSID_WbemStatusCodeText, 0, CLSCTX_INPROC_SERVER,
                                        IID_IWbemStatusCodeText, (LPVOID *) &pStatus);

    if(sc == S_OK)
    {
        BSTR bstr = 0;
        sc = pStatus->GetErrorCodeText(m_hres, 0, 0, &bstr);
        if(sc == S_OK)
        {
            // todo, display this
            SysFreeString(bstr);
            bstr = 0;
        }
        sc = pStatus->GetFacilityCodeText(m_hres, 0, 0, &bstr);
        if(sc == S_OK)
        {
            // todo, display this
            SysFreeString(bstr);
            bstr = 0;
        }
        pStatus->Release();
    }

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemStatusCodeText::GetFacilityCodeText

[This is preliminary documentation and subject to change.]

The GetFacilityCodeText method Returns the name of the subsystem where the error occurred, such as "Windows", "WMI", "SSPI", or "RPC".

HRESULT IWbemStatusCodeText::GetFacilityCodeText(
  HRESULT hRes,
  LCID LocaleId,
  long lFlags,
  BSTR* MessageText
);

Parameters

hRes
[in] Handle to the error code for which you want a description.
LocaleId
[in] Specifies which locale to use when retrieving the string.
lFlags
[in] Reserved. This parameter must be set to zero.
MessageText
[out] Pointer to a string containing the descriptive text of the error code.

Return Values

If the GetFacilityCodeText method is successful, it returns WBEM_S_NO_ERROR.

Remarks

To enable the GetFacilityCodeText method to return the subsystem name, the caller must free the pointer in the MessageText parameter.

Example

The following example shows how to use the GetFacilityCodeText method.

IWbemStatusCodeText * pStatus = NULL;

    SCODE sc = CoCreateInstance(CLSID_WbemStatusCodeText, 0, CLSCTX_INPROC_SERVER,
                                        IID_IWbemStatusCodeText, (LPVOID *) &pStatus);

    if(sc == S_OK)
    {
        BSTR bstr = 0;
        sc = pStatus->GetErrorCodeText(m_hres, 0, 0, &bstr);
        if(sc == S_OK)
        {
            // todo, display this
            SysFreeString(bstr);
            bstr = 0;
        }
        sc = pStatus->GetFacilityCodeText(m_hres, 0, 0, &bstr);
        if(sc == S_OK)
        {
            // todo, display this
            SysFreeString(bstr);
            bstr = 0;
        }
        pStatus->Release();
    }

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemUnboundObjectSink

The IWbemUnboundObjectSink interface is implemented by all logical event consumers. It is a simple sink interface that accepts delivery of event objects.

IWbemUnboundObjectSink Methods | Properties
IndicateToConsumer | This is called by Windows Management to actually deliver events to a consumer.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemprov.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IWbemUnboundObjectSink::IndicateToConsumer

This is called by Windows Management to actually deliver events to a consumer.

HRESULT IWbemUnboundObjectSink::IndicateToConsumer(
  IWbemClassObject *pLogicalConsumer,
  long lNumObjects,
  IWbemClassObject **apObjects
);

Parameters

pLogicalConsumer
[in] A pointer to the logical consumer object for which this set of objects is delivered.
lNumObjects
[in] The number of objects delivered in the array that follows.
apObjects
[in, size_is(lNumObjects)] A pointer to an array of IWbemClassObject instances which represent the events delivered.

Return Values

Returns WBEM_S_NO_ERROR if successful. Otherwise, the implementation should return an appropriate error code.

Remarks

Windows Management typically obtains the IWbemUnboundObjectSink pointer from a event consumer provider which implements the IWbemEventConsumerProvider interface. That interface is called by Windows Management to obtain the IWbemUnboundObjectSink pointer for a particular logical consumer.

Then, Windows Management calls IndicateToConsumer to deliver the actual event objects.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemprov.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemEventConsumerProvider


IUnsecuredApartment

The IUnsecuredApartment interface is used to simplify the process of making asynchronous calls from a client process. When a client is making asynchronous calls, the roles of the client and the server are reversed. In this case, the client implements an object (IWbemObjectSink interface) and the server calls the methods of that object. Because of this, DCOM security rules for servers make it difficult for clients to make asynchronous calls. The primary difficulty is the fact that the client needs to inform DCOM that it is willing to allow Windows Management to invoke methods on the client's object (IWbemObjectSink).

IUnsecuredApartment Methods | Properties
CreateObjectStub | Creates an object stub to assist making asynchronous calls from a client process.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.


IUnsecuredApartment::CreateObjectStub

The IUnsecuredApartment::CreateObjectStub creates an object forwarder sink to assist in receiving asynchronous calls from Windows Management. This function binds an unsecured object sink to a local object sink so that DCOM security will not interfere with asynchronous retrieval of CIM objects. Because of the fact that DCOM security is being bypassed, the remote Windows Management server is assumed to be a trusted component.

The general paradigm is that the original implementation of IWbemObjectSink in the client process is not directly used in asynchronous calls to IWbemServices. Rather, both the original implementation and a substitute object are created, bound together, and then the substitute object is used in the asynchronous methods of IWbemServices.

HRESULT IUnsecuredApartment::CreateObjectStub(
  IUnknown *pObject,
  IUnknown **ppStub
);

Parameters

pObject
[in] A pointer to the client's in-process implementation of IWbemObjectSink.
ppStub
[out] Receives a pointer to a substitute object to be used in asynchronous IWbemServices calls. The user receives an IUnknown pointer and must call QueryInterface for IID_WbemObjectSink before using this object in asynchronous IWbemServices calls.

Return Values

Returns standard COM error codes for QueryInterface. It returns S_OK if the call succeeds. If the call fails because the requested interface was not supported, the method returns E_NOINTERFACE.

DCOM-specific error codes also may be returned if network problems cause you to lose the remote connection to Windows Management.

Sample Code

// Create the object which spawns new substitute sinks
IUnsecuredApartment *pSpawner = 0;
CoCreateInstance(CLSID_UnsecuredApartment, NULL, CLSCTX_ALL, IID_IUnsecuredApartment, (void **) pSpawner);

// Create a substitute sink
IWbemObjectSink *pUserSink = ...    // Create an instance of the user's sink by a private mechanism
IUnknown *pSubstitute = 0;
pSpawner->CreateObjectStub(pUserSink, &pSubstitute);
IWbemObjectSink *pSubstituteSink = 0;
pSubstitute->QueryInterface(IID_IWbemObjectSink, &pSubstituteSink);
pSubstitute->Release( );  // we don't need this interface any more

// We now use pSubstituteSink in IWbemServices calls and objects are delivered to the pUserSink.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 or later (with DCOM).
Header: Declared in Wbemcli.h; include Wbemidl.h.
Library: Use Wbemuuid.lib.

See Also

IWbemObjectSink, Making an Asynchronous Call


Scripting API for WMI

The Windows Management Instrumentation (WMI) scripting reference contains definitions for the WMI Scripting API. This reference provides information for developers who are writing applications with Microsoft® Visual Basic®, Visual Basic for Applications, Visual Basic Scripting Edition (VBScript), or Microsoft® JScript®.

The following table describes WMI scripting objects and how they are used.

Object | Description
SWbemEventSource | Retrieves events in conjunction with SWbemServices.ExecNotificationQuery.
SWbemLastError | Provides extended error information when an error occurs.
SWbemLocator | Obtains an SWbemServices object that can get access to WMI on a particular host computer.
SWbemMethod | Contains a single Common Information Model (CIM) method definition.
SWbemMethodSet | Gets a collection of SWbemMethod objects.
SWbemNamedValue | Contains a single named value.
SWbemNamedValueSet | Gets access to a collection of SWbemNamedValue objects.
SWbemObject | Contains and manipulates a single CIM object class or instance.
SWbemObjectPath | Generates and validates an object path.
SWbemObjectSet | Gets access to a collection of SWbemObject objects.
SWbemPrivilege | Sets or clears a privilege.
SWbemPrivilegeSet | Gets access to a collection of SWbemPrivilege objects.
SWbemProperty | Contains a single CIM property.
SWbemPropertySet | Gets access to a collection of SWbemProperty objects.
SWbemQualifier | Contains a single CIM qualifier.
SWbemQualifierSet | Gets access to a collection of SWbemQualifier objects.
SWbemSecurity | Manages security settings such as Distributed Component Object Model (DCOM) Privileges, AuthenticationLevel, and ImpersonationLevel.
SWbemServices | Creates, updates, and retrieves instances or classes.
SWbemSink | Receives the results of asynchronous operations and event notifications, which are used by client applications.


SWbemEventSource

The SWbemEventSource object retrieves events from an event query in conjunction with SWbemServices.ExecNotificationQuery. You get an SWbemEventSource object if you make a call to SWbemServices.ExecNotificationQuery to make an event query. You can then use the NextEvent method to retrieve events as they arrive.

Methods

The following table lists the method for the SWbemEventSource object.

Method | Description
NextEvent | Used to retrieve an event in conjunction with SWbemServices.ExecNotificationQuery.

Properties

The following table lists the property for the SWbemEventSource object.

Property | Description
Security_ | Used to read or change the security settings.


SWbemEventSource.NextEvent

If an event is available, the NextEvent method of the SWbemEventSource object retrieves the event from an event query.

The following syntax is language-neutral. For an explanation of this syntax, see Document Conventions.

objObject = objwbemEventsource.NextEvent(
[iTimeoutMs = wbemTimeoutInfinite]
)

Parameters

iTimeoutMs
Optional. Number of milliseconds the call will wait for an event before returning a time-out error. The default value for this parameter is wbemTimeoutInfinite (-1), which directs the call to wait indefinitely.

Return Values

If the NextEvent method is successful, it returns a SWbemObject object containing the requested event. If the call times out, the returned object will be NULL and an error will be raised.

Error Codes

The NextEvent method can return the error code listed in the following table.

Error | Meaning
wbemErrTimedOut 0x80043001 | Requested event did not arrive in the amount of time specified in iTimeoutMs.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemEventSource.Security_

The Security_ property of the SWbemEventSource object reads or sets the security settings of an SWbemEventSource object. This property is an SWbemSecurity object.

The following syntax is language-neutral. For an explanation of this syntax, see Document Conventions.

objwbemSecurity = objwbemEventSource.Security_

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

WMI Scripting Security Issues, Object Creation and Monikers


SWbemLastError

The methods and properties of the SWbemLastError object contain and manipulate error objects. The methods and properties of this interface are exactly the same as those of the SWbemObject object, but are used to contain error information instead of CIM class infromation.

You can create an SWbemLastError error object to inspect the extended error information associated with a previous method call. If error information is not available, an attempt to create an error object will fail. If the call succeeds and an error object returns, the status of the object is reset. Further attempts to retrieve a error object will fail until a new error takes place. If you make an asynchronous call that fails, an SWbemLastError object may be returned to you by the SWbemSink.OnCompleted event in the parameter, objWbemErrorObject.

Methods

The following table lists the methods for the SWbemLastError object.

Method | Description
Associators_ | Retrieves the associators of the object.
AssociatorsAsync_ | Asynchronously retrieves the associators of the object.
Clone_ | Makes a copy of the current object.
CompareTo_ | Tests two objects for equality.
Delete_ | Deletes the object from WMI.
DeleteAsync_ | Asynchronously deletes the object from WMI.
ExecMethod_ | Executes a method exported by a method provider.
ExecMethodAsync_ | Asynchronously executes a method exported by a method provider.
GetObjectText_ | Retrieves the textual representation of the object written with MOF syntax.
Instances_ | Returns a collection of instances of the object, which must be a CIM class.
InstancesAsync_ | Asynchronously returns a collection of instances of the object, which must be a CIM class.
Put_ | Creates or updates the object in WMI.
PutAsync_ | Asynchronously creates or updates the object in WMI.
References_ | Returns references to the object.
ReferencesAsync_ | Asynchronously returns references to the object.
SpawnDerivedClass_ | Creates a new derived class from the current object, which must be a CIM class.
SpawnInstance_ | Creates a new instance from the current object.
Subclasses_ | Returns a collection of subclasses of the object, which must be a CIM class.
SubclassesAsync_ | Asynchronously returns a collection of subclasses of the object, which must be a CIM class.
ExecMethod_ | Executes a method on the object.
ExecMethodAsync_ | Asynchronously executes a method on the object.

Properties

The following table lists the properties for the SWbemLastError object.

Property | Description
Derivation_ | Contains an array of strings describing the derivation hierarchy for the class.
Methods_ | Represents the collection of methods of the SWbemLastError object. This property is an SWbemMethodSet object.
Path_ | Contains an SWbemObjectPath object that represents the object path of the current class or instance.
Properties_ | Represents the collection of properties of the SWbemLastError object. This property is an SWbemPropertySet object.
Qualifiers_ | Represents the collection of qualifiers of the SWbemLastError object. This property is an SWbemQualifierSet object.
Security_ | Contains an SWbemSecurity object that is used to read or change the security settings.


SWbemLastError.Associators_

The Associators_ method of the SWbemLastError object returns endpoints, a collection of classes or instances that are associated with the current object. This method performs the same function that the WMI Query Language (WQL) ASSOCIATORS OF statement performs.

The following syntax is language-neutral. For an explanation of this syntax, see Document Conventions.

objWbemObjectSet = objwbemObject.Associators_(
[strAssocClass=""],
[strResultClass=""],
[strResultRole=""],
[strRole=""],
[bClassesOnly=FALSE],
[bSchemaOnly=FALSE],
[strRequiredAssocQualifier=""],
[strRequiredQualifier  =""],
[iFlags=wbemFlagReturnImmediately],
[objwbemNamedValueSet=null]
)

Parameters

strAssocClass
Optional. String that contains an association class. If specified, this parameter indicates that the returned endpoints must be associated with the source through the specified association class or a class derived from this association class.
strResultClass
Optional. String that contains a class name. If specified, this parameter indicates that the returned endpoints must belong to or be derived from the class specified in this parameter.
strResultRole
Optional. String that contains a property name. If specified, this parameter indicates that the returned endpoints must play a specific role in their association with the source object. The role is defined by the name of a specified property—which must be a reference property—of an association.
strRole
Optional. String that contains a property name. If specified, this parameter indicates that the returned endpoints must be part of an association with the source object, in which the source object plays a particular role. The role is defined by the name of a specified property—which must be a reference property—of an association.
bClassesOnly
Optional. Boolean value that if set to TRUE indicates a list of class names should be returned instead of actual instances of the classes. The default value for this parameter is FALSE.
bSchemaOnly

Optional. Boolean value that indicates whether the query applies to schema rather than data. The default value of this parameter is FALSE. It can be set to TRUE only if the strObjectPath parameter specifies the object path of a class. When set to TRUE, the set of returned endpoints represent classes that are suitably associated with the source class in schema. See Schema Queries for more information.

strRequiredAssocQualifier
Optional. String that contains a qualifier name.

If specified, this parameter indicates that the returned endpoints must be associated with the source object through an association class that includes this qualifier. This type of filtering is used to eliminate broad ranges of endpoints unless the endpoints are associated with the target through a particular set of tagged association classes.

strRequiredQualifier
Optional. String that contains a qualifier name.

If specified, this parameter indicates that the returned endpoints must include this qualifier.

iFlags
Optional. Integer specifying additional flags to the operation.

The default for this parameter is wbemFlagReturnImmediately. This parameter can accept the following values.
Value Meaning
wbemFlagForwardOnly
0x20 		Causes a forward-only enumerator to be returned.

Forward-only enumerators are generally much faster and use less memory than conventional enumerators, but they do not allow calls to the Clone_ or Reset_ methods.

wbemFlagBidirectional
0x0 		Causes WMI to retain pointers to objects of the enumeration until the client releases the enumerator.
wbemFlagReturnImmediately
0x10 		Causes the call to return immediately.
wbemFlagReturnWhenComplete
0x0 		Causes this call to block execution of the application until the query has completed.

objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object, whose elements represent the context information that can be used by the provider servicing the request. A provider that supports or requires such context information must document the value names recognized, data type of the value, allowed values, and semantics.

Return Values

If the Associators method is successful, it returns an SWbemObjectSet object.

Error Codes

The Associators_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | Current user does not have permission to view one or more of the classes returned by the call.
wbemErrFailed 0x80041001 | Unspecified error.
wbemErrInvalidParameter 0x80041008 | Invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | Not enough memory to complete the operation.

Remarks

For information about the associated WQL statement ASSOCIATORS OF, source instances, and endpoints, see Data Queries.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemServices.AssociatorsOf, SWbemServices.ReferencesTo, SWbemLastError.References_


SWbemLastError.AssociatorsAsync_

The AssociatorsAsync_ method of the SWbemLastError object asynchronously returns endpoints. This method performs the same function that the WMI Query Language (WQL) ASSOCIATORS OF statement performs. A call to this method returns immediately; the results and status will be returned to the caller through the supplied object sink.

The following syntax is language-neutral. For an explanation of this syntax, see Document Conventions.

objwbemObject.AssociatorsAsync_(
objWbemSink,
[strAssocClass=""],
[strResultClass=""],
[strResultRole=""],
[strRole=""],
[bClassesOnly=FALSE],
[bSchemaOnly=FALSE],
[strRequiredAssocQualifier=""],
[strRequiredQualifier  =""],
[iFlags],
[objwbemNamedValueSet=null]
[objWbemAsyncContext]
)

Parameters

objWbemSink
Required. Object sink that receives the objects asynchronously.
strAssocClass
Optional. String that contains an association class. If specified, this parameter indicates that the returned endpoints must be associated with the source through the specified association class or a class derived from this association class.
strResultClass
Optional. String that contains the name of a class. If specified, this parameter indicates that the returned endpoints must belong to or be derived from the class specified in this parameter.
strResultRole
Optional. String that contains the name of a property that will be the role in this call.. If specified, this parameter indicates that the returned endpoints must play a specific role in their association with the source object. The role is defined by the name of a this property—which must be a reference property—of an association.
strRole
Optional. String that contains the name of a property. If specified, this parameter indicates that the returned endpoints must participate in an association with the source object, in which the source object plays a particular role. The role is defined by the name of a specified property—which must be a reference property—of an association.
bClassesOnly
Optional. This is a Boolean value that indicates whether a list of class names should be returned rather than actual instances of the classes.

These are the classes to which The endpoint instances belong. The default value for this parameter is FALSE.

bSchemaOnly
Optional. This is a

Boolean value that indicates whether the query applies to schema rather than data.

The default value for this parameter is FALSE. It can only be set to TRUE if the strObjectPath parameter specifies the object path of a class. When set to TRUE, the set of returned endpoints represent classes that are suitably associated with the source class in schema.

strRequiredAssocQualifier
Optional. This is a string that contains a qualifier name.

this parameter, if specified, indicates that the returned endpoints must be associated with the source object through an association class that includes the specified qualifier.

strRequiredQualifier
Optional. This is a string that contains a qualifier name.

This parameter, if specified, indicates that the returned endpoints must include the specified qualifier.

iFlags
Optional. This is an integer specifying additional flags to the operation. This parameter can accept the following values.
Value Meaning
wbemFlagSendStatus
0x80 		This flag causes asynchronous calls to send status updates to the OnProgress event handler for your object sink.
wbemFlagDontSendStatus
0x0 		This flag prevents asynchronous calls from sending status updates to the OnProgress event handler for your object sink

objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider servicing the request. A provider that supports or requires such information must document the value names recognized, data type of the value, allowed values, and semantics.
objWbemAsyncContext
Optional. This is an object of type SWbemNamedValueSet that returns to the object sink to identify the source of the original asynchronous call.

Use this parameter if you are making multiple asynchronous calls using the same object sink. To use this parameter, create an SWbemNamedValueSet object and use the SWbemNamedValueSet.Add method to add a value that identifies the asynchronous call you are making. This SWbemNamedValueSet object will be returned to the object sink and the source of the call can be extracted using the SWbemNamedValueSet.item method. For more information, see Making an Asynchronous Call Using the Scripting API.

Return Values

An object of type SWbemSink is returned by this call. The results of the asynchronous call are provided through this sink as an object of type SWbemObjectSet.

Error Codes

The AssociatorsAsync_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user does not have permission to view one or more of the classes returned by the call.
wbemErrFailed 0x80041001 | There is an unspecified error.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Remarks

For information about the associated WQL query "Associators Of", source instances and endpoints see Data Queries.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemServices.AssociatorsOfAsync, SWbemServices.ReferencesTo, SWbemLastError.References_


SWbemLastError.Clone_

The Clone_ method of the SWbemLastError object returns a new object that is a clone of the current object.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objObject = objwbemObject.Clone_()

Return Values

If successful, a new SWbemLastError returns.

Error Codes

The Clone_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrInvalidParameter 0x80041008 | Nothing was specified as a parameter, and it is not acceptable in this usage.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to clone the object.

Remarks

Use this method to duplicate a class definition or instance. This is useful when you need the original copy of the object for backup purposes while you are modifying a new copy. Likewise, you can use this method to create many new instances from a single source instance. For example, you can use SWbemLastError.SpawnInstance_ to create a single starting instance, and use SWbemLastError.Clone_ to produce 100 copies of the instance quickly. Subsequently, you can modify the objects, giving each one specific values.

It is not possible to use this method to convert a class definition to an instance, or to convert an instance to a class definition.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemLastError.CompareTo_

The CompareTo_ method of the SWbemLastError object compares two SWbemObject type objects. This comparison is subject to certain constraints based on the values specified in the iFlags parameter.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

bAreEqual = objwbemObject.CompareTo_(
objwbemObject,
[iFlags= wbemComparisonFlagIncludeAll]
)

Parameters

objwbemObject
Required. This parameter is an Object of class SWbemObject

This is the object with which the first object is compared. The object must be a valid SWbemObject instance, and it cannot be undefined.

iFlags
Optional.

It specifies the object characteristics to consider when comparing an object with other objects. You can use wbemComparisonFlagIncludeAll to consider all features (this is the default), or any combination of the following values.
Value Meaning
wbemComparisonFlagIncludeAll
0x0 		Use this flag to compare all properties, qualifiers, and flavors, or use one of the other flags listed below to ignore any of these items.
wbemComparisonFlagIgnoreObjectSource
0x2 		The source of the objects, namely the server and the namespace they came from, are ignored in comparison to other objects.
wbemComparisonFlagIgnoreQualifiers
0x1 		All qualifiers (including "key" and "dynamic") should be ignored in comparison.
wbemComparisonFlagIgnoreDefaultValues
0x4 		Default values of properties should be ignored. This flag is only meaningful when comparing classes.
wbemComparisonFlagIgnoreFlavor
0x20 		Ignore qualifier flavors. This flag still takes qualifier values into account, but ignores flavor distinctions such as propagation rules and override restrictions.
wbemComparisonFlagIgnoreCase
0x10 		Compares string values in a case-insensitive manner. This applies both to strings and to qualifier values. Property and qualifier names are always compared in a case-insensitive manner whether this flag is specified or not.
wbemComparisonFlagIgnoreClass
0x8 		This flag instructs the system to assume that the objects being compared are instances of the same class. Consequently, this flag compares instance-related information only. Use this flag to optimize performance. If the objects are not of the same class, the results will be undefined.

Return Values

This method returns the Boolean value TRUE if the objects match or FALSE if they do not.

Error Codes

The CompareTo_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemObject


SWbemLastError.Delete_

The Delete_ methodSWbemLastError of the SWbemLastError object deletes the current class or instance.

If a dynamic provider supplied the class or instance, it is sometimes not possible to delete this object unless the provider supports class or instance deletion.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemObject.Delete_(
[iFlags=0],
[objwbemNamedValueSet=null]
)

Parameters

iFlags
Optional. This parameter is reserved and must be zero if specified.
objwbemNamedValueSet
Optional. This parameter is typically undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request.

A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.

Return Values

This method had no return values.

Error Codes

The Delete_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current context does not have adequate security rights to delete the object.
wbemErrFailed 0x8004100 | This is an unspecified error.
wbemErrInvalidClass 0x80041010 | The specified class does not exist.
wbemErrInvalidOperation 0x80041016 | The object cannot be deleted.
wbemErrNotFound 0x80041002 | The object did not exist.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemLastError.DeleteAsync_

The DeleteAsync_ method of the SWbemLastError object asynchronously deletes the current class or instance. This call will return immediately and the results of the delete operation will be returned to the caller through the supplied object sink.

If a dynamic provider supplied the class or instance, it is sometimes not possible to delete this object unless the provider supports class or instance deletion.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemObject.DeleteAsync_(
objWbemSink
[iFlags=0],
[objwbemNamedValueSet=null]
[objWbemAsyncContext]
)

Parameters

objWbemSink
This parameter is the object sink that returns the outcome of the delete operation.
iFlags
Optional. This is an integer that determines the behavior of the call. This parameter can accept the following values.
Value Meaning
wbemFlagSendStatus
0x80 		This flag causes asynchronous calls to send status updates to the OnProgress event handler for your object sink.
wbemFlagDontSendStatus
0x0 		This flag prevents asynchronous calls from sending status updates to the OnProgress event handler for your object sink

objwbemNamedValueSet
Optional. This parameter is typically undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.
objWbemAsyncContext
Optional. This is an object of type SWbemNamedValueSet that returns to the object sink to identify the source of the original asynchronous call. Use this parameter if you are making multiple asynchronous calls using the same object sink. To use this parameter, create an SWbemNamedValueSet object and use the SWbemNamedValueSet.Add method to add a value that identifies the asynchronous call you are making. This SWbemNamedValueSet object will be returned to the object sink and the source of the call can be extracted using the SWbemNamedValueSet.item method. For more information, see Making an Asynchronous Call Using the Scripting API.

Return Values

None. If this call is successful the result of the delete operation will be provided through the supplied object sync.

Error Codes

The DeleteAsync_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current context does not have adequate security rights to delete the object.
wbemErrFailed 0x8004100 | This is an unspecified error.
wbemErrInvalidClass 0x80041010 | The specified class does not exist.
wbemErrInvalidOperation 0x80041016 | The object cannot be deleted.
wbemErrNotFound 0x80041002 | The object did not exist.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemLastError.Derivation_

The Derivation_ property of the SWbemLastError object contains an array of strings that describe the class derivation hierarchy for the instance being referenced. The contents are in most-derived-from order. That is, the first element in the array defines the superclass and the last element defines the dynasty class. This property is read-only.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

strClassArray = objwbemObject.Derivation_

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemLastError.ExecMethod_

The ExecMethod_ method of the SWbemLastError object executes a method exported by a method provider. This method is similar to SWbemServices.ExecMethod, but it operates directly on the object whose method is to be executed.

Use SWbemLastError.ExecMethod_ as an alternate way to execute a method in cases where it is not possible to execute a method directly. For example, you would need to use it with a scripting language such as Microsoft JScript that does not support output parameters, if your method has out parameters. Otherwise, the recommended means of invoking a method is to use direct method invocation. Direct method invocation is executing a method by using object.method syntax. For more information on direct method invocation, see Direct Access.

This method will block while the method that is forwarded to the appropriate provider executes. The information and status are then returned.

WMI does not implement the methods directly. The method providers export the methods.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objOutParams = objwbemObject.ExecMethod_(
strMethodName,
[objwbemInParams=null],
[iFlags=0],
[objwbemNamedValueSet=null]
)

Parameters

strMethodName
Required. This is the name of the method for the object.
objwbemInParams
Optional. This is an SWbemObject object that contains the input parameters for the method being executed.
To construct the objwbemInParams parameter
  1. Call SWbemObject.Methods_.Item("MethodName") to get an SWbemMethod object that contains the properties that describe the method, where "MethodName" is the name of the method to retrieve.
  2. Use the SWbemMethod.InParameters property of the SWbemMethod object to get an InParameters object.
  3. Call SpawnInstance_ on the InParameters object to create an instance.
  4. Set the properties of the instance to whatever values are appropriate. For example, If you want to set an input parameter named myinputparam to the value "whatever" in an instance of InParameters called "INST", the code would look like this: INST.Properties_.Add ("myinputparam").Value = "Whatever"

    The default value for this parameter is undefined.

iFlags
Optional. This parameter is reserved and must be set to zero if specified.
objwbemNamedValueSet
Optional. Typically, it is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.

Return Values

A object of SWbemObject returns if this call is successful. The returned object contains the out parameters and return value for the method being executed.

Error Codes

The ExecMethod_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrInvalidClass 0x80041010 | The specified class was invalid.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.
wbemErrInvalidMethod 0x8004102E | The requested method was not available.
wbemErrAccessDenied 0x80041003 | The current user was not authorized to execute the method.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemServices.ExecMethod, SWbemObject.ExecMethodAsync_


SWbemLastError.ExecMethodAsync_

The ExecMethodAsync_ method of the SWbemLastError object asynchronously executes a method exported by a method provider. This method is similar to SWbemServices.ExecMethodAsync, but it operates directly on the object whose method is to be executed.

Use SWbemLastError.ExecMethodAsync_ as an alternate way to execute a method in cases where it is not possible to execute a method directly. For example, you would need to use it with a scripting language such as Microsoft JScript that does not support output parameters, if your method has out parameters. Otherwise, the recommended means of invoking a method is to use direct method invocation. Direct method invocation is executing a method by using object.method syntax. For more information on direct method invocation, see Direct Access.

This call will return immediately and the results of the put operation will be returned to the caller through the supplied object sink.

WMI does not implement the methods directly. The method providers export the methods.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objOutParams = objwbemObject.ExecMethodAsync_(
objWbemSink,
strMethodName,
[objwbemInParams=null],
[iFlags=0],
[objwbemNamedValueSet=null]
[objWbemAsyncContext]
)

Parameters

objWbemSink
Required. This is the object sink that receives the result of the method call. The outbound parameters are sent to the SWbemSink.OnObjectReady event of the supplied object sink. The result of the call mechanism itself will be sent to the SWbemSink.OnCompleted event of the supplied object sink. Notice that SWbemSink.OnCompleted does not receive the return code of the CIM method. However, it receives the return code of the actual call-return mechanism, and is only useful for verifying that the call occurred or that it failed for mechanical reasons. The result code returned from the CIM method is returned in the outbound parameter object supplied to SWbemSink.OnObjectReady. If any error code returns, then the supplied IWbemObjectSink object will not be used. If the call is successful, then the user's IWbemObjectSink implementation will be called to indicate the result of the operation.
strMethodName
Required. This is the name of the method for the object.
objwbemInParams
Optional. This is an SWbemObject object that contains the input parameters for the method being executed.
To construct the objwbemInParams parameter
  1. Call SWbemObject.Methods_.Item("MethodName") to get an SWbemMethod object that contains the properties that describe the method, where "MethodName" is the name of the method to retrieve.
  2. Use the SWbemMethod.InParameters property of the SWbemMethod object to get an InParameters object.
  3. Call SpawnInstance_ on the InParameters object to create an instance.
  4. Set the properties of the instance to whatever values are appropriate. For example, If you want to set an input parameter named myinputparam to the value "whatever" in an instance of InParameters called "INST", the code would look like this: INST.Properties_.Add ("myinputparam").Value = "Whatever"

    The default value for this parameter is undefined.

iFlags
Optional. This is an integer that determines the behavior of the call. This parameter can accept the following values.
Value Meaning
wbemFlagSendStatus
0x80 		This flag causes asynchronous calls to send status updates to the OnProgress event handler for your object sink.
wbemFlagDontSendStatus
0x0 		This flag prevents asynchronous calls from sending status updates to the OnProgress event handler for your object sink

objwbemNamedValueSet
Optional. Typically, it is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.
objWbemAsyncContext
Optional. This is an object of type SWbemNamedValueSet that returns to the object sink to identify the source of the original asynchronous call. Use this parameter if you are making multiple asynchronous calls using the same object sink. To use this parameter, create an SWbemNamedValueSet object and use the SWbemNamedValueSet.Add method to add a value that identifies the asynchronous call you are making. This SWbemNamedValueSet object will be returned to the object sink and the source of the call can be extracted using the SWbemNamedValueSet.item method. For more information, see Making an Asynchronous Call Using the Scripting API.

Return Values

None. An object of type SWbemObject returns to the supplied sink if this call is successful. The returned object contains the out parameters and return value for the method being executed.

Error Codes

The ExecMethodAsync_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrInvalidClass 0x80041010 | The specified class was invalid.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.
wbemErrInvalidMethod 0x8004102E | The requested method was not available.
wbemErrAccessDenied 0x80041003 | The current user was not authorized to execute the method.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemServices.ExecMethodAsync


SWbemLastError.GetObjectText_

The GetObjectText_ method of the SWbemLastError object returns a textual rendering of the object. This interface can be used to display an object's contents. Currently, only the Managed Object Format (MOF) syntax is supported as an output format. Notice that the MOF text returned does not contain all the information about the object, but only enough information for the MOF compiler to be able to re-create the original object. For instance, you will not find any information about the propagated qualifiers or the parent class properties.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

strMofText = objwbemObject.GetObjectText_(
[iFlags=0]
)

Parameters

iFlags
Optional. This parameter is reserved and must be zero if specified.

Return Values

If successful, this method will return a string that contains the output text.

Error Codes

The GetObjectText_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemLastError.Instances_

The Instances_ method of the SWbemLastError object creates an enumerator that returns the instances of the current class object. This method implements a simple query. More complex queries may require the use of SWbemServices.ExecQuery.

Note This method only works for class objects. It is not an error for the returned collection to have zero elements.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objWbemObjectSet = objwbemObject.Instances_(
[iFlags=wbemFlagReturnImmediately],
[objwbemNamedValueSet=null]
)

Parameters

iFlags
Optional. This parameter is reserved and must be zero if specified.
objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics. This parameter is optional.

Return Values

If successful, an object of type an object of type SWbemObjectSet returns.

Error Codes

The Instances_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user does not have permission to view instances of the specified class.
wbemErrFailed 0x80041001 | An unspecified error occurred.
wbemErrInvalidClass 0x80041010 | The specified class is invalid.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemObjectSet


SWbemLastError.InstancesAsync_

The InstancesAsync_ method of the SWbemLastError object asynchronously creates an enumerator that returns the instances of the current class object. This method implements a simple query. More complex queries may require the use of SWbemServices.ExecQueryAsync. This call will return immediately and the results of the call will be returned to the caller through the supplied object sink.

Note This method only works for class objects. It is not an error for the returned collection to have zero elements.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemObject.InstancesAsync_(
[objWbemSink ]
[iFlags],
[objwbemNamedValueSet=null],
[objWbemAsyncContext]
)

Parameters

objWbemSink
This parameter is the object sink that will return the instances.
iFlags
Optional. This is an integer that determines the behavior of the call. This parameter can accept the following values.
Value Meaning
wbemFlagSendStatus
0x80 		This flag causes asynchronous calls to send status updates to the OnProgress event handler for your object sink.
wbemFlagDontSendStatus
0x0 		This flag prevents asynchronous calls from sending status updates to the OnProgress event handler for your object sink

objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics. This parameter is optional.
objWbemAsyncContext
Optional. This is an object of type SWbemNamedValueSet that returns to the object sink to identify the source of the original asynchronous call. Use this parameter if you are making multiple asynchronous calls using the same object sink. To use this parameter, create an SWbemNamedValueSet object and use the SWbemNamedValueSet.Add method to add a value that identifies the asynchronous call you are making. This SWbemNamedValueSet object will be returned to the object sink and the source of the call can be extracted using the SWbemNamedValueSet.item method. For more information, see Making an Asynchronous Call Using the Scripting API.

Return Values

None. If this call is successful, the results of the asynchronous call are provided through this sync as an object of type SWbemObjectSet.

Error Codes

The InstancesAsync_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user does not have permission to view instances of the specified class.
wbemErrFailed 0x80041001 | An unspecified error occurred.
wbemErrInvalidClass 0x80041010 | The specified class is invalid.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemObjectSet


SWbemLastError.Methods_

The Methods_ property of the SWbemLastError object returns an SWbemMethodSet object that is a collection of the CIM methods for the current class or instance. This property is read-only.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objMethodSet = objwbemObject.Methods_

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemLastError.Path_

The Path_ property of the SWbemLastError object returns an SWbemObjectPath object that represents the object path of the current class or instance. This property can be passed as a parameter to methods that require an object path.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objObjectPath = objwbemObject.Path_

Remarks

Only the Class property of the returned SWbemObjectPath instance can be modified. If you try to modify any other property, or try to call the methods SetAsClass or SetAsSingleton, you will get an error of wbemErrReadOnly.

Because of this, you cannot modify the SWbemNamedValueSet that is the value of the Keys property of the returned SWbemObjectPath instance. If you try to call the methods Add, Remove, or DeleteAll on this value, you will get an error of wbemErrReadOnly. Furthermore, you will not be able to modify any SWbemNamedValue obtained from this collection. Attempts to modify the Value property will return the same error code.

However, if you call SWbemObject.Clone_ to create a copy, the Path_ property of the copy is fully modifiable.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemLastError.Properties_

The Properties_ property of the SWbemLastError object returns an SWbemPropertySet object that is a collection of the CIM properties for the current class or instance. This property is read-only.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objPropertySet = objwbemObject.Properties_

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemLastError.Put_

The Put_ method of the SWbemLastError object creates or updates an instance or class object to WMI. You can use this method after you have modified any properties or methods in an SWbemObject object and your changes will be written to WMI.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objObjectPath = objwbemObject.Put_(
[iFlags= wbemChangeFlagCreateOrUpdate],
[objwbemNamedValueSet=null]
)

Parameters

iFlags
Optional. This parameter determines if the call will create or update the class or instance and if the call will return right away or not. This parameter can accept the following values.
Value Meaning
wbemChangeFlagUpdateCompatible
0x0 		This flag allows a class to be updated if there are no derived classes and there are on instances for that class. It also allows updates in all cases if the change is just to non-important qualifiers (for example the description qualifier). This is the default behavior for this call and is used for compatibility with previous versions of WMI. If the class has instances the update will fail.
wbemChangeFlagUpdateSafeMode
0x20 		This flag allows updates of classes even if there are child classes as long as the change does not cause any conflicts with child classes. An example of an update in this flag would allow would be to add a new property to the base class that was not previously mentioned in any of the child classes. If the class has instances the update will fail.
WbemChangeFlagUpdateForceMode
0x40 		This flag forces updates of classes when conflicting child classes exist. For example, this flag will force an update if a class qualifier was defined in a child class, and the base class tries to add the same qualifier and in conflict with the existing one. In force mode this conflict would be resolved by deleting the conflicting qualifier in the child class. If the class has instances the update will fail.
wbemChangeFlagCreateOrUpdate
0x0 		This flag causes the class or instance to be created if it does not exist or overwritten if it exists already.
wbemChangeFlagCreateOnly
0x2 		This flag is used for creation only. The call will fail if the class or instance already exists.
wbemChangeFlagUpdateOnly
0x1 		This flag causes this call to update. The class or instance must exist for the call to be successful.
wbemFlagReturnImmediately
0x10 		This flag causes the call to return immediately.
wbemFlagReturnWhenComplete
0x0 		This flag causes this call to block until the query has completed.

objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.

Return Values

If the call is successful, an object of type SWbemObjectPath will be returned. This will contain the object path of the instance or class that has been successfully committed to WMI.

Error Codes

The Put_ method can return the error codes listed in the following table.

Error | Meaning
MeaninwbemErrAccessDenied 0x80041003 | The current user does not have permission to update an instance of the specified class.
wbemErrAlreadyExists 0x80041019 | wbemChangeFlagCreateOnly flag was specified, but the instance already exists.
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrIllegalNull 0x8004100A | A value of Nothing was specified for a property that may not be Nothing, such as one that is marked by a key, indexed, or not_null qualifier.
wbemErrInvalidObject 0x80041014 | The specified instance is invalid.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrNotFound 0x80041002 | wbemChangeFlagUpdateOnly flag was specified, but the instance or class does not exist.
wbemErrIncompleteClass 0x80041020 | Required properties for classes have not all been set.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemObjectPath.Class, SWbemQualifier, SWbemProperty


SWbemLastError.PutAsync_

The PutAsync_ method of the SWbemLastError object creates or updates an instance or class object to WMI. You can use this method after you have modified any properties or methods in an SWbemObject object and your changes will be written to WMI. This call will return immediately and the results of the put operation will be returned to the caller through the supplied object sink.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemObject.PutAsyncAsync_(
objWbemSink,
[iFlags= wbemChangeFlagCreateOrUpdate],
[objwbemNamedValueSet=null],
[objWbemAsyncContext]
)

Parameters

objWbemSink
Required. This is the object sink that will asynchronously receive the result of the put operation.
iFlags
Optional. This parameter determines if the call will create or update the class or instance and if the call will return right away or not. This parameter can accept the following values.
Value Meaning
wbemChangeFlagUpdateCompatible
0x0 		This flag allows a class to be updated if there are no derived classes and there are on instances for that class. It also allows updates in all cases if the change is just to non-important qualifiers (for example the description qualifier). This is the default behavior for this call and is used for compatibility with previous versions of Window Management. If the class has instances the update will fail.
wbemChangeFlagUpdateSafeMode
0x20 		This flag allows updates of classes even if there are child classes as long as the change does not cause any conflicts with child classes. An example of an update in this flag would allow would be to add a new property to the base class that was not previously mentioned in any of the child classes. If the class has instances the update will fail.
WbemChangeFlagUpdateForceMode
0x40 		This flag forces updates of classes when conflicting child classes exist. For example, this flag will force an update if a class qualifier was defined in a child class, and the base class tries to add the same qualifier and in conflict with the existing one. In force mode this conflict would be resolved by deleting the conflicting qualifier in the child class. If the class has instances the update will fail.
wbemChangeFlagCreateOrUpdate
0x0 		This flag causes the class or instance to be created if it does not exist or overwritten if it exists already.
wbemChangeFlagCreateOnly
0x2 		This flag is used for creation only. The call will fail if the class or instance already exists.
wbemChangeFlagUpdateOnly
0x1 		This flag causes this call to update. The class or instance must exist for the call to be successful.
wbemFlagReturnImmediately
0x10 		This flag causes the call to return immediately.
wbemFlagReturnWhenComplete
0x0 		This flag causes this call to block until the query has completed.
wbemFlagSendStatus
0x80 		This flag causes asynchronous calls to send status updates to the OnProgress event handler for your object sink.
wbemFlagDontSendStatus
0x0 		This flag prevents asynchronous calls from sending status updates to the OnProgress event handler for your object sink

objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.
objWbemAsyncContext
Optional. This is an object of type SWbemNamedValueSet that returns to the object sink to identify the source of the original asynchronous call. Use this parameter if you are making multiple asynchronous calls using the same object sink. To use this parameter, create an SWbemNamedValueSet object and use the SWbemNamedValueSet.Add method to add a value that identifies the asynchronous call you are making. This SWbemNamedValueSet object will be returned to the object sink and the source of the call can be extracted using the SWbemNamedValueSet.item method. For more information, see Making an Asynchronous Call Using the Scripting API.

Return Values

None. If the call is successful, the OnObjectPut event of the supplied object sink will receive an object of type SWbemObjectPath, containing the object path of the instance or class that has been successfully committed to WMI.

Error Codes

The PutAsync_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user does not have permission to update an instance of the specified class.
wbemErrAlreadyExists 0x80041019 | wbemChangeFlagCreateOnly flag was specified, but the instance already exists.
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrIllegalNull 0x8004100A | A value of Nothing was specified for a property that may not be Nothing, such as one that is marked by a key, indexed, or not_null qualifier.
wbemErrInvalidObject 0x80041014 | The specified instance is invalid.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrNotFound 0x80041002 | wbemChangeFlagUpdateOnly flag was specified, but the instance or class does not exist.
wbemErrIncompleteClass 0x80041020 | Required properties for classes have not all been set.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemObjectPath.Class, SWbemQualifier, SWbemProperty


SWbemLastError.Qualifiers_

The Qualifiers_ property of the SWbemLastError object returns an SWbemQualifierSet object that is a collection of the CIM qualifiers for the current class or instance. This property is read-only.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objQualifierSet = objwbemObject.Qualifiers_

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemLastError.References_

The References_ method of the SWbemLastError object returns a collection of all association classes or instances that refer to the current object.

This method performs the same function that the WQL "References Of" query performs.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objWbemObjectSet = objwbemObject.References_(
[strResultClass=""],
[strRole=""],
[bClassesOnly=FALSE],
[bSchemaOnly=FALSE],
[strRequiredQualifier=""],
[iFlags=wbemFlagReturnImmediately],
[objwbemNamedValueSet=null]
)

Parameters

strResultClass
Optional. This is a string that contains a class name. This parameter, if specified, indicates that the returned association objects must belong to or be derived from the class specified in this parameter.
strRole
Optional. This is a string that contains a property name. If specified, this parameter indicates that the returned association objects must be limited to those in which the source object plays a particular role. The role is defined by the name of a specified property—which must be a reference property—of an association.
bClassesOnly
Optional. This is a Boolean value that indicates whether a list of class names should be returned rather than actual instances of the classes. These are the classes to which the association objects belong. The default value for this parameter is FALSE.
bSchemaOnly
Optional. This is a Boolean value that indicates whether the query applies to schema rather than data. The default value for this parameter is FALSE. It can only be set to TRUE if the strObjectPath parameter specifies the object path of a class. When set to TRUE, the set of returned endpoints represent classes that are suitably associated with the source class in schema.
strRequiredQualifier
Optional. This is a string that contains a qualifier name. This parameter, if specified, indicates that the returned association objects must include the specified qualifier.
iFlags
Optional. This is an integer specifying additional flags to the operation. The default for this parameter is wbemFlagReturnImmediately, which directs the call to return immediately rather than wait until the query has completed. This parameter can accept the following values.
Value Meaning
wbemFlagForwardOnly
0x20 		This flag causes a forward-only enumerator to be returned. Forward-only enumerators are generally much faster and use less memory than conventional enumerators, but they do not allow calls to Clone or Reset.
wbemFlagBidirectional
0x0 		This flag causes WMI to retain pointers to objects of the enumeration until the client releases the enumerator.
wbemFlagReturnImmediately
0x10 		This flag causes the call to return immediately.
wbemFlagReturnWhenComplete
0x0 		This flag causes this call to block until the query has completed.

objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.

Return Values

If the call is successful, an object of type SWbemObjectSet will be returned.

Error Codes

The References_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user does not have permission to view one or more of the classes returned by the call.
wbemErrFailed 0x80041001 | There is an unspecified error.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Remarks

For information about the associated WQL query "References Of", source instances, and association objects, see Data Queries.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemServices.ReferencesTo, SWbemServices.AssociatorsOf, SWbemObject.Associators_


SWbemLastError.ReferencesAsync_

The ReferencesAsync_ method of the SWbemLastError object returns a collection of all association classes or instances that refer to the current object.

This method performs the same function that the WQL "References Of" query performs. This call will return immediately and the results and status will be returned to the caller through the supplied object sink.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemObject.ReferencesAsync_(
objWbemSink,
[strResultClass=""],
[strRole=""],
[bClassesOnly=FALSE],
[bSchemaOnly=FALSE],
[strRequiredQualifier=""],
[iFlags],
[objwbemNamedValueSet=null],
[objWbemAsyncContext]
)

Parameters

objWbemSink
Required. This is the object sink that will receive the objects asynchronously.
strResultClass
Optional. This is a string that contains a class name. This parameter, if specified, indicates that the returned association objects must belong to or be derived from the class specified in this parameter.
strRole
Optional. This is a string that contains a property name. If specified, this parameter indicates that the returned association objects must be limited to those in which the source object plays a particular role. The role is defined by the name of a specified property—which must be a reference property—of an association.
bClassesOnly
Optional. This is a Boolean value that indicates whether a list of class names should be returned rather than actual instances of the classes. These are the classes to which the association objects belong. The default value for this parameter is FALSE.
bSchemaOnly
Optional. This is a Boolean value that indicates whether the query applies to schema rather than data. The default value for this parameter is FALSE. It can only be set to TRUE if the strObjectPath parameter specifies the object path of a class. When set to TRUE, the set of returned endpoints represent classes that are suitably associated with the source class in schema.
strRequiredQualifier
Optional. This is a string that contains a qualifier name. This parameter, if specified, indicates that the returned association objects must include the specified qualifier.
iFlags
Optional. This is an integer specifying additional flags to the operation. This parameter can accept the following values.
Value Meaning
wbemFlagSendStatus
0x80 		This flag causes asynchronous calls to send status updates to the OnProgress event handler for your object sink.
wbemFlagDontSendStatus
0x0 		This flag prevents asynchronous calls from sending status updates to the OnProgress event handler for your object sink

objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.
objWbemAsyncContext
Optional. This is an object of type SWbemNamedValueSet that returns to the object sink to identify the source of the original asynchronous call. Use this parameter if you are making multiple asynchronous calls using the same object sink. To use this parameter, create an SWbemNamedValueSet object and use the SWbemNamedValueSet.Add method to add a value that identifies the asynchronous call you are making. This SWbemNamedValueSet object will be returned to the object sink and the source of the call can be extracted using the SWbemNamedValueSet.item method. For more information, see Making an Asynchronous Call Using the Scripting API.

Return Values

None. If successful, the results of the asynchronous call are provided through this sink as an object of type SWbemObjectSet. This object is a collection of all association classes or instances that refer to the current object.

Error Codes

The References_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user does not have permission to view one or more of the classes returned by the call.
wbemErrFailed 0x80041001 | There is an unspecified error.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Remarks

For information about the associated WQL query "References Of", source instances, and association objects, see Data Queries.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemServices.ReferencesTo,

SWbemServices.ReferencesToAsync, SWbemServices.AssociatorsOf, SWbemObject.Associators_


SWbemLastError.Security_

The Security_ property of the SWbemLastError object is used to read or set the security settings for an SWbemLastError object. This property is an object of type SWbemSecurity.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemSecurity = objwbemObject.Security_

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

Setting the DCOM Impersonation Level for the Scripting API, Object Creation and Monikers


SWbemLastError.SpawnDerivedClass_

Use the SpawnDerivedClass_ method of the SWbemLastError object to create a derived class object from the current object. The object must be a class definition that becomes the superclass of the spawned object.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objNewClass = objwbemObject.SpawnDerivedClass_(
[iFlags=0]
)

Parameters

iFlags
Optional. This parameter is reserved and must be zero if specified.

Return Values

If the call is successful, an object of type SWbemObject returns that contains the new class definition object. No object returns when there is an error.

Error Codes

The SpawnDerivedClass_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrFailed 0x8004100 | This is an unspecified error.
wbemErrIllegalOperation 0x8004101E | The user requested an illegal operation, such as spawning a class from an instance.
wbemErrIncompleteClass 0x80041020 | The source class was not completely defined or registered with WMI, so a new derived class is not permitted.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Remarks

The object returned automatically becomes a subclass of the current object. This behavior cannot be overridden. There is no other method by which you can create derived classes.

You cannot create a derived class from a class that is local to your own client process. Before you can use this method to create a derived class, you must create the base class. To create the base class, call SWbemObject.Put_, and retrieve it using SWbemServices.Get.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemLastError.SpawnInstance_

Use the SpawnInstance_ method of the SWbemLastError object to create a new instance of a class. The current object must be a class definition obtained from WMI via a method such as SWbemServices.Get or SWbemServices.ExecQuery. Then use this class definition to create new instances. Create each new instance locally within the process, and then call SWbemObject.Put_ to actually create the instance within WMI.

Note Spawning an instance from an instance is not allowed.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objNewInstance = objwbemObject.SpawnInstance_(
[iFlags=0]
)

Parameters

iFlags
Optional. This parameter is reserved and must be zero if specified.

Return Values

If successful, this call returns an object of type SWbemObject that contains a new instance of the class.

Error Codes

The SpawnInstance_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrIncompleteClass 0xH80041020 | The current object is not a valid class definition, and it cannot spawn new instances. Either it is incomplete, or it has not been registered with WMI using SWbemObject.Put_.
wbemErrIllegalOperation 0xH8004101E | Returned if this method is used on an instance instead of a class.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemServices.Get, SWbemObject.Put_


SWbemLastError.Subclasses_

The Subclasses_ method of the SWbemLastError object returns an object of type SWbemObjectSet. This object is a collection of subclasses of the current object, which must be a class. Items in the returned collection can be obtained by way of standard collection methods. See Collections for information on using collections.

Note It is not an error for the returned collection to have zero elements if there are no subclasses of the current object. This method only works for class objects.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objWbemObjectSet = objwbemObject.Subclasses_(
[iFlags= wbemFlagReturnImmediately+wbemQueryFlagDeep],
[objwbemNamedValueSet=null]
)

Parameters

iFlags
Optional. This determines how deep the enumeration will be. This parameter can accept the following values.
Value Meaning
wbemQueryFlagDeep
0 		This value forces recursive enumeration into all subclasses derived from the specified superclass. The superclass itself is not returned in the enumeration.
wbemQueryFlagShallow
0x1 		This is the default for this parameter. It forces the enumeration to include only immediate subclasses of the specified superclass.
WbemFlagReturnImmediately
0x10 		This flag causes the call to return immediately
wbemFlagReturnWhenComplete
0x0 		This flag causes this call to block until the call has completed.

objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.

Return Values

If the call is successful, an object of type SWbemObjectSet will be returned.

Error Codes

The Subclasses_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user does not have permission to view one or more of the classes returned by the call.
wbemErrFailed 0x80041001 | There is an unspecified error.
wbemErrInvalidClass 0x80041010 | The specified class did not exist.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemObjectSet


SWbemLastError.SubclassesAsync_

The SubclassesAsync_ method of the SWbemLastError object asynchronously returns a collection of subclasses of the current object, which must be a class. This call will return immediately and the results of the put operation will be returned to the caller through the supplied object sink. Items in the returned collection can be obtained by way of standard collection methods. See Collections for information on using collections.

Note It is not an error for the returned collection to have zero elements if there are no subclasses of the current object. This method only works for class objects.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemObject.SubclassesAsync_(
objWbemSink,
[iFlags= wbemQueryFlagDeep],
[objwbemNamedValueSet=null]
[objWbemAsyncContext]
)

Parameters

objWbemSink
Required. This is the object sink that will asynchronously receive the result of the put operation.
iFlags
Optional. This determines how deep the enumeration will be. This parameter can accept the following values.
Value Meaning
wbemQueryFlagDeep
0 		This value forces recursive enumeration into all subclasses derived from the specified superclass. The superclass itself is not returned in the enumeration.
wbemQueryFlagShallow
0x1 		This is the default for this parameter. It forces the enumeration to include only immediate subclasses of the specified superclass.
wbemFlagSendStatus
0x80 		This flag causes asynchronous calls to send status updates to the OnProgress event handler for your object sink.
wbemFlagDontSendStatus
0x0 		This flag prevents asynchronous calls from sending status updates to the OnProgress event handler for your object sink

objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.
objWbemAsyncContext
Optional. This is an object of type SWbemNamedValueSet that returns to the object sink to identify the source of the original asynchronous call. Use this parameter if you are making multiple asynchronous calls using the same object sink. To use this parameter, create an SWbemNamedValueSet object and use the SWbemNamedValueSet.Add method to add a value that identifies the asynchronous call you are making. This SWbemNamedValueSet object will be returned to the object sink and the source of the call can be extracted using the SWbemNamedValueSet.item method. For more information, see Making an Asynchronous Call Using the Scripting API.

Return Values

None. If the call is successful, an object of type SWbemObjectSet will be returned to the supplied object sink.

Error Codes

The SubclassesAsync_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user does not have permission to view one or more of the classes returned by the call.
wbemErrFailed 0x80041001 | There is an unspecified error.
wbemErrInvalidClass 0x80041010 | The specified class did not exist.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemObjectSet


SWbemLocator

You can use the methods of the SWbemLocator object to obtain an SWbemServices object that represents a connection to a namespace on a local or remote host machine. You can then use the methods on the SWbemServices object to access WMI.

Methods

Method | Description
ConnectServer | Connects to WMI on the specified machine.

Properties

Property | Description
Security_ | Used to read or change the security settings.


SWbemLocator.ConnectServer

The ConnectServer method of the SWbemLocator object connects to the namespace on the machine specified in the Server parameter. This can be either a local or remote target machine, typically with a Microsoft Windows NT/Windows 2000 or Microsoft Windows 95/98 operating system, which must have an operational WMI. If the method is successful, an SWbemServices object will be returned that is bound to the namespace on the host machine.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemServices = objwbemLocator.ConnectServer(
[strServer=""],
[strNameSpace=""],
[strUser=""],
[strPassword=""],
[strLocale=""],
[strAuthority=""],
[iSecurityFlags=0],
[objwbemNamedValueSet=null]
)

Parameters

strServer
Optional. For access to a remote machine using Distributed Component Object Model (DCOM), this parameter specifies the machine name. One example would be "myserver". If you do not provide this parameter, the call will default to the local machine.
strNameSpace
Optional. This is a string that specifies the namespace to which you log on. For example, to log on to the Root\Default namespace, use "root\default". If you do not specify this parameter, it will default to the namespace that has been configured as the default name space for scripting. For more information on the default value for this parameter, see Object Creation and Monikers.
strUser
Optional. This is a string that specifies the user name to use while attempting to connect. This can be in the form of a user name or Domain\Username. Leave it blank to use the current logged-on user name. The strUser parameter should only be used with connections to remote WMI servers. If you attempt to specify strUserfor a local WMI connection, the connection attempt will fail.
strPassword
Optional. This is a string that specifies the password to use when attempting to connect. Leave it blank to use the password of the current logged-on user. The strPassword parameter should only be used with connections to remote WMI servers. If you attempt to specify strPassword for a local WMI connection, the connection attempt will fail.
strLocale
Optional. This is a string that specifies the localization code. If you want to use the current locale, leave it blank. If not blank, this parameter must be a string that indicates the desired locale in which information should be retrieved. For Microsoft locale identifiers, the format of the string is "MS_xxxx", where xxxx is a string in hexadecimal form that indicates the LCID.

For example, American English would appear as "MS_409"

strAuthority
Optional. If the strAuthority parameter begins with the string "kerberos:", Kerberos authentication will be used and this parameter should contain a Kerberos principal name. If the strAuthority parameter contains any other value, NT LAN Manager (NTLM) authentication will be used and this parameter should contain a NTLM domain name. If you leave this parameter blank the operating system will negotiate with DCOM to determine whether NTLM or Kerberos authentication will be used. The authority parameter should only be used with connections to remote WMI servers. If you attempt to set the authority for a local WMI connection, the connection attempt will fail. For more information see Using Kerberos or NTLM Authentication with the Scripting API for more information.
iSecurityFlags
Optional. This parameter reserved and must be zero if specified.
objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.

Return Values

If successful, an object of type SWbemServices that is bound to the specified namespace returns.

Error Codes

The ConnectServer method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current or specified user name and password were not valid or authorized to make the connection.
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrInvalidNamespace 0x8004100E | The specified namespace did not exist on the server.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified, or the namespace could not be parsed.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.
wbemErrTransportFailure 0x80041015 | A networking error occurred, preventing normal operation.

Remarks

An error code of Hex 0x80070005 indicates a DCOM access-denied error.

Note When connecting to WMI on a remote Microsoft Windows 95 system from a Microsoft Windows NT/Windows 2000 system there are two issues to consider.

  • If the local system is supplying credentials (your user name and password) of a domain that it is not a member of, you may notice that synchronous enumerations and queries may take much longer to process.
  • If you provide credentials in the process of connecting to WMI, the logon will fail and you will get an RPC Server is unavailable error.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemServices


SWbemLocator.Security_

The Security_ property of the SWbemLocator object is used to read or set the security settings for an SWbemLocator object. This property is an object of type SWbemSecurity.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemSecurity = objwbemLocator.Security_

Note The properties of an SWbemLocator.Security_ object have no default values. If you attempt to get the value of SWbemSecurity.AuthenticationLevel or SWbemSecurity.ImpersonationLevel on an SWbemLocator object before you have set it, an wbemErrFailed error will result.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

Setting the DCOM Impersonation Level for the Scripting API, Object Creation and Monikers


SWbemMethod

You can use the properties of the SWbemMethod object to inspect a single CIM method definition of a CIM object.

This object can be used to inspect the definitions of methods. In order to invoke the methods, you should use either direct access (see Direct Access ) on an SWbemObject (which is the recommended mechanism), or the SWbemServices.ExecMethod call.

Note In this version of the API, write access to method information is not supported. If you want to define methods, or modify existing method definitions, you may use the WMI COM API or, preferably, you should define the method changes in a MOF file, and then submit that using the MOF Compiler.

Methods

None.

Properties

Property | Description
InParameters | This is an object of type SWbemObject, whose properties define the input parameters for this method.
Name | This is the name of the method.
Origin | This is the originating class of the method.
OutParameters | This is an object of type SWbemObject whose properties define the out parameters and return type of this method.
Qualifiers_ | This is an object of type SWbemQualifierSet that contains the qualifiers for this method.


SWbemMethod.InParameters

The InParameters property of the SWbemMethod object is an object of type SWbemObject whose CIM properties define the input parameters for this method. This property is read-only. Note that any changes made to this object will not be reflected in the underlying method definition.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objInParameters = objwbemMethod.InParameters

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemMethod.Name

The Name property of the SWbemMethod object is a string that describes the name of this method. This property is read-only.

Syntax

strMethodName = objwbemMethod.Name

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemMethod.Origin

The Origin property of the SWbemMethod object returns the name of the CIM class in which this method was introduced. For classes with deep inheritance hierarchies, it is often desirable to know which methods were declared in which classes. This property is read-only.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

strClassOriginName = objwbemMethod.Origin

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemMethod.OutParameters

The OutParameters property of the SWbemMethod object is an object of type SWbemObject whose CIM properties define the out parameters and return type of this method. This property is read-only. Note that any changes made to this object will not be reflected in the underlying method definition.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objOutParameters = objwbemMethod.OutParameters

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemMethod.Qualifiers_

The Qualifiers_ property of the SWbemMethod object returns an object of type SWbemQualifierSet that is the collection of qualifiers for this CIM method. This property is read-only.

Syntax

objQualifierSet = objwbemMethod.Qualifiers_

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemMethodSet

An SWbemMethodSet object is a collection of objects of type SWbemMethod. Items are retrieved using the Item method. For information on using collections, see Collections.

Note In this version of the API, write access to method information is not supported. If you want to define methods, or modify existing method definitions, you may use the WMI COM API, or, preferably, you should define the method changes in a MOF file, and then submit that using the MOF Compiler.

Methods

Method | Description
Item | Retrieves an SWbemMethod from the collection. This is the default automation method of this object.

Properties

Property | Description
Count | The number of items in the collection.


SWbemMethodSet.Item

The Item method of the SWbemMethodSet object returns a named SWbemMethod from the collection.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objMethod= objwbemMethodSet.Item(
strName,
[iFlags=0]
)

Parameters

strName
Required. This parameter is the name of the method to retrieve.
iFlags
Optional. This parameter is reserved and the default value is 0.

Return Values

If successful, the requested SWbemMethod returns.

Error Codes

The Item method can return the error codes listed in the following table.

Error | Meaning
wbemErrInvalidParameter 0x80041008 | The iFlags parameter was not valid.
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrNotFound 0x80041002 | The specified method does not exist.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemMethod


SWbemMethodSet.Count

The Count property of the SWbemMethodSet object defines the number of items in the collection. This property is read-only.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

iCount = objwbemMethodSet.Count

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemNamedValue

The SWbemNamedValue object represents a single named value that belongs to the SWbemNamedValueSet collection object.

Properties

Property | Description
Name | Name of the SWbemNamedValue item.
Value | Value of the SWbemNamedValue item. This is the default property of this object.


SWbemNamedValue.Name

The Name property of the SWbemNamedValue object is a unique case-insensitive string that is used when retrieving or setting an SWbemNamedValue item. This property is read-only.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

strName = objwbemNamedValue.Name

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemNamedValue.Value

The Value property of the SWbemNamedValue object returns the variant value of an SWbemNamedValue item. This is the default property for SWbemNamedValue objects. Changes made to the value property are reflected automatically in the SWbemNamedValueSet collection to which the SWbemNamedValue belongs.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

varValue = objwbemNamedValue.Value

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemNamedValueSet

An SWbemNamedValueSet object is a collection of objects of type SWbemNamedValue. The methods and properties of SWbemNamedValueSet are used principally to send additional information to providers when submitting certain calls to WMI. All calls in SWbemServices, and some calls in SWbemObject, take an optional parameter that is an object of this type. A client can add information to an SWbemNamedValueSet object, and send the SWbemNamedValueSet object along with the call as one of the parameters.

For information on using collections, see Collections.

Important It is very important that providers use this mechanism as sparingly as possible. It is recommended that providers never use it. If a provider requires a large amount of highly specific context information to respond to a request, all clients must be coded to provide this information. This mechanism can break the uniform access model that is the basis of WMI. Nevertheless, in some situations you will not be able to avoid it. Therefore, this mechanism allows you to access such providers, if necessary.

An SWbemNamedValueSet object is a collection of SWbemNamedValue elements. These Items are added to the collection using the SWbemNamedValueSet.Add method. They are removed using the SWbemNamedValueSet.Remove method and retrieved using the SWbemNamedValueSet.Item method. You can access the methods to fill in any context information required by a dynamic provider. After you call one of the SWbemServices methods, you can reuse the SWbemNamedValueSet object for another call.

The underlying provider determines the information contained in an SWbemNamedValueSet object. WMI makes no use of the information, but simply forwards it to the provider. Providers must publish the context information they require to service requests.

Methods

Method | Description
Add | Adds an SWbemNamedValue object to the collection.
Clone | Makes a copy of this SWbemNamedValueSet collection.
DeleteAll | Removes all items from the collection, making the SWbemNamedValueSet object empty.
Item | Retrieves an SWbemNamedValue from the collection. This is the default method of the object.
Remove | Removes an SWbemNamedValue object from the collection.

Properties

Property | Description
Count | The number of items in the collection.


SWbemNamedValueSet.Add

The Add method of the SWbemNamedValueSet object adds an SWbemNamedValue object to the collection. If an element already exists in the collection with the same name, the new element replaces it.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objNamedValue = objwbemNamedValueSet.Add(
strName,
varVal,
[iFlags=0]
)

Parameters

strName
Required. This is the name of the new value.
varVal
Required. This is a variant representing the new value.
iFlags
Optional. This parameter is reserved and must be set to zero if specified.

Return Values

If successful, this method returns the newly modified or created SWbemNamedValue.

Remarks

For examples of adding and retrieving named values, see SWbemNamedValue.Value.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemNamedValueSet.Clone

The Clone method of the SWbemNamedValueSet object returns a new object that is a clone of the current collection.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemNamedValueSet = objwbemNamedValueSet.Clone()

Return Values

If successful, a new SWbemNamedValueSet returns.

Error Codes

The Clone method can return the error codes listed in the following table.

Error | Meaning
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to clone the object.

Remarks

Use this method to duplicate an SWbemNamedValueSet collection.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemNamedValueSet.Count

Use the Count property of the SWbemNamedValueSet object to determine how many items are in the collection. This property is read-only.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

iCount = objwbemNamedValueSet.Count

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemNamedValueSet.DeleteAll

The DeleteAll method of the SWbemNamedValueSet object removes all named values from the collection, thus emptying it.

Syntax

objwbemNamedValueSet.DeleteAll

Return Values

This method has no return values.

Error Codes

The DeleteAll method can return the error code listed in the following table.

Error | Meaning
wbemErrFailed 0x80041001 | This is an unspecified error.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemNamedValueSet.Remove


SWbemNamedValueSet.Item

The Item method of the SWbemNamedValueSet object gets an SWbemNamedValue from the collection.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objNamedValue = objwbemNamedValueSet.Item(
strName,
[iFlags=0]
)

Parameters

strName
Required. This is the name of the value to retrieve.
iFlags
Optional. This parameter is reserved and must be zero if specified.

Return Values

If successful, the requested SWbemNamedValue returns.

Error Codes

The Item method can return the error codes listed in the following table.

Error | Meaning
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified, or the namespace could not be parsed.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.
wbemErrNotFound 0x80041002 | The requested item was not found.

Remarks

For examples of adding and retrieving named values, see SWbemNamedValue.Value.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemNamedValueSet.Remove

The Remove method of the SWbemNamedValueSet object deletes a named value from the context.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemNamedValueSet.Remove(
strName,
[iFlags=0]
)

Parameters

strName
Required. This is the name of the value to remove.
iFlags
Optional. This parameter is reserved and must be zero if specified.

Return Values

This method has no return values.

Error Codes

The Remove method can return the error codes listed in the following table.

Error | Meaning
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified, or the namespace could not be parsed.
wbemErrNotFound 0x80041002 | The requested item was not found.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemObject

You can use the methods and properties of the SWbemObject object to represent a single Common Information Model (CIM) class definition or CIM object instance.

This object supports two types of properties and methods. Those defined in this section are generic properties and methods that apply to all CIM objects. In addition, this object exposes the CIM Properties (respectively, Methods) of the object as dynamic Automation Properties (respectively, Methods) of this object. These names and types of these properties and methods depend on the underlying CIM Object. For more information on how these dynamic properties and methods are exposed, refer to Direct Access.

From the WMI client perspective, this object is always in-process. Write operations only affect the local copy of the object, and read operations always retrieve values from the local copy. Updates to WMI are performed only when entire objects are written using a call to the SWbemObject.Put_ method. If you modify the properties or methods in an SWbemObject, your changes will be not written to WMI until you call SWbemObject.Put_.

The generic method and property names defined in this section always end with a trailing underscore ("_") to differentiate them from the dynamic CIM methods and properties of the underlying CIM object.

Methods

Method | Description
Associators_ | Retrieves the associators of the object.
AssociatorsAsync_ | Asynchronously retrieves the associators of the object.
Clone_ | Makes a copy of the current object.
CompareTo_ | Tests two objects for equality.
Delete_ | Deletes the object from WMI.
DeleteAsync_ | Asynchronously deletes the object from WMI.
ExecMethod_ | Executes a method exported by a method provider.
ExecMethodAsync_ | Asynchronously executes a method exported by a method provider.
GetObjectText_ | Retrieves the textual representation of the object (MOF syntax).
Instances_ | Returns a collection of instances of the object (which must be a CIM class).
InstancesAsync_ | Asynchronously returns a collection of instances of the object (which must be a CIM class).
Put_ | Creates or updates the object in WMI.
PutAsync_ | Asynchronously creates or updates the object in WMI.
References_ | Returns References to the object.
ReferencesAsync_ | Asynchronously returns References to the object.
SpawnDerivedClass_ | Creates a new derived class from the current object (which must be a CIM class).
SpawnInstance_ | Creates a new instance from the current object.
Subclasses_ | Returns a collection of subclasses of the object (which must be a CIM class).
SubclassesAsync_ | Asynchronously returns a collection of subclasses of the object (which must be a CIM class).

Properties

Property | Description
Derivation_ | Contains an array of strings describing the derivation hierarchy for the class.
Methods_ | This is an SWbemMethodSet object. It is the collection of methods for this object.
Path_ | Contains an SWbemObjectPath object that represents the object path of the current class or instance.
Properties_ | This is an SWbemPropertySet object. It is the collection of properties for this object.
Qualifiers_ | This is an SWbemQualifierSet object. It is the collection of qualifiers for this object.
Security_ | Contains an SWbemSecurity object used to read or change the security settings.


SWbemObject.Associators_

The Associators_ method of the SWbemObject object returns a collection of objects (classes or instances) that are associated with the current object. These returned objects are called endpoints. This method performs the same function that the WMI Query Language (WQL) "Associators Of" query performs.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objWbemObjectSet = objwbemObject.Associators_(
[strAssocClass=""],
[strResultClass=""],
[strResultRole=""],
[strRole=""],
[bClassesOnly=FALSE],
[bSchemaOnly=FALSE],
[strRequiredAssocQualifier=""],
[strRequiredQualifier=""],
[iFlags=wbemFlagReturnImmediately],
[objwbemNamedValueSet=null]
)

Parameters

strAssocClass
Optional. This is a string that contains an association class. If specified, this parameter indicates that the returned endpoints must be associated with the source through the specified association class or a class derived from this association class.
strResultClass
Optional. This is a string that contains a class name. If specified, this parameter indicates that the returned endpoints must belong to or be derived from the class specified in this parameter.
strResultRole
Optional. This is a string that contains a property name. If specified, this parameter indicates that the returned endpoints must play a particular role in their association with the source object. The role is defined by the name of a specified property—which must be a reference property—of an association.
strRole
Optional. This is a string that contains a property name. If specified, this parameter indicates that the returned endpoints must participate in an association with the source object in which the source object plays a particular role. The role is defined by the name of a specified property—which must be a reference property—of an association.
bClassesOnly
Optional. This is a Boolean value that indicates whether a list of class names should be returned rather than actual instances of the classes. These are the classes to which the endpoint instances belong. The default value for this parameter is FALSE.
bSchemaOnly
Optional. This is a Boolean value that indicates whether the query applies to schema rather than data. The default value for this parameter is FALSE. It can only be set to TRUE if the strObjectPath parameter specifies the object path of a class. When set to TRUE, the set of returned endpoints represent classes that are suitably associated with the source class in schema.
strRequiredAssocQualifier
Optional. This is a string that contains a qualifier name. This parameter, if specified, indicates that the returned endpoints must be associated with the source object through an association class that includes the specified qualifier.
strRequiredQualifier
Optional. This is a string that contains a qualifier name. This parameter, if specified, indicates that the returned endpoints must include the specified qualifier.
iFlags
Optional. This is an integer specifying additional flags to the operation. The default for this parameter is wbemFlagReturnImmediately, which directs the call to return immediately rather than wait until the query has completed. This parameter can accept the following values.
Value Meaning
wbemFlagForwardOnly
0x20 		This flag causes a forward-only enumerator to be returned. Forward-only enumerators are generally much faster and use less memory than conventional enumerators, but they do not allow calls to Clone or Reset.
wbemFlagBidirectional
0x0 		This flag causes WMI to retain pointers to objects of the enumeration until the client releases the enumerator.
wbemFlagReturnImmediately
0x10 		This flag causes the call to return immediately.
wbemFlagReturnWhenComplete
0x0 		This flag causes this call to block until the query has completed.

objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.

Return Values

If the call is successful, an object of type SWbemObjectSet will be returned.

Error Codes

The Associators_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user does not have permission to view one or more of the classes returned by the call.
wbemErrFailed 0x80041001 | There is an unspecified error.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Remarks

For information about the associated WQL query "Associators Of", source instances and endpoints see Data Queries.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemServices.AssociatorsOf, SWbemServices.ReferencesTo, SWbemObject.References_


SWbemObject.AssociatorsAsync_

The AssociatorsAsync_ method of the SWbemObject object asynchronously returns a collection of objects (classes or instances) that are associated with the current object. These returned objects are called endpoints. This method performs the same function that the WMI Query Language (WQL) "Associators Of" query performs. This call will return immediately and the results and status will be returned to the caller through the supplied object sink.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemObject.AssociatorsAsync_(
objWbemSink,
[strAssocClass=""],
[strResultClass=""],
[strResultRole=""],
[strRole=""],
[bClassesOnly=FALSE],
[bSchemaOnly=FALSE],
[strRequiredAssocQualifier=""],
[strRequiredQualifier=""]
[iFlags],
[objwbemNamedValueSet=null]
[objWbemAsyncContext]
)

Parameters

objWbemSink
Required. This is the object sink that will receive the objects asynchronously.
strAssocClass
Optional. This is a string that contains an association class. If specified, this parameter indicates that the returned endpoints must be associated with the source through the specified association class or a class derived from this association class.
strResultClass
Optional. This is a string that contains a class name. If specified, this parameter indicates that the returned endpoints must belong to or be derived from the class specified in this parameter.
strResultRole
Optional. This is a string that contains a property name. If specified, this parameter indicates that the returned endpoints must play a particular role in their association with the source object. The role is defined by the name of a specified property—which must be a reference property—of an association.
strRole
Optional. This is a string that contains a property name. If specified, this parameter indicates that the returned endpoints must participate in an association with the source object in which the source object plays a particular role. The role is defined by the name of a specified property—which must be a reference property—of an association.
bClassesOnly
Optional. This is a Boolean value that indicates whether a list of class names should be returned rather than actual instances of the classes. These are the classes to which the endpoint instances belong. The default value for this parameter is FALSE.
bSchemaOnly
Optional. This is a Boolean value that indicates whether the query applies to schema rather than data. The default value for this parameter is FALSE. It can only be set to TRUE if the strObjectPath parameter specifies the object path of a class. When set to TRUE, the set of returned endpoints represent classes that are suitably associated with the source class in schema.
strRequiredAssocQualifier
Optional. This is a string that contains a qualifier name. This parameter, if specified, indicates that the returned endpoints must be associated with the source object through an association class that includes the specified qualifier.
strRequiredQualifier
Optional. This is a string that contains a qualifier name. This parameter, if specified, indicates that the returned endpoints must include the specified qualifier.
iFlags
Optional. This is an integer specifying additional flags to the operation. This parameter can accept the following values.
Value Meaning
wbemFlagSendStatus
0x80 		This flag causes asynchronous calls to send status updates to the OnProgress event handler for your object sink.
wbemFlagDontSendStatus
0x0 		This flag prevents asynchronous calls from sending status updates to the OnProgress event handler for your object sink

objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.
objWbemAsyncContext
Optional. This is an object of type SWbemNamedValueSet that returns to the object sink to identify the source of the original asynchronous call. Use this parameter if you are making multiple asynchronous calls using the same object sink. To use this parameter, create an SWbemNamedValueSet object and use the SWbemNamedValueSet.Add method to add a value that identifies the asynchronous call you are making. This SWbemNamedValueSet object will be returned to the object sink and the source of the call can be extracted using the SWbemNamedValueSet.item method. For more information, see Making an Asynchronous Call Using the Scripting API.

Return Values

An object of type SWbemSink is returned by this call. The results of the asynchronous call are provided through this sink as an object of type SWbemObjectSet.

Error Codes

The AssociatorsAsync_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user does not have permission to view one or more of the classes returned by the call.
wbemErrFailed 0x80041001 | There is an unspecified error.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Remarks

For information about the associated WQL query "Associators Of", source instances and endpoints see Data Queries

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemServices.AssociatorsOfAsync, SWbemServices.ReferencesTo, SWbemObject.References_


SWbemObject.Clone_

The Clone_ method of the SWbemObject object returns a new object that is a clone of the current object.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objObject = objwbemObject.Clone_()

Return Values

If successful, a new SWbemObject returns.

Error Codes

The Clone_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrInvalidParameter 0x80041008 | Nothing was specified as a parameter, and it is not acceptable in this usage.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to clone the object.

Remarks

Use this method to duplicate a class definition or instance. This is useful when you need the original copy of the object for backup purposes while you are modifying a new copy. Likewise, you can use this method to create many new instances from a single source instance. For example, you can use SWbemObject.SpawnInstance_ to create a single starting instance, and use SWbemObject.Clone_ to produce 100 copies of the instance quickly. Subsequently, you can modify the objects, giving each one specific values.

It is not possible to use this method to convert a class definition to an instance, or to convert an instance to a class definition.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemObject.CompareTo_

The CompareTo_ method of the SWbemObject object compares two SWbemObject type objects. This comparison is subject to certain constraints based on the values specified in the iFlags parameter.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

bAreEqual = objwbemObject.CompareTo_(
objwbemObject,
[iFlags= wbemComparisonFlagIncludeAll]
)

Parameters

objwbemObject
Required. This parameter is an Object of class SWbemObject. This is the object with which the first object is compared. The object must be a valid SWbemObject instance, and it cannot be undefined.
iFlags
Optional. It specifies the object characteristics to consider when comparing an object with other objects. You can use wbemComparisonFlagIncludeAll to consider all features (this is the default), or any combination of the following values.
Value Meaning
wbemComparisonFlagIncludeAll
0x0 		Use this flag to compare all properties, qualifiers, and flavors, or use one of the other flags listed below to ignore any of these items.
wbemComparisonFlagIgnoreObjectSource
0x2 		The source of the objects, namely the server and the namespace they came from, are ignored in comparison to other objects.
wbemComparisonFlagIgnoreQualifiers
0x1 		All qualifiers (including "key" and "dynamic") should be ignored in comparison.
wbemComparisonFlagIgnoreDefaultValues
0x4 		Default values of properties should be ignored. This flag is only meaningful when comparing classes.
wbemComparisonFlagIgnoreFlavor
0x20 		Ignore qualifier flavors. This flag still takes qualifier values into account, but ignores flavor distinctions such as propagation rules and override restrictions.
wbemComparisonFlagIgnoreCase
0x10 		Compares string values in a case-insensitive manner. This applies both to strings and to qualifier values. Property and qualifier names are always compared in a case-insensitive manner whether this flag is specified or not.
wbemComparisonFlagIgnoreClass
0x8 		This flag instructs the system to assume that the objects being compared are instances of the same class. Consequently, this flag compares instance-related information only. Use this flag to optimize performance. If the objects are not of the same class, the results will be undefined.

Return Values

This method returns the Boolean value TRUE if the objects match or FALSE if they do not.

Error Codes

The CompareTo_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemObject


SWbemObject.Delete_

The Delete_ method of the SWbemObject object deletes the current class or instance.

If a dynamic provider supplied the class or instance, it is sometimes not possible to delete this object unless the provider supports class or instance deletion.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemObject.Delete_(
[iFlags=0],
[objwbemNamedValueSet=null]
)

Parameters

iFlags
Optional. This parameter is reserved and must be zero if specified.
objwbemNamedValueSet
Optional. This parameter is typically undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.

Return Values

This method has no return values.

Error Codes

The Delete_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current context does not have adequate security rights to delete the object.
wbemErrFailed 0x8004100 | This is an unspecified error.
wbemErrInvalidClass 0x80041010 | The specified class does not exist.
wbemErrInvalidOperation 0x80041016 | The object cannot be deleted.
wbemErrNotFound 0x80041002 | The object did not exist.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemObject.DeleteAsync_

The DeleteAsync_ method of the SWbemObject object asynchronously deletes the current class or instance. This call will return immediately and the results of the delete operation will be returned to the caller through the supplied object sink.

If a dynamic provider supplied the class or instance, it is sometimes not possible to delete this object unless the provider supports class or instance deletion.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemObject.DeleteAsync_(
objWbemSink
[iFlags=0],
[objwbemNamedValueSet=null]
[objWbemAsyncContext]
)

Parameters

objWbemSink
This parameter is the object sink that returns the outcome of the delete operation.
iFlags
Optional. This is an integer that determines the behavior of the call. This parameter can accept the following values.
Value Meaning
wbemFlagSendStatus
0x80 		This flag causes asynchronous calls to send status updates to the OnProgress event handler for your object sink.
wbemFlagDontSendStatus
0x0 		This flag prevents asynchronous calls from sending status updates to the OnProgress event handler for your object sink

objwbemNamedValueSet
Optional. This parameter is typically undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.
objWbemAsyncContext
Optional. This is an object of type SWbemNamedValueSet that returns to the object sink to identify the source of the original asynchronous call. Use this parameter if you are making multiple asynchronous calls using the same object sink. To use this parameter, create an SWbemNamedValueSet object and use the SWbemNamedValueSet.Add method to add a value that identifies the asynchronous call you are making. This SWbemNamedValueSet object will be returned to the object sink and the source of the call can be extracted using the SWbemNamedValueSet.item method. For more information, see Making an Asynchronous Call Using the Scripting API.

Return Values

None. If this call is successful the result of the delete operation will be provided through the supplied object sync.

Error Codes

The DeleteAsync_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current context does not have adequate security rights to delete the object.
wbemErrFailed 0x8004100 | This is an unspecified error.
wbemErrInvalidClass 0x80041010 | The specified class does not exist.
wbemErrInvalidOperation 0x80041016 | The object cannot be deleted.
wbemErrNotFound 0x80041002 | The object did not exist.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemObject.Derivation_

The Derivation_ property of the SWbemObject object contains an array of strings that describe the class derivation hierarchy for the instance being referenced. The contents are in most-derived-from order. That is, the first element in the array defines the superclass and the last element defines the dynasty class. This property is read-only.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

strClassArray = objwbemObject.Derivation_

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemObject.ExecMethod_

The ExecMethod_ method of the SWbemObject object executes a method exported by a method provider. This method is similar to SWbemServices.ExecMethod, but it operates directly on the object whose method is to be executed.

Use SWbemObject.ExecMethod_ as an alternate way to execute a method in cases where it is not possible to execute a method directly. For example, you would need to use it with a scripting language such as Microsoft JScript that does not support output parameters, if your method has out parameters. Otherwise, the recommended means of invoking a method is to use direct method invocation. Direct method invocation is executing a method by using object.method syntax. For more information on direct method invocation, see Direct Access.

This method will block while the method that is forwarded to the appropriate provider executes. The information and status are then returned.

WMI does not implement the methods directly. The method providers export the methods.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objOutParams = objwbemObject.ExecMethod_(
strMethodName,
[objwbemInParams=null],
[iFlags=0],
[objwbemNamedValueSet=null]
)

Parameters

strMethodName
Required. This is the name of the method for the object.
objwbemInParams
Optional. This is an SWbemObject object that contains the input parameters for the method being executed.
To construct the objwbemInParams parameter
  1. Call SWbemObject.Methods_.Item("MethodName") to get an SWbemMethod object that contains the properties that describe the method, where "MethodName" is the name of the method to retrieve.
  2. Use the SWbemMethod.InParameters property of the SWbemMethod object to get an InParameters object.
  3. Call SpawnInstance_ on the InParameters object to create an instance.
  4. Set the properties of the instance to whatever values are appropriate. For example, If you want to set an input parameter named myinputparam to the value "whatever" in an instance of InParameters called "INST", the code would look like this: INST.Properties_.Add ("myinputparam").Value = "Whatever"

    The default value for this parameter is undefined.

iFlags
Optional. This parameter is reserved and must be set to zero if specified.
objwbemNamedValueSet
Optional. Typically, it is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.

Return Values

A object of SWbemObject returns if this call is successful. The returned object contains the out parameters and return value for the method being executed.

Error Codes

The ExecMethod_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrInvalidClass 0x80041010 | The specified class was invalid.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.
wbemErrInvalidMethod 0x8004102E | The requested method was not available.
wbemErrAccessDenied 0x80041003 | The current user was not authorized to execute the method.

Examples

SWbemObject.ExecMethod_ Examples

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemServices.ExecMethod, SWbemObject.ExecMethodAsync_


SWbemObject.ExecMethodAsync_

The ExecMethodAsync_ method of the SWbemObject object asynchronously executes a method exported by a method provider. This method is similar to SWbemServices.ExecMethodAsync, but it operates directly on the object whose method is to be executed.

Use SWbemObject.ExecMethodAsync_ as an alternate way to execute a method in cases where it is not possible to execute a method directly. For example, you would need to use it with a scripting language such as Microsoft JScript that does not support output parameters, if your method has out parameters. Otherwise, the recommended means of invoking a method is to use direct method invocation. Direct method invocation is executing a method by using object.method syntax. For more information on direct method invocation, see Direct Access.

This call will return immediately and the results of the put operation will be returned to the caller through the supplied object sink.

WMI does not implement the methods directly. The method providers export the methods.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objOutParams = objwbemObject.ExecMethodAsync_(
objWbemSink,
strMethodName,
[objwbemInParams=null],
[iFlags=0],
[objwbemNamedValueSet=null]
[objWbemAsyncContext]
)

Parameters

objWbemSink
Required. This is the object sink that receives the result of the method call. The outbound parameters are sent to the SWbemSink.OnObjectReady event of the supplied object sink. The result of the call mechanism itself will be sent to the SWbemSink.OnCompleted event of the supplied object sink. Notice that SWbemSink.OnCompleted does not receive the return code of the CIM method. However, it receives the return code of the actual call-return mechanism, and is only useful for verifying that the call occurred or that it failed for mechanical reasons. The result code returned from the CIM method is returned in the outbound parameter object supplied to SWbemSink.OnObjectReady. If any error code returns, then the supplied IWbemObjectSink object will not be used. If the call is successful, then the user's IWbemObjectSink implementation will be called to indicate the result of the operation.
strMethodName
Required. This is the name of the method for the object.
objwbemInParams
Optional. This is an SWbemObject object that contains the input parameters for the method being executed.
To construct the objwbemInParams parameter
  1. Call SWbemObject.Methods_.Item("MethodName") to get an SWbemMethod object that contains the properties that describe the method, where "MethodName" is the name of the method to retrieve.
  2. Use the SWbemMethod.InParameters property of the SWbemMethod object to get an InParameters object.
  3. Call SpawnInstance_ on the InParameters object to create an instance.
  4. Set the properties of the instance to whatever values are appropriate. For example, If you want to set an input parameter named myinputparam to the value "whatever" in an instance of InParameters called "INST", the code would look like this: INST.Properties_.Add ("myinputparam").Value = "Whatever"

    The default value for this parameter is undefined.

iFlags
Optional. This is an integer that determines the behavior of the call. This parameter can accept the following values.
Value Meaning
wbemFlagSendStatus
0x80 		This flag causes asynchronous calls to send status updates to the OnProgress event handler for your object sink.
wbemFlagDontSendStatus
0x0 		This flag prevents asynchronous calls from sending status updates to the OnProgress event handler for your object sink

objwbemNamedValueSet
Optional. Typically, it is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.
objWbemAsyncContext
Optional. This is an object of type SWbemNamedValueSet that returns to the object sink to identify the source of the original asynchronous call. Use this parameter if you are making multiple asynchronous calls using the same object sink. To use this parameter, create an SWbemNamedValueSet object and use the SWbemNamedValueSet.Add method to add a value that identifies the asynchronous call you are making. This SWbemNamedValueSet object will be returned to the object sink and the source of the call can be extracted using the SWbemNamedValueSet.item method. For more information, see Making an Asynchronous Call Using the Scripting API.

Return Values

None. An object of type SWbemObject returns to the supplied sink if this call is successful. The returned object contains the out parameters and return value for the method being executed.

Error Codes

The ExecMethodAsync_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrInvalidClass 0x80041010 | The specified class was invalid.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.
wbemErrInvalidMethod 0x8004102E | The requested method was not available.
wbemErrAccessDenied 0x80041003 | The current user was not authorized to execute the method.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemServices.ExecMethodAsync


SWbemObject.GetObjectText_

The GetObjectText_ method of the SWbemObject object returns a textual rendering of the object. This interface can be used to display an object's contents. Currently, only the Managed Object Format (MOF) syntax is supported as an output format. Notice that the MOF text returned does not contain all the information about the object, but only enough information for the MOF compiler to be able to re-create the original object. For instance, you will not find any information about the propagated qualifiers or the parent class properties.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

strMofText = objwbemObject.GetObjectText_(
[iFlags=0]
)

Parameters

iFlags
Optional. This parameter is reserved and must be zero if specified.

Return Values

If successful, this method will return a string that contains the output text.

Error Codes

The GetObjectText_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemObject.Instances_

The Instances_ method of the SWbemObject object creates an enumerator that returns the instances of the current class object. This method implements a simple query. More complex queries may require the use of SWbemServices.ExecQuery.

Note This method only works for class objects. It is not an error for the returned collection to have zero elements.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objWbemObjectSet = objwbemObject.Instances_(
[iFlags=wbemFlagReturnImmediately],
[objwbemNamedValueSet=null]
)

Parameters

iFlags
Optional. This parameter is reserved and must be zero if specified.
objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics. This parameter is optional.

Return Values

If successful, an object of type an object of type SWbemObjectSet returns.

Error Codes

The Instances_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user does not have permission to view instances of the specified class.
wbemErrFailed 0x80041001 | An unspecified error occurred.
wbemErrInvalidClass 0x80041010 | The specified class is invalid.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemObjectSet


SWbemObject.InstancesAsync_

The InstancesAsync_ method of the SWbemObject object asynchronously creates an enumerator that returns the instances of the current class object. This method implements a simple query. More complex queries may require the use of SWbemServices.ExecQuery. This call will return immediately and the results of the call will be returned to the caller through the supplied object sink.

Note This method only works for class objects. It is not an error for the returned collection to have zero elements.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemObject.InstancesAsync_(
[objWbemSink ]
[iFlags],
[objwbemNamedValueSet=null],
[objWbemAsyncContext]
)

Parameters

objWbemSink
This parameter is the object sink that will return the instances.
iFlags
Optional. This is an integer that determines the behavior of the call. This parameter can accept the following values.
Value Meaning
wbemFlagSendStatus
0x80 		This flag causes asynchronous calls to send status updates to the OnProgress event handler for your object sink.
wbemFlagDontSendStatus
0x0 		This flag prevents asynchronous calls from sending status updates to the OnProgress event handler for your object sink

objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics. This parameter is optional.
objWbemAsyncContext
Optional. This is an object of type SWbemNamedValueSet that returns to the object sink to identify the source of the original asynchronous call. Use this parameter if you are making multiple asynchronous calls using the same object sink. To use this parameter, create an SWbemNamedValueSet object and use the SWbemNamedValueSet.Add method to add a value that identifies the asynchronous call you are making. This SWbemNamedValueSet object will be returned to the object sink and the source of the call can be extracted using the SWbemNamedValueSet.item method. For more information, see Making an Asynchronous Call Using the Scripting API.

Return Values

None. If this call is successful, the results of the asynchronous call are provided through this sync as an object of type SWbemObjectSet.

Error Codes

The InstancesAsync_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user does not have permission to view instances of the specified class.
wbemErrFailed 0x80041001 | An unspecified error occurred.
wbemErrInvalidClass 0x80041010 | The specified class is invalid.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemObjectSet


SWbemObject.Methods_

The Methods_ property of the SWbemObject object returns an SWbemMethodSet object that is a collection of the CIM methods for the current class or instance. This property is read-only.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objMethodSet = objwbemObject.Methods_

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemObject.Path_

The Path_ property of the SWbemObject object returns an SWbemObjectPath object that represents the object path of the current class or instance. This property can be passed as a parameter to methods that require an object path.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objObjectPath = objwbemObject.Path_

Remarks

Only the Class property of the returned SWbemObjectPath instance can be modified. If you try to modify any other property, or try to call the methods SetAsClass or SetAsSingleton, you will get an error of wbemErrReadOnly.

Because of this, you cannot modify the SWbemNamedValueSet that is the value of the Keys property of the returned SWbemObjectPath instance. If you try to call the methods Add, Remove, or DeleteAll on this value, you will get an error of wbemErrReadOnly. Furthermore, you will not be able to modify any SWbemNamedValue obtained from this collection. Attempts to modify the Value property will return the same error code.

However, if you call SWbemObject.Clone_ to create a copy, the Path_ property of the copy is fully modifiable.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemObject.Properties_

The Properties_ property of the SWbemObject object returns an SWbemPropertySet object that is a collection of the CIM properties for the current class or instance. This property is read-only.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objPropertySet = objwbemObject.Properties_

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemObject.Put_

The Put_ method of the SWbemObject object creates or updates an instance or class object to WMI. You can use this method after you have modified any properties or methods in an SWbemObject object and your changes will be written to WMI.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objObjectPath = objwbemObject.Put_(
[iFlags= wbemChangeFlagCreateOrUpdate],
[objwbemNamedValueSet=null]
)

Parameters

iFlags
Optional. This parameter determines if the call will create or update the class or instance and if the call will return right away or not. This parameter can accept the following values.
Value Meaning
wbemChangeFlagUpdateCompatible
0x0 		This flag allows a class to be updated if there are no derived classes and there are no instances for that class. It also allows updates in all cases if the change is just to non-important qualifiers (for example the description qualifier). This is the default behavior for this call and is used for compatibility with previous versions of WMI. If the class has instances the update will fail.
wbemChangeFlagUpdateSafeMode
0x20 		This flag allows updates of classes even if there are child classes as long as the change does not cause any conflicts with child classes. An example of an update in this flag would allow would be to add a new property to the base class that was not previously mentioned in any of the child classes. If the class has instances the update will fail.
WbemChangeFlagUpdateForceMode
0x40 		This flag forces updates of classes when conflicting child classes exist. For example, this flag will force an update if a class qualifier was defined in a child class, and the base class tries to add the same qualifier and in conflict with the existing one. In force mode this conflict would be resolved by deleting the conflicting qualifier in the child class. If the class has instances the update will fail.
wbemChangeFlagCreateOrUpdate
0x0 		This flag causes the class or instance to be created if it does not exist or overwritten if it exists already.
wbemChangeFlagCreateOnly
0x2 		This flag is used for creation only. The call will fail if the class or instance already exists.
wbemChangeFlagUpdateOnly
0x1 		This flag causes this call to update. The class or instance must exist for the call to be successful.
wbemFlagReturnImmediately
0x10 		This flag causes the call to return immediately.
wbemFlagReturnWhenComplete
0x0 		This flag causes this call to block until the query has completed.
wbemFlagUseAmendedQualifiers
0x20000 		This flag causes WMI to return class amendment data along with the base class definition. For more information about amended qualifiers see WMI Localization.

objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.

Return Values

If the call is successful, an object of type SWbemObjectPath will be returned. This will contain the object path of the instance or class that has been successfully committed to WMI.

Error Codes

The Put_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user does not have permission to update an instance of the specified class.
wbemErrAlreadyExists 0x80041019 | wbemChangeFlagCreateOnly flag was specified, but the instance already exists.
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrIllegalNull 0x8004100A | A value of Nothing was specified for a property that may not be Nothing, such as one that is marked by a key, indexed, or not_null qualifier.
wbemErrInvalidObject 0x80041014 | The specified instance is invalid.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrNotFound 0x80041002 | wbemChangeFlagUpdateOnly flag was specified, but the instance or class does not exist.
wbemErrIncompleteClass 0x80041020 | Required properties for classes have not all been set.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemObjectPath.Class, SWbemQualifier, SWbemProperty


SWbemObject.PutAsync_

The PutAsync_ method of the SWbemObject object creates or updates an instance or class object to WMI. You can use this method after you have modified any properties or methods in an SWbemObject object and your changes will be written to WMI. This call will return immediately and the results of the put operation will be returned to the caller through the supplied object sink.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemObject.PutAsyncAsync_(
objWbemSink,
[iFlags= wbemChangeFlagCreateOrUpdate],
[objwbemNamedValueSet=null],
[objWbemAsyncContext]
)

Parameters

objWbemSink
Required. This is the object sink that will asynchronously receive the result of the put operation.
iFlags
Optional. This parameter determines if the call will create or update the class or instance and if the call will return right away or not. This parameter can accept the following values.
Value Meaning
wbemChangeFlagUpdateCompatible
0x0 		This flag allows a class to be updated if there are no derived classes and there are no instances for that class. It also allows updates in all cases if the change is just to non-important qualifiers (for example the description qualifier). This is the default behavior for this call and is used for compatibility with previous versions of Window Management. If the class has instances the update will fail.
wbemChangeFlagUpdateSafeMode
0x20 		This flag allows updates of classes even if there are child classes as long as the change does not cause any conflicts with child classes. An example of an update in this flag would allow would be to add a new property to the base class that was not previously mentioned in any of the child classes. If the class has instances the update will fail.
WbemChangeFlagUpdateForceMode
0x40 		This flag forces updates of classes when conflicting child classes exist. For example, this flag will force an update if a class qualifier was defined in a child class, and the base class tries to add the same qualifier and in conflict with the existing one. In force mode this conflict would be resolved by deleting the conflicting qualifier in the child class. If the class has instances the update will fail.
wbemChangeFlagCreateOrUpdate
0x0 		This flag causes the class or instance to be created if it does not exist or overwritten if it exists already.
wbemChangeFlagCreateOnly
0x2 		This flag is used for creation only. The call will fail if the class or instance already exists.
wbemChangeFlagUpdateOnly
0x1 		This flag causes this call to update. The class or instance must exist for the call to be successful.
wbemFlagReturnImmediately
0x10 		This flag causes the call to return immediately.
wbemFlagReturnWhenComplete
0x0 		This flag causes this call to block until the query has completed.
wbemFlagSendStatus
0x80 		This flag causes asynchronous calls to send status updates to the OnProgress event handler for your object sink.
wbemFlagDontSendStatus
0x0 		This flag prevents asynchronous calls from sending status updates to the OnProgress event handler for your object sink
wbemFlagUseAmendedQualifiers
0x20000 		This flag causes WMI to return class amendment data along with the base class definition. For more information about amended qualifiers see WMI Localization.

objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.
objWbemAsyncContext
Optional. This is an object of type SWbemNamedValueSet that returns to the object sink to identify the source of the original asynchronous call. Use this parameter if you are making multiple asynchronous calls using the same object sink. To use this parameter, create an SWbemNamedValueSet object and use the SWbemNamedValueSet.Add method to add a value that identifies the asynchronous call you are making. This SWbemNamedValueSet object will be returned to the object sink and the source of the call can be extracted using the SWbemNamedValueSet.item method. For more information, see Making an Asynchronous Call Using the Scripting API.

Return Values

None. If the call is successful, the OnObjectPut event of the supplied object sink will receive an object of type SWbemObjectPath, containing the object path of the instance or class that has been successfully committed to WMI.

Error Codes

The PutAsync_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user does not have permission to update an instance of the specified class.
wbemErrAlreadyExists 0x80041019 | wbemChangeFlagCreateOnly flag was specified, but the instance already exists.
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrIllegalNull 0x8004100A | A value of Nothing was specified for a property that may not be Nothing, such as one that is marked by a key, indexed, or not_null qualifier.
wbemErrInvalidObject 0x80041014 | The specified instance is invalid.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrNotFound 0x80041002 | wbemChangeFlagUpdateOnly flag was specified, but the instance or class does not exist.
wbemErrIncompleteClass 0x80041020 | Required properties for classes have not all been set.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemObjectPath.Class, SWbemQualifier, SWbemProperty


SWbemObject.Qualifiers_

The Qualifiers_ property of the SWbemObject object returns an SWbemQualifierSet object that is a collection of the CIM qualifiers for the current class or instance. This property is read-only.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objQualifierSet = objwbemObject.Qualifiers_

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemObject.References_

The References_ method of the SWbemObject object returns a collection of all association classes or instances that refer to the current object.

This method performs the same function that the WQL "References Of" query performs.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objWbemObjectSet = objwbemObject.References_(
[strResultClass=""],
[strRole=""],
[bClassesOnly=FALSE],
[bSchemaOnly=FALSE],
[strRequiredQualifier=""],
[iFlags=wbemFlagReturnImmediately],
[objwbemNamedValueSet=null]
)

Parameters

strResultClass
Optional. This is a string that contains a class name. This parameter, if specified, indicates that the returned association objects must belong to or be derived from the class specified in this parameter.
strRole
Optional. This is a string that contains a property name. If specified, this parameter indicates that the returned association objects must be limited to those in which the source object plays a particular role. The role is defined by the name of a specified property—which must be a reference property—of an association.
bClassesOnly
Optional. This is a Boolean value that indicates whether a list of class names should be returned rather than actual instances of the classes. These are the classes to which the association objects belong. The default value for this parameter is FALSE.
bSchemaOnly
Optional. This is a Boolean value that indicates whether the query applies to schema rather than data. The default value for this parameter is FALSE. It can only be set to TRUE if the strObjectPath parameter specifies the object path of a class. When set to TRUE, the set of returned endpoints represent classes that are suitably associated with the source class in schema.
strRequiredQualifier
Optional. This is a string that contains a qualifier name. This parameter, if specified, indicates that the returned association objects must include the specified qualifier.
iFlags
Optional. This is an integer specifying additional flags to the operation. The default for this parameter is wbemFlagReturnImmediately, which directs the call to return immediately rather than wait until the query has completed. This parameter can accept the following values.
Value Meaning
wbemFlagForwardOnly
0x20 		This flag causes a forward-only enumerator to be returned. Forward-only enumerators are generally much faster and use less memory than conventional enumerators, but they do not allow calls to Clone or Reset.
wbemFlagBidirectional
0x0 		This flag causes WMI to retain pointers to objects of the enumeration until the client releases the enumerator.
wbemFlagReturnImmediately
0x10 		This flag causes the call to return immediately.
wbemFlagReturnWhenComplete
0x0 		This flag causes this call to block until the query has completed.

objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.

Return Values

If the call is successful, an object of type SWbemObjectSet will be returned.

Error Codes

The References_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user does not have permission to view one or more of the classes returned by the call.
wbemErrFailed 0x80041001 | There is an unspecified error.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Remarks

For information about the associated WQL query "References Of", source instances, and association objects, see Data Queries.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemServices.ReferencesTo, SWbemServices.AssociatorsOf, SWbemObject.Associators_


SWbemObject.ReferencesAsync_

The ReferencesAsync_ method of the SWbemObject object returns a collection of all association classes or instances that refer to the current object.

This method performs the same function that the WQL "References Of" query performs. This call will return immediately and the results and status will be returned to the caller through the supplied object sink.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemObject.ReferencesAsync_(
objWbemSink,
[strResultClass=""],
[strRole=""],
[bClassesOnly=FALSE],
[bSchemaOnly=FALSE],
[strRequiredQualifier=""],
[iFlags],
[objwbemNamedValueSet=null],
[objWbemAsyncContext]
)

Parameters

objWbemSink
Required. This is the object sink that will receive the objects asynchronously.
strResultClass
Optional. This is a string that contains a class name. This parameter, if specified, indicates that the returned association objects must belong to or be derived from the class specified in this parameter.
strRole
Optional. This is a string that contains a property name. If specified, this parameter indicates that the returned association objects must be limited to those in which the source object plays a particular role. The role is defined by the name of a specified property—which must be a reference property—of an association.
bClassesOnly
Optional. This is a Boolean value that indicates whether a list of class names should be returned rather than actual instances of the classes. These are the classes to which the association objects belong. The default value for this parameter is FALSE.
bSchemaOnly
Optional. This is a Boolean value that indicates whether the query applies to schema rather than data. The default value for this parameter is FALSE. It can only be set to TRUE if the strObjectPath parameter specifies the object path of a class. When set to TRUE, the set of returned endpoints represent classes that are suitably associated with the source class in schema.
strRequiredQualifier
Optional. This is a string that contains a qualifier name. This parameter, if specified, indicates that the returned association objects must include the specified qualifier.
iFlags
Optional. This is an integer specifying additional flags to the operation. This parameter can accept the following values.
Value Meaning
wbemFlagSendStatus
0x80 		This flag causes asynchronous calls to send status updates to the OnProgress event handler for your object sink.
wbemFlagDontSendStatus
0x0 		This flag prevents asynchronous calls from sending status updates to the OnProgress event handler for your object sink

objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.
objWbemAsyncContext
Optional. This is an object of type SWbemNamedValueSet that returns to the object sink to identify the source of the original asynchronous call. Use this parameter if you are making multiple asynchronous calls using the same object sink. To use this parameter, create an SWbemNamedValueSet object and use the SWbemNamedValueSet.Add method to add a value that identifies the asynchronous call you are making. This SWbemNamedValueSet object will be returned to the object sink and the source of the call can be extracted using the SWbemNamedValueSet.item method. For more information, see Making an Asynchronous Call Using the Scripting API.

Return Values

None. If successful, the results of the asynchronous call are provided through this sink as an object of type SWbemObjectSet. This object is a collection of all association classes or instances that refer to the current object.

Error Codes

The References_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user does not have permission to view one or more of the classes returned by the call.
wbemErrFailed 0x80041001 | There is an unspecified error.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Remarks

For information about the associated WQL query "References Of", source instances, and association objects, see Data Queries.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemServices.ReferencesTo,

SWbemServices.ReferencesToAsync, SWbemServices.AssociatorsOf, SWbemObject.Associators_


SWbemObject.Security_

The Security_ property of the SWbemObject object is used to read or set the security settings for an SWbemObject object. This property is an object of type SWbemSecurity.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemSecurity = objwbemObject.Security_

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

Setting the DCOM Impersonation Level for the Scripting API, Object Creation and Monikers


SWbemObject.SpawnDerivedClass_

Use the SpawnDerivedClass_ method of the SWbemObject object to create a derived class object from the current object. The object must be a class definition that becomes the superclass of the spawned object.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objNewClass = objwbemObject.SpawnDerivedClass_(
[iFlags=0]
)

Parameters

iFlags
Optional. This parameter is reserved and must be zero if specified.

Return Values

If the call is successful, an object of type SWbemObject returns that contains the new class definition object. No object returns when there is an error.

Error Codes

The SpawnDerivedClass_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrFailed 0x8004100 | This is an unspecified error.
wbemErrIllegalOperation 0x8004101E | The user requested an illegal operation, such as spawning a class from an instance.
wbemErrIncompleteClass 0x80041020 | The source class was not completely defined or registered with WMI, so a new derived class is not permitted.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Remarks

The object returned automatically becomes a subclass of the current object. This behavior cannot be overridden. There is no other method by which you can create derived classes.

You cannot create a derived class from a class that is local to your own client process. Before you can use this method to create a derived class, you must create the base class. To create the base class, call SWbemObject.Put_, and retrieve it using SWbemServices.Get.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemObject.SpawnInstance_

Use the SpawnInstance_ method of the SWbemObject object to create a new instance of a class. The current object must be a class definition obtained from WMI via a method such as SWbemServices.Get or SWbemServices.ExecQuery. Then use this class definition to create new instances. Create each new instance locally within the process, and then call SWbemObject.Put_ to actually create the instance within WMI.

Note spawning an instance from an instance is supported but the returned instance will be empty.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objNewInstance = objwbemObject.SpawnInstance_(
[iFlags=0]
)

Parameters

iFlags
Optional. This parameter is reserved and must be zero if specified.

Return Values

If successful, this call returns an object of type SWbemObject that contains a new instance of the class.

Error Codes

The SpawnInstance_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrIncompleteClass 0xH80041020 | The current object is not a valid class definition, and it cannot spawn new instances. Either it is incomplete, or it has not been registered with WMI using SWbemObject.Put_.
wbemErrIllegalOperation 0xH8004101E | Returned if this method is used on an instance instead of a class.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemServices.Get, SWbemObject.Put_


SWbemObject.Subclasses_

The Subclasses_ method of the SWbemObject object returns an object of type SWbemObjectSet. This object is a collection of subclasses of the current object, which must be a class. Items in the returned collection can be obtained by way of standard collection methods. See Collections for information on using collections.

Note It is not an error for the returned collection to have zero elements if there are no subclasses of the current object. This method only works for class objects.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objWbemObjectSet = objwbemObject.Subclasses_(
[iFlags= wbemFlagReturnImmediately+wbemQueryFlagDeep],
[objwbemNamedValueSet=null]
)

Parameters

iFlags
Optional. This determines how deep the enumeration will be. This parameter can accept the following values.
Value Meaning
wbemQueryFlagDeep
0 		This value forces recursive enumeration into all subclasses derived from the specified superclass. The superclass itself is not returned in the enumeration.
wbemQueryFlagShallow
0x1 		This is the default for this parameter. It forces the enumeration to include only immediate subclasses of the specified superclass.
WbemFlagReturnImmediately
0x10 		This flag causes the call to return immediately
wbemFlagReturnWhenComplete
0x0 		This flag causes this call to block until the call has completed.

objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.

Return Values

If the call is successful, an object of type SWbemObjectSet will be returned.

Error Codes

The Subclasses_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user does not have permission to view one or more of the classes returned by the call.
wbemErrFailed 0x80041001 | There is an unspecified error.
wbemErrInvalidClass 0x80041010 | The specified class did not exist.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemObjectSet


SWbemObject.SubclassesAsync_

The SubclassesAsync_ method of the SWbemObject object asynchronously returns a collection of subclasses of the current object, which must be a class. This call will return immediately and the results of the put operation will be returned to the caller through the supplied object sink. Items in the returned collection can be obtained by way of standard collection methods. See Collections for information on using collections.

Note It is not an error for the returned collection to have zero elements if there are no subclasses of the current object. This method only works for class objects.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemObject.SubclassesAsync_(
objWbemSink,
[iFlags= wbemQueryFlagDeep],
[objwbemNamedValueSet=null]
[objWbemAsyncContext]
)

Parameters

objWbemSink
Required. This is the object sink that will receive the objects asynchronously.
iFlags
Optional. This determines how deep the enumeration will be. This parameter can accept the following values.
Value Meaning
wbemQueryFlagDeep
0 		This value forces recursive enumeration into all subclasses derived from the specified superclass. The superclass itself is not returned in the enumeration.
wbemQueryFlagShallow
0x1 		This is the default for this parameter. It forces the enumeration to include only immediate subclasses of the specified superclass.
wbemFlagSendStatus
0x80 		This flag causes asynchronous calls to send status updates to the OnProgress event handler for your object sink.
wbemFlagDontSendStatus
0x0 		This flag prevents asynchronous calls from sending status updates to the OnProgress event handler for your object sink

objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.
objWbemAsyncContext
Optional. This is an object of type SWbemNamedValueSet that returns to the object sink to identify the source of the original asynchronous call. Use this parameter if you are making multiple asynchronous calls using the same object sink. To use this parameter, create an SWbemNamedValueSet object and use the SWbemNamedValueSet.Add method to add a value that identifies the asynchronous call you are making. This SWbemNamedValueSet object will be returned to the object sink and the source of the call can be extracted using the SWbemNamedValueSet.item method. For more information, see Making an Asynchronous Call Using the Scripting API.

Return Values

None. If the call is successful, an object of type SWbemObjectSet will be returned to the supplied object sink.

Error Codes

The SubclassesAsync_ method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user does not have permission to view one or more of the classes returned by the call.
wbemErrFailed 0x80041001 | There is an unspecified error.
wbemErrInvalidClass 0x80041010 | The specified class did not exist.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemObjectSet


SWbemObjectPath

Use the methods and properties of the SWbemObjectPath object to construct and validate an object path.

Methods

Method | Description
SetAsClass | Forces the path to address a Common Information Model (CIM) class.
SetAsSingleton | Forces the path to address a singleton CIM instance.

Properties

Property | Description
Authority | A string that defines the Authority component of the object path.
Class | The name of the class that will be part of the object path.
DisplayName | A string that contains the path in a form that can be used as a moniker display name. See Object Creation and Monikers.
IsClass | Boolean value that indicates if this path represents a class. This is analogous to the __GENUS property in the Component Object Model (COM) API.
IsSingleton | Boolean value that indicates if this path represents a singleton instance.
Keys | This property is an SWbemNamedValueSet that contains the key value bindings.
Locale | A string containing the locale for this object path
Namespace | The name of the namespace that is part of the object path. This is the same as the __NAMESPACE property in the COM API.
ParentNamespace | The name of the parent of the namespace that is part of the object path.
Path | Contains the absolute path. This is the same as the __PATH system property in the COM API. This is the default property of this object.
Relpath | Contains the relative path. This is the same as the __RELPATH system property in the COM API.
Security_ | Used to read or change the security settings.
Server | The name of the server. This is the same as the __SERVER system property in the COM API.


SWbemObjectPath.SetAsClass

The SetAsClass method of the SWbemObjectPath object forces the path to address a CIM class.

Syntax

objwbemObjectPath.SetAsClass

Return Values

None.

Error Codes

The SetAsClass method can return the following error code.

Error | Meaning
wbemErrFailed 0x80041001 | This is an unspecified error.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemObjectPath.SetAsSingleton

The SetAsSingleton method of the SWbemObjectPath object forces the path to address a singleton CIM instance. A singleton class is a class that can never have more than one instance.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemObjectPath.SetAsSingleton()

Return Values

This method has no return values.

Error Codes

The SetAsSingleton method can return the following error code.

Error | Meaning
wbemErrFailed 0x80041001 | This is an unspecified error.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemObjectPath.Authority

The Authority property of the SWbemObjectPath object contains a string that defines the Authority component of the object path. See the strAuthority parameter of the SWbemLocator.ConnectServer method and Using Kerberos or NTLM Authentication with the Scripting API for more information.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

strAuthority = objwbemObjectPath.Authority
objwbemObjectPath.Authority = strAuthority

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemObjectPath.Class

The Class property of the SWbemObjectPath object is the name of the class that is part of the object path.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

strClass = objwbemObjectPath.Class
objwbemObjectPath.Class = strClass

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemObjectPath.DisplayName

The DisplayName property of the SWbemObjectPath object is a string that contains the path in a form that can be used as a moniker display name.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

strDisplayName = objwbemObjectPath.DisplayName
objwbemObjectPath.DisplayName = strDisplayName

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemObjectPath.IsClass

The IsClass property of the SWbemObjectPath object is a Boolean value that indicates if this path represents a class. This property is read-only.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

bIsClass = objwbemObjectPath.IsClass

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemObjectPath.IsSingleton

The IsSingleton property of the SWbemObjectPath object is a Boolean value that indicates if this path represents a singleton instance. A singleton instance is an instance of a class that can never have more than one instance. This property is read-only.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

bIsSingleton = objwbemObjectPath.IsSingleton

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemObjectPath.Keys

The Keys property of the SWbemObjectPath object is an object of type SWbemNamedValueSet that contains the key value bindings.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objNamedValueSet = objwbemObjectPath.Keys

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemObjectPath.Locale

The Locale property of the SWbemObjectPath object contains the locale of object path.

When the SWbemObjectPath.locale property is part of a standalone SWbemObjectPath object, it is read-write and can be used to set the locale component of the Moniker.

When the SWbemObjectPath.locale property is accessed as part of a SWbemObject.Path_ property, it is read-only and reports the value of the locale used in binding to the Namespace from which the object was obtained.

For Microsoft locale identifiers, the format of the string is "MS_xxxx", where xxxx is a string in hexadecimal form that indicates the LCID. For example, American English would appear as "MS_409"

For more information about WMI localization see WMI Localization.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

strNamespace = objwbemObjectPath.Namespace
objwbemObjectPath.Namespace = strNamespace


SWbemObjectPath.Namespace

The Namespace property of the SWbemObjectPath object contains the name of the namespace that is part of the object path.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

strNamespace = objwbemObjectPath.Namespace
objwbemObjectPath.Namespace = strNamespace

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemObjectPath.ParentNamespace

The ParentNamespace property of the SWbemObjectPath object contains the name of the parent namespace that is part of the object path. This property is read-only.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

strParentNamespace = objwbemObjectPath.ParentNamespace

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemObjectPath.Path

The Path property of the SWbemObjectPath object contains the absolute path. This is the same as the __PATH property in the COM API. This is the default property of this object.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

strPath = objwbemObjectPath.Path
objwbemObjectPath.Path = strPath

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemObjectPath.Relpath

The Relpath property of the SWbemObjectPath object contains the relative path.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

strRelPath = objwbemObjectPath.RelPath
objwbemObjectPath.RelPath = strRelPath

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemObjectPath.Security_

The Security property of the SWbemObjectPath object is used to read or set the security components of an object path. Note that it is not used to set security attributes of the SWbemObjectPath object itself. It is used only to represent the security components of the path for an SWbemLocator object. This property is an object of type SWbemSecurity.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemSecurity = objwbemObjectPath.Security_

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

Setting the DCOM Impersonation Level for the Scripting API , Object Creation and Monikers


SWbemObjectPath.Server

The Server property of the SWbemObjectPath object contains the name of the server that is be part of the object path.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

strServer = objwbemObjectPath.Server
objwbemObjectPath. Server = strServer

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemObjectSet

An SWbemObjectSet object is a collection of objects of type SWbemObject. For information on using collections, see Collections.

You can get an SWbemObjectSet object by calling any of the following methods or their asynchronous equivalents:

SWbemServices.InstancesOf

SWbemServices.SubclassesOf

SWbemObject.Instances_

SWbemServices.ExecQuery

SWbemServices.AssociatorsOf

SWbemServices.ReferencesTo

SWbemObject.Associators_

SWbemObject.References_

SWbemObject.Subclasses_

Note SWbemObjectSet does not support the optional Add and Remove collection methods.

Methods

Method | Description
Item | Retrieves an SWbemObject from the collection. This is the default method of the object.

Properties

Property | Description
Count | The number of items in the collection.
Security_ | Used to read or change the security settings.


SWbemObjectSet.Item

The Item method of the SWbemObjectSet object gets an SWbemObject from the collection.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objObject = objwbemObjectSet.Item(
strObjectPath,
[iFlags=0]
)

Parameters

strObjectPath
Required. This parameter is the relative path of the object you want to retrieve from the collection (for example, Win32_LogicalDisk="C:").
iFlags
Optional. This parameter is reserved and the default value is 0.

Return Values

If successful, the requested SWbemObject returns.

Error Codes

The Item method can return the error codes listed in the following table.

Error | Meaning
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.
wbemErrNotFound 0x80041002 | The requested item was not found.

Remarks

This method may be expensive (require a lot of processor time) as complete enumeration by the provider of the elements of the set is required to return the result.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemObjectSet.Count

Use the Count property of the SWbemObjectSet object to determine how many items are in the context collection. This property is read-only.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

iCount = objWbemObjectSet.Count

Remarks

This method may be expensive (require a lot of processor time) as complete enumeration by the provider of the elements of the set is required to return the result.

Note If you attempt to get this property from an SWbemObjectSet that was returned from a method where the specified flags included wbemFlagForwardOnly, you will get an wbemErrFailed error.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemObjectSet.Security_

The Security_ property of the SWbemObjectSet object is used to read or set the security settings for an SWbemObjectSet object. This property is an object of type SWbemSecurity.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemSecurity = SWbemObjectSet.Security_

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

WMI Scripting Security Issues, Object Creation and Monikers


SWbemPrivilege

The SWbemPrivilege object represents a single privilege.

Methods

None.

Properties

Property | Description
Displayname | The display name of this privilege.
Identifier | The integer that represents the privilege that is being set or retrieved.
IsEnabled | Boolean value that indicates if this privilege is enabled.
Name | The name of this privilege.

See Also

Setting Privileges for the Scripting API


SWbemPrivilege.DisplayName

The DisplayName property of an SWbemPrivilege object is a string that displays a description of an SWbemPrivilege object. For example, the privilege that controls if a user can execute the shutdown method of a CIM object has the SWbemPrivilege DisplayName of "Shut down the system" This property is read-only.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

sDisplayName = objWbemPrivilege.DisplayName

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemPrivilege.Identifier

The Identifier property of an SWbemPrivilege object is an integer of type WbemPrivilegeEnum that represents the privilege that is being set or retrieved.

Note This property is read only.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

iPrivilege = objWbemPrivilege.Identifier
objWbemPrivilege.Identifier= Identifier

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

WbemPrivilegeEnum


SWbemPrivilege.IsEnabled

The IsEnabled property of an SWbemPrivilege object is a Boolean value that you use to enable or disable this privilege.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

bIsEnabled = objwbemPrivilege.IsEnabled
objwbemPrivilege.IsEnabled = bIsEnabled

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemPrivilege.Name

The Name property of an SWbemPrivilege object is a string that uniquely describes a privilege. For example, the privilege that controls whether a user can execute the shutdown method of a CIM object has the SWbemPrivilege Name of "SeShutdownPrivilege". This property is read-only.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

sName = objWbemPrivilege.Name

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemPrivilegeSet

An SWbemPrivilegeSet object is a collection of objects of type SWbemPrivilege. Items are added to the collection using the Add and AddAsString methods, retrieved using the Item method, and removed from the collection using the Remove method.

For information on using collections, see Collections.

An SWbemPrivilegeSet object is a set of "privilege override requests" for a particular object which will be attempted to be enforced when making API calls with that object. An SWbemPrivilegeSet does not define the privileges available to the current user or process.

Methods

Method | Description
Add | Adds an SWbemPrivilege object to the SWbemPrivilegeSet collection using a WbemPrivilegeEnum constant.
AddAsString | Adds an SWbemPrivilege object to the SWbemPrivilegeSet collection using a Windows NT/Windows 2000 privilege string.
Item | Retrieves an SWbemPrivilege object from the collection. This is the default method of this object.
DeleteAll | Deletes all the privileges from the collection.
Remove | Removes an SWbemPrivilege object from the collection.

Properties

Property | Description
Count | The number of items in the collection.

See Also

Setting Privileges for the Scripting API, WbemPrivilegeEnum


SWbemPrivilegeSet.Add

The Add method of the SWbemPrivilegeSet object adds an SWbemPrivilege object to the SWbemPrivilegeSet collection. If a Privilege with the same name already exists in the collection, it is replaced.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objPrivilege = objwbemPrivilegeSet.Add(
iPrivilege,
[bIsEnabled = True]
)

Parameters

iPrivilege
Required. This is an one of the WMI constants from the group WbemPrivilegeEnum. These constants are essentially integers that represent specific privileges. For example, to add the privilege that allows you to shut down a Windows NT/Windows 2000 system, you would use the constant wbemPrivilegeShutdown or the numeric equivalent 0x17. For a complete list of these constants and the associated Windows NT/Windows 2000 Privilege Strings, see Windows NT/Windows 2000 Privilege Strings.
bIsEnabled
Optional. This is a Boolean value that enables or disables this privilege. The default value is TRUE.

Return Values

This method returns an SWbemPrivilege object that represents the new Privilege, if successful. Otherwise, a null object returns.

Error Codes

The Add method can return the error codes listed in the following table.

Error | Meaning
wbemErrFailed 0x80041001 | This is an unspecified error.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemPrivilegeSet.Remove, SWbemPrivilegeSet.AddAsString, Setting Privileges for the Scripting API, WbemPrivilegeEnum


SWbemPrivilegeSet.AddAsString

The AddAsString method of the SWbemPrivilegeSet allows you to add a privilege to an SWbemPrivilegeSet collection using a Windows NT/Windows 2000 privilege string. This is method is useful when a CIM class that advertises the privileges it requires as qualifier values of type string[] with elements defined by NT privilege strings.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objPrivilege = objwbemPrivilegeSet.AddAsString(
strPrivilege,
[bIsEnabled = True]
)

Parameters

strPrivilege
Required. This is one of the Windows NT/Windows 2000 privilege strings. For a complete list of these strings and the associated WMI constants, see Windows NT/Windows 2000 Privilege Strings. Every Windows NT/Windows 2000 privilege string represents a specific privilege. For example, to add the privilege that allows you to shut down a Windows NT/Windows 2000 system, you would use the string "SeShutdownPrivilege".
bIsEnabled
Optional. This is a Boolean value that enables or disables this privilege. The default value is TRUE.

Return Values

This method returns an SWbemPrivilege object that represents the new Privilege, if successful. Otherwise, a null object returns.

Error Codes

The AddAsString method can return the error codes listed in the following table.

Error | Meaning
wbemErrFailed 0x80041001 | This is an unspecified error.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemPrivilegeSet.Remove, SWbemPrivilegeSet.Add, WbemPrivilegeEnum


SWbemPrivilegeSet.DeleteAll

The DeleteAll method of the SWbemPrivilegeSet object removes all privileges from the collection, thus emptying it.

Syntax

objwbemPrivilegeSet.DeleteAll

Return Values

This method has no return values.

Error Codes

The DeleteAll method can return the error code listed in the following table.

Error | Meaning
wbemErrFailed 0x80041001 | This is an unspecified error.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemPrivilegeSet.Remove, Setting Privileges for the Scripting API


SWbemPrivilegeSet.Count

The Count property of the SWbemPrivilege object contains the number of items in an SWbemPrivilegeSet collection. This property is read-only.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

iCount = objwbemPrivilegeSet.Count

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemPrivilegeSet.Item

The Item method of the SWbemPrivilegeSet object returns an SWbemPrivilege from the collection. The Item method is the default method of an SWbemPrivilegeSet object.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objPrivilege= objwbemPrivilegeSet.Item(
iPrivilege,
)

Parameters

iPrivilege
Required. This is an one of the WMI constants from the group WbemPrivilegeEnum. These constants are essentially integers that represent specific privileges. For example, to get the privilege that allows you to shut down a Windows NT/Windows 2000 system, you would use the constant wbemPrivilegeShutdown or the numeric equivalent 0x17.

Return Values

If successful, the requested SWbemPrivilege returns.

Error Codes

The Item method can return the error codes listed in the following table.

Error | Meaning
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrNotFound 0x80041002 | The specified Privilege does not exist.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemPrivilege, Setting Privileges for the Scripting API


SWbemPrivilegeSet.Remove

The Remove method of the SWbemPrivilegeSet object deletes a Privilege from the collection.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemPrivilegeSet.Remove(
iPrivilege,
)

Parameters

iPrivilege
Required. This is an one of the WMI constants from the group WbemPrivilegeEnum. These constants are essentially integers that represent specific privileges. For example, to remove the privilege that allows you to shut down a Windows NT/Windows 2000 system, you would use the constant wbemPrivilegeShutdown or the numeric equivalent 0x17.

Return Values

This method has no return values.

Error Codes

The Remove method can return the error codes listed in the following table.

Error | Meaning
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrNotFound 0x80041002 | The specified Privilege does not exist.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemPrivilegeSet.Add


SWbemProperty

The SWbemProperty object represents a single CIM property of a managed object.

Methods

None.

Properties

Property | Description
CIMType | The CIM Type of this property.
IsArray | Boolean value that indicates if this property has an array type.
IsLocal | Boolean value that indicates if this is a local property.
Name | Name of this property.
Origin | Contains the originating class of this property.
Qualifiers_ | This is an SWbemQualifierSet, which is the collection of qualifiers for this property.
Value | The actual value of this property. This is the default automation property of this object.


SWbemProperty.CIMType

Use the CIMType property of the SWbemProperty object to determine the CIM type of this property. This property is read-only.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

iCIMType = objwbemProperty.CIMType

Remarks

See WbemCimtypeEnum for the table of CIMTypes and their values.

Instances of embedded objects are stored in composite objects as properties of type CIM_OBJECT. To determine the class of an embedded object in an instance of a composite class, you need to examine the CIMType qualifier of the CIM_OBJECT property.

The object references in an association class are stored in properties of type CIM_RERERENCE. To determine the actual object paths you need to examine the CIMType qualifier of the CIM_RERERENCE type properties.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemProperty.IsArray

The IsArray property of the SWbemProperty object is a Boolean value used to determine if this property has an array type. This property is read-only.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

bIsArray = objwbemProperty.IsArray

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemProperty.IsLocal

The IsLocal property of the SWbemProperty object is a Boolean value used to determine if this property is local. A value of FALSE indicates that this property has been inherited from another class. This property is read-only.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

bIsLocal = objwbemProperty.IsLocal

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemProperty.Name

The Name property of the SWbemProperty object returns the name of this CIM property. This property is read-only.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

strName = objwbemProperty.Name

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemProperty.Origin

The Origin property of the SWbemProperty object retrieves the name of the CIM class in which this CIM property was introduced. For classes with deep inheritance hierarchies, it is often desirable to know which properties were declared in which classes.

If the property is local (see SWbemQualifier.IsLocal), this will be same as the owning class. This property is read-only.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

strOriginClassName = objwbemProperty.Origin

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemProperty.Qualifiers_

The Qualifiers_ property of the SWbemProperty object returns an object of type SWbemQualifierSet that is the collection of qualifiers for this CIM property. This property is read-only.

Syntax

objQualifierSet = objwbemProperty.Qualifiers_

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemProperty.Value

The Value property of the SWbemProperty object defines the variant value of the CIM property. This is the default automation property of this object.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

varValue = objwbemProperty.Value
objwbemProperty.Value = varValue

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemPropertySet

An SWbemPropertySet object is a collection of objects of type SWbemProperty. You can add items to the collection using the Add method, retrieve items using the Item method, and remove items from the collection using the Remove method. For information on using collections, see Collections.

The SWbemProperty objects that make up an SWbemPropertySet collection are used to describe the properties of a single CIM class or instance.

Methods

Method | Description
Add | Adds an SWbemProperty object to the SWbemPropertySet collection.
Item | Retrieves an SWbemProperty from the collection. This is the default method of this object.
Remove | Removes an SWbemProperty object from the collection.

Property

Property | Description
Count | The number of items in the collection.


SWbemPropertySet.Add

The Add method of the SWbemPropertySet object adds an SWbemProperty object to the SWbemPropertySet collection. If a property with the same name already exists in the collection, its contents are replaced with the new definition.

Note The value of the property is NULL (unassigned) after this operation. To set or change the value of a Common Information Model (CIM) property, you must set the Value property of the returned SWbemProperty.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objProperty = objwbemPropertySet.Add(
strName,
iCIMType,
[bIsArray=FALSE],
[iFlags=0]
)

Parameters

strName
Required. This is the name of the new property.
iCIMType
Required. This is the CIMType of the new property. See WbemCimTypeEnum for the table with the CIMTypes and their values.
bIsArray
Optional. This specifies whether the property is an array type. The default value for this parameter is FALSE.
iFlags
Optional. This parameter is reserved and must be zero if specified.

Return Values

This method returns an SWbemProperty object that represents the new property, if successful. Otherwise, a null object returns.

Error Codes

The Add method can return the error codes listed in the following table.

Error | Meaning
wbemErrFailed 0x80041001 | This is an unspecified failure.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory for this method to execute.
wbemErrInvalidPropertyType 0x8004102A | The CIM type is not recognized.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemProperty.Value, SWbemPropertySet.Remove


SWbemPropertySet.Item

The Item method of the SWbemPropertySet object gets a named SWbemProperty from the collection. This is the default method for this object.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objProperty = objwbemPropertySet.Item(
strName,
[iFlags=0]
)

Parameters

strName
Required. This is the name of the property to retrieve.
iFlags
Optional. This parameter is reserved and must be zero if specified.

Return Values

If successful, the requested SWbemProperty returns.

Error Codes

The Item method can return the error codes listed in the following table.

Error | Meaning
wbemErrFailed 0x80041001 | This is an unspecified failure.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory for this method to execute.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemPropertySet.Remove

The Remove method of the SWbemPropertySet object deletes a property from the SWbemPropertySet collection.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemPropertySet.Remove(
strName,
[iFlags=0]
)

Parameters

strName
Required. This is the name of the item to remove.
iFlags
Optional. This parameter is reserved and must be zero if specified.

Return Values

This method has no return values.

Error Codes

The Remove method can return the error codes listed in the following table.

Error | Meaning
wbemErrFailed 0x80041001 | This is an unspecified failure.
wbemErrInvalidOperation 0x80041016 | The user attempted to delete a property that cannot be deleted.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrNotFound 0x80041002 | The specified property does not exist.
wbemErrOutOfMemory 0x80041006 | There was not enough memory for this method to execute.
wbemErrPropagatedProperty 0x2147217380 | The user attempted to delete a property that was not owned. The property was inherited from a parent class.
wbemErrResetToDefault 0x80043002 | The user deleted an override default value for the current class. The default value for this property in the parent class has been reactivated.

Remarks

Properties cannot be removed from class instances or derived classes with inherited properties. Such deletion attempts will raise an error and the property will not be removed, rather it will be reset to its default value.

You cannot iterate a collection while removing items because when you remove an element from a collection, the collection pointer is moved on to the next element. See Removing Items from Collections for more information.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemPropertySet.Add


SWbemPropertySet.Count

Use the Count automation property of the SWbemPropertySet object to determine how many items are in the SWbemPropertySet collection. This property is read-only.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

iCount = objwbemPropertySet.Count

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemQualifier

You can use the properties of the SWbemQualifier object to represent a single CIM qualifier of a CIM Class, CIM Instance, CIM property, CIM method, or CIM method parameter.

Methods

No methods.

Properties

Property | Description
IsAmended | Boolean value that indicates if this qualifier has been localized using a merge operation
IsLocal | Boolean value that indicates if this is a local qualifier.
IsOverridable | Boolean value that indicates if this qualifier can be overridden when propagated.
Name | Name of this qualifier.
PropagatesToInstance | Boolean value that indicates if this qualifier can be propagated to an instance.
PropagatesToSubclass | Boolean value that indicates if this qualifier can be propagated to a subclass.
Value | The actual value of this qualifier. This is the default property of this object.


SWbemQualifier.IsAmended

The IsAmended property of the SWbemQualifier object is a Boolean value that indicates if this qualifier has been localized using a merge operation.


SWbemQualifier.IsLocal

The IsLocal property of the SWbemQualifier object is a Boolean value that indicates if the qualifier is local. This property is read-only.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

bIsLocal = objwbemQualifier.IsLocal

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemQualifier.PropagatesToInstance

The PropagatesToInstance property of the SWbemQualifier object is a Boolean value that indicates if this qualifier can be propagated to an instance.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

bPropagatesToInstance = objwbemQualifier.PropagatesToInstance
objwbemQualifier.PropagatesToInstance = bPropagatesToInstance

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemQualifier.PropagatesToSubClass

The PropagatesToSubClass property of the SWbemQualifier object is a Boolean value that indicates if this qualifier can be propagated to an subclass.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

bPropagatesToSubclass = objwbemQualifier.PropagatesToSubclass
objwbemQualifier.PropagatesToSubclass = bPropagatesToSubclass

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemQualifier.Value

The Value property of the SWbemQualifier object contains the variant value of the CIM qualifier. This is the default property of this object.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

varValue = objwbemQualifier.Value
objwbemQualifier.Value = varValue

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemQualifier.Name

The Name property of the SWbemQualifier object defines the name of this qualifier. This property is read-only.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

strQualifierName = objwbemQualifier.Name

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemQualifier.IsOverridable

The IsOverridable property of the SWbemQualifier object is a Boolean value that indicates if the qualifier can be overridden when propagated.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

bIsOverridable = objwbemQualifier.IsOverridable
objwbemQualifier.IsOverridable = bIsOverridable

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemQualifierSet

An SWbemQualifierSet object is a collection of objects of type SWbemQualifier. Items are added to the collection using the Add method, retrieved using the Item method, and removed from the collection using the Remove method.

For information on using collections, see Collections.

The SWbemQualifier objects that make up an SWbemQualifierSet collection describe the CIM qualifiers attached to a CIM Class, CIM Instance, CIM Method, or CIM Method Parameter.

Methods

Method | Description
Add | Adds an SWbemQualifier object to the SWbemQualifierSet collection.
Item | Retrieves an SWbemQualifier from the collection. This is the default method of this object.
Remove | Removes an SWbemQualifier object from the collection.

Properties

Property | Description
Count | The number of items in the collection.


SWbemQualifierSet.Add

The Add method of the SWbemQualifierSet object adds an SWbemQualifier object to the SWbemQualifierSet collection. If a qualifier with the same name already exists in the collection, it is replaced.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objQualifier = objwbemQualifierSet.Add(
strName,
varVal,
[bPropagatesToSubclasses=TRUE],
[bPropagatesToInstances=TRUE],
[bOverridable=TRUE],
[iFlags=0]
)

Parameters

strName
Required. This parameter is the name of the new qualifier.
varVal
Required. This parameter is the variant value of the new qualifier.
bPropagatesToSubclasses
Optional. This parameter is a Boolean value that indicates if this new qualifier will be propagated to subclasses. The default value is TRUE.
bPropagatesToInstances
Optional. This parameter is a Boolean value that indicates if this new qualifier will be propagated to instances. The default value is TRUE.
bOverridable
Optional. This parameter is a Boolean value that indicates if this qualifier can be overridden when propagated. The default value is TRUE.
iFlags
Optional. This parameter is reserved and the default value is 0.

Return Values

This method returns an SWbemQualifier object that represents the new qualifier, if successful. Otherwise, a null object returns.

Error Codes

The Add method can return the error codes listed in the following table.

Error | Meaning
wbemErrInvalidParameter 0x80041008 | The iFlags parameter was not valid.
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrCannotBeKey 0x8004101F | There was an illegal attempt to specify a key qualifier on a property that cannot be a key. The keys are specified in the class definition for an object, and cannot be altered on a per-instance basis.
wbemErrInvalidQualifierType 0x80041029 | The varVal parameter is not of a legal qualifier type.
wbemErrOverrideNotAllowed 0x8004101A | It is not possible to perform the SWbemQualifierSet.Add operation on this qualifier because the owning object does not permit overrides.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemQualifierSet.Remove


SWbemQualifierSet.Item

The Item method of the SWbemQualifierSet object returns a named SWbemQualifier from the collection. It is the default method of this object.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objQualifier= objwbemQualifierSet.Item(
strName,
[iFlags=0]
)

Parameters

strName
Required. This parameter is the name of the qualifier to retrieve.
iFlags
Optional. This parameter is reserved and the default value is 0.

Return Values

If successful, the requested SWbemQualifier returns.

Error Codes

The Item method can return the error codes listed in the following table.

Error | Meaning
wbemErrInvalidParameter 0x80041008 | The iFlags parameter was not valid.
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrNotFound 0x80041002 | The specified qualifier does not exist.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemQualifier


SWbemQualifierSet.Remove

The Remove method of the SWbemQualifierSet object deletes a named qualifier from the collection.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemQualifierSet.Remove(
strName,
[iFlags=0]
)

Parameters

strName
Required. This parameter is the name of the qualifier to remove.
iFlags
Optional. This parameter is reserved and the default value is 0.

Return Values

This method has not return values.

Error Codes

The Remove method can return the error codes listed in the following table.

Error | Meaning
wbemErrInvalidParameter 0x80041008 | The iFlags parameter was not valid.
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrNotFound 0x80041002 | The specified qualifier does not exist.
wbemErrInvalidOperation 0x80041016 | Removing this qualifier is illegal.

Note You cannot iterate a collection while removing items because when you remove an element from a collection, the collection pointer is moved on to the next element. See Removing Items from Collections for more information.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemQualifierSet.Add


SWbemQualifierSet.Count

The Count property of the SWbemQualifierSet object contains the number of items in an SWbemQualifierSet collection. This property is read-only.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

iCount = objwbemQualifierSet.Count

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.


SWbemSecurity

The SWbemSecurity object is used to read or set the security settings such as Windows NT/Windows 2000 Privileges, DCOM Impersonation, and Authentication levels assigned to an object. Objects of type SWbemLocator, SWbemServices, SWbemObject, SWbemObjectSet, SWbemObjectPath, SWbemLastError and SWbemEventSource have a property called Security_. that is an SWbemSecurity type object. You may need to set the properties of the Security_ when performing tasks such as retrieving an instance or viewing the Windows NT/Windows 2000 security log using WMI.

Methods

None.

Properties

Property | Description
AuthenticationLevel | This is a numeric value that defines the DCOM Authentication level assigned to this object. This setting determines how you want to protect information sent to you from WMI.
ImpersonationLevel | This is a numeric value that defines the DCOM Impersonation level assigned to this object. This setting determines if processes owned by WMI can see or use your security credentials when making calls to other processes.
Privileges | This is an object of type SWbemPrivilegeSet that defines the Windows NT/Windows 2000 Privileges for this object.

Note The properties of an SWbemLocator.Security_ object have no default values. If you attempt to get the value of SWbemSecurity.AuthenticationLevel or SWbemSecurity.ImpersonationLevel on an SWbemLocator object before you have set it, an wbemErrFailed error will result.


SWbemSecurity.AuthenticationLevel

The AuthenticationLevel property is an integer that defines the DCOM Authentication level assigned to an object. This setting determines how you want to protect information sent to you from WMI. See Setting the DCOM Authentication Level for the Scripting API for more information on authentication levels. Generally speaking, it is not necessary to set the authentication level when making WMI API calls. If you do not set this property, the default DCOM authentication level for your system will be used.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

iAuthenticationlevel = objWbemSecurity.AuthenticationLevel
objWbemSecurity.AuthenticationLevel = iAuthenticationlevel

Remarks

You can set the authentication level of an object of type SWbemServices, SWbemObject, SWbemObjectSet , SWbemObjectPath or SwbemLocator by setting the Security_ property AuthenticationLevel to the desired value.

For example to set the authentication level for an object of type SwbemObject:

objinstance.Security_.AuthenticationLevel = wbemAuthenticationLevelPkt

You can also specify authentication levels a part of a moniker. For example, the following example sets both the authentication level and the impersonation and retrieves an instance of the Win32_LogicalDisk 'C:'

Set objinst = GetObject("WinMgmts:{impersonationLevel=impersonate,"& _
                        "authenticationLevel=pktPrivacy}" & _
                        "!root/cimv2:Win32_LogicalDisk='c:'")

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

Setting the DCOM Authentication Level for the Scripting API.


SWbemSecurity.ImpersonationLevel

The ImpersonationLevel property is an integer that defines the DCOM impersonation level assigned to an object. This setting determines if processes owned by WMI can see or use your security credentials when making calls to other processes. See Setting the DCOM Impersonation Level for the Scripting API for more information on impersonation levels. If you do not specifically set the impersonation level, in either a moniker or by setting SWbemSecurity.ImpersonationLevel on a securable object, the current release of WMI sets the default impersonation level to wbemImpersonatonLevelImpersonate. Previous versions of WMI set the default impersonation level to WbemImpersonationLevelIdentify. If this setting is not sufficient, the provider may not service your request and the call to the WMI API may fail with an error code of wbemErrAccessDenied (hexadecimal 0x80041003).

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

iImpersonationLevel  = objWbemSecurity.ImpersonationLevel
objWbemSecurity.ImpersonationLevel = iImpersonationLevel

Remarks

You can set the impersonation level of an object of type SWbemServices, SWbemObject, SWbemObjectSet , SWbemObjectPath or SwbemLocator by setting the Security_ property ImpersonationLevel to the desired value. For example, to set the impersonation level for an object of type SwbemObject:

objinstance.Security_.ImpersonationLevel = wbemImpersonationLevelImpersonate

You can also specify impersonation levels a part of a moniker. For example, the following example sets both the authentication level and the impersonation and retrieves an instance of the Win32_Service 'Alerter'

Set objinst = GetObject("WinMgmts:{impersonationLevel=impersonate,"& _
                         "authenticationLevel=pktPrivacy}"& _
                         "!root/cimv2:Win32_service='ALERTER'")

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

Setting the DCOM Impersonation Level for the Scripting API


SWbemSecurity.Privileges

The Privileges property is an object of type SWbemPrivilegeSet. This property is used to enable or disable specific Windows NT/Windows 2000 privileges. You may need to set one of these privileges to perform specific tasks using the WMI API.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objPrivilegeSet = objwbemObject.Privileges

Remarks

You can change the privileges defined for objects of type SWbemServices, SWbemObject, SWbemObjectSet, SWbemObjectPath or SwbemLocator by adding items of type SWbemPrivilege to the Security_ property Privileges.

Note There are fundamental differences in how different versions of Windows handle changes to privileges. If you are developing an application that will only be used on Windows 2000 platforms, you can set or revoke privileges at any time. If your application needs to be portable for use on Windows NT 4 platforms, you must set the privileges before you make the first call to SWbemLocator:ConnectServer or as part of the moniker.

This example works on Windows NT/Windows 2000 Platforms.

Set Service = GetObject("winmgmts:{impersonationLevel=impersonate, (SeDebugPrivilege)}")

The following example may not work on Windows NT 4.x platforms. It attempts to perform the same task, but it sets the privilege after the initial login to WMI.

Set Service = GetObject("winmgmts:{impersonationLevel=impersonate}")
Service.Security_.Privileges.AddAsString "SeDebugPrivilege", True

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

Setting Privileges for the Scripting API


SWbemServices

You can use the methods of an SWbemServices object to perform operations against a namespace on a local or remote host.

Methods

Method | Description
AssociatorsOf | Returns a collection of objects (classes or instances) that are associated with a specified object. This method performs the same function that the WMI Query Language (WQL) "Associators Of" query performs.
AssociatorsOfAsync | Asynchronously returns a collection of objects (classes or instances) that are associated with a specified object. This method performs the same function that the WMI Query Language (WQL) "Associators Of" query performs.
Delete | Deletes an instance or class.
DeleteAsync | Asynchronously deletes an instance or class.
ExecMethod | Executes an object method.
ExecMethodAsync | Asynchronously executes an object method.
ExecNotificationQuery | Executes a query to receive events.
ExecNotificationQueryAsync | Asynchronously executes a query to receive events.
ExecQuery | Executes a query to retrieve a collection of objects (classes or instances).
ExecQueryAsync | Asynchronously executes a query to retrieve a collection of objects (classes or instances).
Get | Retrieves a class or instance.
GetAsync | Asynchronously retrieves a class or instance.
InstancesOf | Returns a collection of instances of a specified class.
InstancesOfAsync | Asynchronously returns a collection of instances of a specified class.
ReferencesTo | Returns a collection of objects (classes or instances) that refer to a single object. This method performs the same function that the WQL "References Of" query performs.
ReferencesToAsync | Asynchronously returns a collection of objects (classes or instances) that refer to a single object. This method performs the same function that the WQL "References Of" query performs.
SubclassesOf | Returns a collection of subclasses of a specified class.
SubclassesOfAsync | Asynchronously returns a collection of subclasses of a specified class.

Properties

Property | Description
Security_ | Used to read or change the security settings.


SWbemServices.AssociatorsOf

The AssociatorsOf method of the SWbemServices object returns a collection of objects (classes or instances) that are associated with a specified object. These returned objects are called endpoints. This method performs the same function that the WQL "Associators Of" query performs.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objWbemObjectSet = objwbemServices.AssociatorsOf(
strObjectPath,
[strAssocClass=""],
[strResultClass=""],
[strResultRole=""],
[strRole=""],
[bClassesOnly=FALSE],
[bSchemaOnly=FALSE],
[strRequiredAssocQualifier=""],
[strRequiredQualifier=""],
[iFlags=wbemFlagReturnImmediately],
[objwbemNamedValueSet=null]
)

Parameters

strObjectPath
Required. This is a string containing the object path of the source class or instance.
strAssocClass
Optional. This is a string that contains an association class. If specified, this parameter indicates that the returned endpoints must be associated with the source through the specified association class or a class derived from this association class.
strResultClass
Optional. This is a string that contains a class name. If specified, this optional parameter indicates that the returned endpoints must belong to or be derived from the class specified in this parameter.
strResultRole
Optional. This is a string that contains a property name. If specified, this parameter indicates that the returned endpoints must play a particular role in their association with the source object. The role is defined by the name of a specified property—which must be a reference property—of an association.
strRole
Optional. This is a string that contains a property name. If specified, this parameter indicates that the returned endpoints must participate in an association with the source object in which the source object plays a particular role. The role is defined by the name of a specified property—which must be a reference property—of an association.
bClassesOnly
Optional. This is a Boolean value that indicates whether a list of class names should be returned rather than actual instances of the classes. These are the classes to which the endpoint instances belong. The default value for this parameter is FALSE.
bSchemaOnly
Optional. This is a Boolean value that indicates whether the query applies to schema rather than data. The default value for this parameter is FALSE. It can only be set to TRUE if the strObjectPath parameter specifies the object path of a class. When set to TRUE, the set of returned endpoints represent classes that are suitably associated with the source class in schema.
strRequiredAssocQualifier
Optional. This is a string that contains a qualifier name. This parameter, if specified, indicates that the returned endpoints must be associated with the source object through an association class that includes the specified qualifier.
strRequiredQualifier
Optional. This is a string that contains a qualifier name. This parameter, if specified, indicates that the returned endpoints must include the specified qualifier.
iFlags
Optional. This is an integer specifying additional flags to the operation. The default for this parameter is wbemFlagReturnImmediately, which directs the call to return immediately rather than wait until the query has completed. This parameter can accept the following values.
Value Meaning
wbemFlagForwardOnly
0x20 		This flag causes a forward-only enumerator to be returned. Forward-only enumerators are generally much faster and use less memory than conventional enumerators, but they do not allow calls to Clone or Reset.
wbemFlagBidirectional
0x0 		This flag causes WMI to retain pointers to objects of the enumeration until the client releases the enumerator.
wbemFlagReturnImmediately
0x10 		This flag causes the call to return immediately.
wbemFlagReturnWhenComplete
0x0 		This flag causes this call to block until the query has completed.

objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.

Return Values

If the call is successful, an object of type SWbemObjectSet will be returned.

Error Codes

The AssociatorsOf method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user does not have permission to view one or more of the classes returned by the call.
wbemErrFailed 0x80041001 | There is an unspecified error.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.
wbemErrNotFound 0x80041002 | The requested item was not found.

Remarks

It is not an error for the returned collection to have zero elements.

For information about the associated WQL query "Associators Of", source instances and endpoints see "Data Queries" and "WMI Query Language".

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemServices.AssociatorsOfAsync, SWbemServices.ReferencesTo, SWbemObject.References_, SWbemObject.Associators_,SWbemObject.AssociatorsAsync_


SWbemServices.AssociatorsOfAsync

The AssociatorsOfAsync method of the SWbemServices object asynchronously returns a collection of objects (classes or instances) that are associated with a specified object. These returned objects are called endpoints. This method performs the same function that the WQL "Associators Of" query performs. This call will return immediately and the results and status will be returned to the caller through the supplied object sink.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objWbemServices.AssociatorsOfAsync(
objWbemSink
strObjectPath,
[strAssocClass=""],
[strResultClass=""],
[strResultRole=""],
[strRole=""],
[bClassesOnly=FALSE],
[bSchemaOnly=FALSE],
[strRequiredAssocQualifier=""],
[strRequiredQualifier=""],
[iFlags ],
[objWbemNamedValueSet=null]
[objWbemAsyncContext=null]
)

Parameters

objWbemSink
Required. This is the object sink that will receive the objects asynchronously.
strObjectPath
Required. This is a string containing the object path of the source class or instance.
strAssocClass
Optional. This is a string that contains an association class. If specified, this parameter indicates that the returned endpoints must be associated with the source through the specified association class or a class derived from this association class.
strResultClass
Optional. This is a string that contains a class name. If specified, this optional parameter indicates that the returned endpoints must belong to or be derived from the class specified in this parameter.
strResultRole
Optional. This is a string that contains a property name. If specified, this parameter indicates that the returned endpoints must play a particular role in their association with the source object. The role is defined by the name of a specified property—which must be a reference property—of an association.
strRole
Optional. This is a string that contains a property name. If specified, this parameter indicates that the returned endpoints must participate in an association with the source object in which the source object plays a particular role. The role is defined by the name of a specified property—which must be a reference property—of an association.
bClassesOnly
Optional. This is a Boolean value that indicates whether a list of class names should be returned rather than actual instances of the classes. These are the classes to which the endpoint instances belong. The default value for this parameter is FALSE.
bSchemaOnly
Optional. This is a Boolean value that indicates whether the query applies to schema rather than data. The default value for this parameter is FALSE. It can only be set to TRUE if the strObjectPath parameter specifies the object path of a class. When set to TRUE, the set of returned endpoints represent classes that are suitably associated with the source class in schema.
strRequiredAssocQualifier
Optional. This is a string that contains a qualifier name. This parameter, if specified, indicates that the returned endpoints must be associated with the source object through an association class that includes the specified qualifier.
strRequiredQualifier
Optional. This is a string that contains a qualifier name. This parameter, if specified, indicates that the returned endpoints must include the specified qualifier.
iFlags
Optional. This is an integer specifying additional flags to the operation. The default for this parameter is wbemFlagBidirectional, see the descriptions below for more information.
Value Meaning
wbemFlagSendStatus
0x80 		This flag causes asynchronous calls to send status updates to the OnProgress event handler for your object sink.
wbemFlagDontSendStatus
0x0 		This flag prevents asynchronous calls from sending status updates to the OnProgress event handler for your object sink

objWbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.
objWbemAsyncContext
Optional. This is an object of type SWbemNamedValueSet that returns to the object sink to identify the source of the original asynchronous call. Use this parameter if you are making multiple asynchronous calls using the same object sink. To use this parameter, create an SWbemNamedValueSet object and use the SWbemNamedValueSet.Add method to add a value that identifies the asynchronous call you are making. This SWbemNamedValueSet object will be returned to the object sink and the source of the call can be extracted using the SWbemNamedValueSet.item method. For more information, see Making an Asynchronous Call Using the Scripting API.

Return Values

None. If the call is successful, an SWbemObjectSet object will be returned to the object sink.

Error Codes

The AssociatorsOfAsync method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user does not have permission to view one or more of the classes returned by the call.
wbemErrFailed 0x80041001 | There is an unspecified error.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.
wbemErrNotFound 0x80041002 | The requested item was not found.

Remarks

This method will return a collection that has zero elements if there are no classes or instances associated with the source object.

For information about the associated WQL query "Associators Of", source instances and endpoints see Data Queries.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemServices.ReferencesTo, SWbemServices.ReferencesToAsync, SWbemObject.References_, SWbemObject.ReferencesAsync_, SWbemObject.Associators_, SWbemObject.AssociatorsAsync_


SWbemServices.Delete

The Delete method of the SWbemServices object deletes the class or instance specified in the object path. You can only delete objects in the current namespace.

If a dynamic provider supplied the class or instance, it is sometimes not possible to delete this object unless the provider supports class or instance deletion.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemServices.Delete(
strObjectPath,
[iFlags=0],
[objwbemNamedValueSet=null]
)

Parameters

strObjectPath
Required. This is a string containing the object path to the object that you want to delete. Object paths can be constructed by hand, or built using the SWbemObjectPath interface, or from the Path_ property of an instance of SWbemObject.
iFlags
Reserved. It must be zero.
objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.

Return Values

None.

Error Codes

The Delete method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current context does not have adequate security rights to delete the object.
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrInvalidClass 0x80041010 | The specified class does not exist.
wbemErrInvalidOperation 0x80041016 | The object cannot be deleted.
wbemErrNotFound 0x80041002 | The object did not exist.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Examples

SWbemServices.Delete Examples

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemObjectPath


SWbemServices.DeleteAsync

The DeleteAsync method of the SWbemServices object asynchronously deletes the class or instance specified in the object path. This call will return immediately and the status will be returned to the caller through the supplied object sink. You can only delete objects in the current namespace.

If a dynamic provider supplied the class or instance, it is sometimes not possible to delete this object unless the provider supports class or instance deletion.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objWbemServices.DeleteAsync(
[ObjWbemSink = null],
strObjectPath,
[iFlags=0],
[objWbemNamedValueSet=null]
[objWbemAsyncContext=null]
)

Parameters

ObjWbemSink
Optional. This is the object sink that will receive the results of the deletion.
strObjectPath
Required. This is a string containing the object path to the object that you want to delete. Object paths can be constructed by hand, or built using the SWbemObjectPath interface, or from the Path_ property of an instance of SWbemObject.
iFlags
Optional. This parameter determines if status updates will be returned or not. This parameter can accept the following values.
Value Meaning
wbemFlagSendStatus
0x80 		This flag causes asynchronous calls to send status updates to the OnProgress event handler for your object sink.
wbemFlagDontSendStatus
0x0 		This flag prevents asynchronous calls from sending status updates to the OnProgress event handler for your object sink

objWbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.
objWbemAsyncContext
Optional. This is an object of type SWbemNamedValueSet that returns to the object sink to identify the source of the original asynchronous call. Use this parameter if you are making multiple asynchronous calls using the same object sink. To use this parameter, create an SWbemNamedValueSet object and use the SWbemNamedValueSet.Add method to add a value that identifies the asynchronous call you are making. This SWbemNamedValueSet object will be returned to the object sink and the source of the call can be extracted using the SWbemNamedValueSet.item method. For more information, see Making an Asynchronous Call Using the Scripting API .

Return Values

None. If the call is successful, the object sink will receive notification of the deletion.

Error Codes

The DeleteAsync method can return the error codes listed in the following table.

Error | Meaning
wbemErrFailed 0x80041001 | There is an unspecified error.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.
wbemErrTransportFailure 0x80041015 | A networking error occurred, preventing normal operation.
wbemErrAccessDenied 0x80041003 | The current or specified user name and password were not valid or authorized to make the connection.
wbemErrNotFound 0x80041002 | The requested item was not found.

Examples

SWbemServices.DeleteAsync Examples

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemObjectPath


SWbemServices.ExecMethod

The ExecMethod method of the SWbemServices object executes a method exported by a method provider. This method can be used as an alternate way to execute a method in cases where it is not possible to execute a method directly. For example, you would need to use it with a scripting language such as Microsoft JScript that does not support output parameters, if your method has out parameters. Otherwise, the recommended means of invoking a method is to use direct method invocation. Direct method invocation is executing a method by using object.method syntax. For example, to execute a method called "get" on an object called "myobject" you could use the syntax: myobject.get. For more information on direct method invocation, see Direct Access.

This method will block while the method that is forwarded to the appropriate provider executes. The information and status are then returned.

WMI does not implement the methods directly. The method providers export the methods.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objOutParams = objwbemServices.ExecMethod(
strObjectPath,
strMethodName,
[objwbemInParams=null],
[iFlags=0],
[objwbemNamedValueSet=null]
)

Parameters

strObjectPath
Required. This is a string containing the object path of the object for which the method is executed. Object paths can be constructed by hand, or built using the SWbemObjectPath object or from the Path_ property of an instance of SWbemObject.
strMethodName
Required. It is the name of the method for the object.
objwbemInParams
Optional. This is an SWbemObject object that contains the input parameters for the method being executed. The following procedure describes the four steps in constructing this parameter:

To construct the objwbemInParams parameter

  1. Call SWbemObject.Methods_.Item("MethodName") to get an SWbemMethod object that contains the properties that describe the method, where "MethodName" is the name of the method to retrieve.
  2. Use the SWbemMethod.InParameters property of the SWbemMethod object to get an InParameters object.
  3. Call SpawnInstance_ on the InParameters object to create an instance.
  4. Set the properties of the instance to whatever values are appropriate. For example, If you want to set an input parameter named myinputparam to the value "whatever" in an instance of InParameters called "INST", the code would look like this: INST.Properties_.Add("myinputparam").Value = "Whatever"

    By default, this parameter is undefined.

iFlags
Optional. This parameter is reserved, and must be zero.
objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.

Return Values

An object of type SWbemObject returns if this call is successful. The returned object contains the out parameters and return value for the method being executed.

Error Codes

The ExecMethod method can return the error codes listed in the following table.

Error | Meaning
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrInvalidClass 0x80041010 | The specified class was invalid.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.
wbemErrInvalidMethod 0x8004102E | The requested method was not available.
wbemErrAccessDenied 0x80041003 | The current user was not authorized to execute the method.

Examples

SWbemServices.ExecMethod Examples

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemObject.ExecMethod_


SWbemServices.ExecMethodAsync

The ExecMethodAsync method of the SWbemServices object asynchronously executes a method exported by a method provider. The call immediately returns to the client while the inbound parameters are forwarded to the appropriate provider where the method executes. Information and status are returned to the caller through the supplied object sink.

This method can be used as an alternate way to execute a method in cases where it is not possible to execute a method directly. For example, you would need to use it with a scripting language such as Microsoft JScript that does not support output parameters, if your method has out parameters. Otherwise, the recommended means of invoking a method is to use direct method invocation. Direct method invocation is executing a method by using object.method syntax. For example, to execute a method called "get" on an object called "myobject" you could use the syntax: myobject.get. For more information on direct method invocation, see Direct Access.

WMI does not implement the methods directly. The method providers export the methods.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objWbemServices.ExecMethodAsync(
objWbemSink,
strObjectPath,
strMethodName,
[objWbemInParams=null],
[iFlags=0],
[objWbemNamedValueSet=null],
[objWbemAsyncContext=null]
)

Parameters

objWbemSink
Required. This is the object sink that receives the result of the method call. The outbound parameters are sent to the SWbemSink.OnObjectReady event of the supplied object sink. The result of the call mechanism itself will be sent to the SWbemSink.OnCompleted event of the supplied object sink. Notice that SWbemSink.OnCompleted does not receive the return code of the CIM method. However, it receives the return code of the actual call-return mechanism, and is only useful for verifying that the call occurred or that it failed for mechanical reasons. The result code returned from the CIM method is returned in the outbound parameter object supplied to SWbemSink.OnObjectReady. If any error code returns, then the supplied IWbemObjectSink object will not be used. If the call is successful, then the user's IWbemObjectSink implementation will be called to indicate the result of the operation.
strObjectPath
Required. This is a string containing the object path of the object for which the method is executed. Object paths can be constructed by hand, or built using the SWbemObjectPath object or from the Path_ property of an instance of SWbemObject.
strMethodName
Required. It is the name of the method that will be executed.
objWbemInParams
Optional. This is an SWbemObject object that contains the input parameters for the method being executed. The following procedure describes the four steps in constructing this parameter:
To construct the objwbemInParams parameter
  1. Call SWbemObject.Methods_.Item("MethodName") to get an SWbemMethod object that contains the properties that describe the method, where "MethodName" is the name of the method to retrieve.
  2. Use the SWbemMethod.InParameters property of the SWbemMethod object to get an InParameters object.
  3. Call SpawnInstance_ on the InParameters object to create an instance.
  4. Set the properties of the instance to whatever values are appropriate. For example, If you want to set an input parameter named myinputparam to the value "whatever" in an instance of InParameters called "INST", the code would look like this: INST.Properties_.Add("myinputparam").Value = "Whatever"

    By default, this parameter is undefined.

iFlags
Optional. This is an integer that determines the behavior of the call. This parameter can accept the following values.
Value Meaning
wbemFlagSendStatus
0x80 		This flag causes asynchronous calls to send status updates to the OnProgress event handler for your object sink.
wbemFlagDontSendStatus
0x0 		This flag prevents asynchronous calls from sending status updates to the OnProgress event handler for your object sink

objWbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.
objWbemAsyncContext
Optional. This is an object of type SWbemNamedValueSet that returns to the object sink to identify the source of the original asynchronous call. Use this parameter if you are making multiple asynchronous calls using the same object sink. To use this parameter, create an SWbemNamedValueSet object and use the SWbemNamedValueSet.Add method to add a value that identifies the asynchronous call you are making. This SWbemNamedValueSet object will be returned to the object sink and the source of the call can be extracted using the SWbemNamedValueSet.item method. For more information, see Making an Asynchronous Call Using the Scripting API

Return Values

None. If this call is successful, the object sink will return an object of type SWbemObject. The returned object contains the out parameters and return value for the method being executed.

Error Codes

The ExecMethod method can return the error codes listed in the following table.

Error | Meaning
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrInvalidClass 0x80041010 | The specified class was invalid.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.
wbemErrInvalidMethod 0x8004102E | The requested method was not available.
wbemErrAccessDenied 0x80041003 | The current user was not authorized to execute the method.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemServices.ExecMethod, SWbemObject.ExecMethodAsync_, SWbemObject.ExecMethod_


SWbemServices.ExecNotificationQuery

The ExecNotificationQuery method of the SWbemServices object executes a query to receive events. The call returns immediately. The user can poll the returned enumerator for events as they arrive.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemEventsource = objwbemServices.ExecNotificationQuery(
strQuery,
[strQueryLanguage="WQL"],
[iFlags=(wbemFlagReturnImmediately)],
[objwbemNamedValueSet=null]
)

Parameters

strQuery
Required. This is a string containing the text of the event-related query. This cannot be blank.
strQueryLanguage
Optional. This parameter is a string containing the query laguage to be used. If it is supplied, it must be "WQL".
iFlags
Optional. This is an integer that determines the behavior of the query. The default value is wbemFlagReturnImmediately. This parameter can accept the following values.
Value Meaning
wbemFlagReturnImmediately
0x10 		This flag causes the call to return immediately.
wbemFlagReturnWhenComplete
0x0 		This flag causes this call to block until the query has completed.

objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.

Return Values

If no error occurs, this method returns an object that is of type SWbemEventSource. You can call the SWbemEventSource.NextEvent method to retrieve events as they arrive.

Error Codes

The ExecNotificationQuery method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user is not authorized to view the result set.
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrInvalidQuery 0x80041017 | The query was not valid syntactically.
wbemErrInvalidQueryType 0x80041018 | The requested query language is not supported.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Examples

SWbemServices.ExecNotificationQuery Examples

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemServices.ExecQuery, SWbemEventSource.NextEvent


SWbemServices.ExecNotificationQueryAsync

The ExecNotificationQueryAsync method of the SWbemServices object executes a query asynchronously to receive events. This call will return immediately and status and events will be returned to the caller through the supplied object sink.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemServices.ExecNotificationQueryAsync(
objWbemSink,
strQuery,
[strQueryLanguage="WQL"],
[iFlags=0],
[objwbemNamedValueSet=null],
[objWbemAsyncContext=null]
)

Parameters

objWbemSink
Required. This is the object sink that will receive notification of events asynchronously.
strQuery
Required. This is a string containing the text of the event-related query. This cannot be blank.
strQueryLanguage
Optional. This parameter is a string containing the query laguage to be used. If it is supplied, it must be "WQL".
iFlags
Optional. This is an integer that determines the behavior of the query. This parameter can be set to the following values.
Value Meaning
wbemFlagSendStatus
0x80 		This flag causes asynchronous calls to send status updates to the OnProgress event handler for your object sink.
wbemFlagDontSendStatus
0x0 		This flag prevents asynchronous calls from sending status updates to the OnProgress event handler for your object sink

objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.
objWbemAsyncContext
Optional. This is an object of type SWbemNamedValueSet that returns to the object sink to identify the source of the original asynchronous call. Use this parameter if you are making multiple asynchronous calls using the same object sink. To use this parameter, create an SWbemNamedValueSet object and use the SWbemNamedValueSet.Add method to add a value that identifies the asynchronous call you are making. This SWbemNamedValueSet object will be returned to the object sink and the source of the call can be extracted using the SWbemNamedValueSet.item method. For more information, see Making an Asynchronous Call Using the Scripting API

Return Values

None. If successful, the object sink will receive objects of type SWbemObject as events become available.

Error Codes

The ExecNotificationQueryAsync method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user is not authorized to view the result set.
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrInvalidQuery 0x80041017 | The query was not valid syntactically.
wbemErrInvalidQueryType 0x80041018 | The requested query language is not supported.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Examples

SWbemServices.ExecNotificationQueryAsync Examples

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemServices.ExecQueryAsync, SWbemServices.ExecQuery


SWbemServices.ExecQuery

The ExecQuery method of the SWbemServices object executes a query to retrieve objects. These objects are available through the returned SWbemObjectSet collection.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objWbemObjectSet = objwbemServices.ExecQuery(
strQuery,
[strQueryLanguage="WQL"],
[iFlags=wbemFlagReturnImmediately],
[objwbemNamedValueSet=null]
)

Parameters

strQuery
Required. This is a string containing the text of the query. This parameter cannot be blank.
strQueryLanguage
Optional. This parameter is a string containing the query laguage to be used. If it is supplied, it must be "WQL".
iFlags
Optional. This is an integer that determines the behavior of the query and determines if this call will wait for all results or return immediately. The default value for this parameter is wbemFlagReturnImmediately. This parameter can accept the following values.
Value Meaning
wbemFlagForwardOnly
0x20 		This flag causes a forward-only enumerator to be returned. Forward-only enumerators are generally much faster and use less memory than conventional enumerators, but they do not allow calls to Clone or Reset.
wbemFlagBidirectional
0x0 		This flag causes WMI to retain pointers to objects of the enumeration until the client releases the enumerator.
wbemFlagReturnImmediately
0x10 		This flag causes the call to return immediately.
wbemFlagReturnWhenComplete
0x0 		This flag causes this call to block until the query has completed.
wbemQueryFlagPrototype
0x2 		This flag is used for prototyping. It stops the query from happening and instead returns an object that looks like a typical result object.
wbemFlagUseAmendedQualifiers
0x20000 		This flag causes WMI to return class amendment data along with the base class definition. For more information about amended qualifiers see WMI Localization.

objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.

Return Values

If no error occurs, this method returns an object that is of type SWbemObjectSet. This is an object collection that contains the result set of the query. The caller can examine the collection using the implementation of collections for the programming language you are using. For more information on collections, see Collections.

Error Codes

The ExecQuery method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user does not have permission to view the result set.
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrInvalidQuery 0x80041017 | The query was not syntactically valid.
wbemErrInvalidQueryType 0x80041018 | The requested query language is not supported.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Remarks

It is not an error for the query to return an empty result set. This method will return key properties regardless of whether or not the key property is requested in the strQuery argument. If an error occurs when executing this method and you use the wbemFlagReturnImmediately flag the Err object is not set until you attempt to access the returned object set. However, if you use the wbemFlagReturnWhenComplete flag, the Err object is set when the ExecQuery method is called.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemServices.Get


SWbemServices.ExecQueryAsync

The ExecQueryAsync method of the SWbemServices object asynchronously executes a query to retrieve objects. These objects are available as an SWbemObjectSet collection that returns to the object sink.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objWbemObjectSet = objwbemServices.ExecQueryAsync(
objWbemSink,
strQuery,
[strQueryLanguage="WQL"],
[iFlags],
[objwbemNamedValueSet=null],
[objWbemAsyncContext=null]
)

Parameters

objWbemSink
Optional. This is the object sink that will execute the query asynchronously.
strQuery
Required. This is a string containing the text of the query. This parameter cannot be blank.
strQueryLanguage
Optional. This parameter is a string containing the query laguage to be used. If it is supplied, it must be "WQL".
iFlags
Optional. This is an integer that determines the behavior of the query. This parameter can accept the following values.
Value Meaning
wbemFlagSendStatus
0x80 		This flag causes asynchronous calls to send status updates to the OnProgress event handler for your object sink.
wbemFlagDontSendStatus
0x0 		This flag prevents asynchronous calls from sending status updates to the OnProgress event handler for your object sink
wbemQueryFlagPrototype
0x2 		This flag is used for prototyping. It stops the query from happening and instead returns an object that looks like a typical result object.
wbemFlagUseAmendedQualifiers
0x20000 		This flag causes WMI to return class amendment data along with the base class definition. For more information about amended qualifiers see WMI Localization.

objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.
objWbemAsyncContext
Optional. This is an object of type SWbemNamedValueSet that returns to the object sink to identify the source of the original asynchronous call. Use this parameter if you are making multiple asynchronous calls using the same object sink. To use this parameter, create an SWbemNamedValueSet object and use the SWbemNamedValueSet.Add method to add a value that identifies the asynchronous call you are making. This SWbemNamedValueSet object will be returned to the object sink and the source of the call can be extracted using the SWbemNamedValueSet.item method. For more information, see

Return Values

If successful this method returns an object sink. If no error occurs, the object sink will receive an object that is of type SWbemObjectSet. This is an object collection that contains the result set of the query. The caller can examine the collection using the implementation of collections for the programming language you are using. For more information on collections, see Collections.

Error Codes

The ExecQueryAsync method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user does not have permission to view the result set.
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrInvalidQuery 0x80041017 | The query was not syntactically valid.
wbemErrInvalidQueryType 0x80041018 | The requested query language is not supported.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Remarks

This method may return an empty result set if there are no objects that match the criteria in the query. This method will return key properties regardless of whether or not the key property is requested in the strQuery argument.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemServices.Get, Making an Asynchronous Call Using the Scripting API


SWbemServices.Get

The Get method of the SWbemServices object retrieves an object, either a class definition or an instance, based on the object's path. This method only retrieves objects from the namespace associated with the current SWbemServices object.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objObject = objwbemServices.Get(
[strObjectPath=""],
[iFlags=0],
[objwbemNamedValueSet=null]
)

Parameters

strObjectPath
Optional. This parameter is the object path of the object you want to retrieve. If this is empty, an empty object returns that can become a new class. Object paths can be constructed by hand, or built using the SWbemObjectPath interface or from the Path_ property of an instance of SWbemObject. This parameter is optional.
iFlags
Optional. This is an integer that determines the behavior of the query. This parameter can accept the following values.
Value Meaning
wbemFlagUseAmendedQualifiers
0x20000 		This flag causes WMI to return class amendment data along with the base class definition. For more information about amended qualifiers see WMI Localization.

objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.

Return Values

If successful, this method returns an SWbemObject representing the requested object.

Error Codes

The Get method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user does not have permission to access the object.
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrInvalidObjectPath 0xH8004103A | The specified path was invalid.
wbemErrNotFound 0x80041002 | The requested object could not be found.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemObject


SWbemServices.GetAsync

The GetAsync method of the SWbemServices object asynchronously retrieves an object, either a class definition or an instance, based on the object's path. This call will return immediately and status and object will be returned to the caller through the supplied object sink.

This method only retrieves objects from the namespace associated with the current SWbemServices object.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemServices.GetAsync(
objWbemSink = null,
[strObjectPath=""],
[iFlags=0],
[objwbemNamedValueSet=null]
[objWbemAsyncContext=null]
)

Parameters

objWbemSink
Required. This is the object sink that will get objects asynchronously.
strObjectPath
Optional. The object path of the object you want to retrieve. If this is empty, an empty object returns that can become a new class. Object paths can be constructed by hand, or built using the SWbemObjectPath interface or from the Path_ property of an instance of SWbemObject. This parameter is optional.
iFlags
Optional. This is an integer that determines the behavior of the call. This parameter can accept the following values.
Value Meaning
wbemFlagSendStatus
0x80 		This flag causes asynchronous calls to send status updates to the OnProgress event handler for your object sink.
wbemFlagDontSendStatus
0x0 		This flag prevents asynchronous calls from sending status updates to the OnProgress event handler for your object sink
wbemFlagUseAmendedQualifiers
0x20000 		This flag causes WMI to return class amendment data along with the base class definition. For more information about amended qualifiers see WMI Localization.

objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.
objWbemAsyncContext
Optional. This is an object of type SWbemNamedValueSet that returns to the object sink to identify the source of the original asynchronous call. Use this parameter if you are making multiple asynchronous calls using the same object sink. To use this parameter, create an SWbemNamedValueSet object and use the SWbemNamedValueSet.Add method to add a value that identifies the asynchronous call you are making. This SWbemNamedValueSet object will be returned to the object sink and the source of the call can be extracted using the SWbemNamedValueSet.item method. For more information, see Making an Asynchronous Call Using the Scripting API.

Return Values

None. If this call is successful, the object sink will receive an object of type SWbemObject representing the requested object.

Error Codes

The Get method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user does not have permission to access the object.
wbemErrFailed 0x80041001 | This is an unspecified error.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrInvalidObjectPath 0xH8004103A | The specified path was invalid.
wbemErrNotFound 0x80041002 | The requested object could not be found.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemObject


SWbemServices.InstancesOf

The InstancesOf method of the SWbemServices object creates an enumerator that returns the instances of a specified class according to user-specified selection criteria. This method implements a simple query. More complex queries may require the use of SWbemServices.ExecQuery.

Note This method only works for class objects. It is not an error for the returned enumerator to have zero elements.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objWbemObjectSet = objwbemServices.InstancesOf(
strClass,
[iFlags=wbemFlagReturnImmediately],
[objwbemNamedValueSet=null]
)

Parameters

strClass
Required. This is a string containing the name of the class for which instances are desired. This parameter cannot be blank.
iFlags
Optional. This parameter determines how deep the call will enumerate and if this call will return immediately or wait until the call is complete before returning. The default value for this parameter is wbemFlagReturnImmediately. This parameter can accept the following values.
Value Meaning
wbemFlagForwardOnly
0x20 		This flag causes a forward-only enumerator to be returned. Forward-only enumerators are generally much faster and use less memory than conventional enumerators, but they do not allow calls to Clone or Reset.
wbemFlagBidirectional
0x0 		This flag causes WMI to retain pointers to objects of the enumeration until the client releases the enumerator.
wbemFlagReturnImmediately
0x10 		This is the default value for this parameter. This flag causes the call to return immediately.
wbemFlagReturnWhenComplete
0x0 		This flag causes this call to block until the query has completed.
wbemQueryFlagShallow
0x1 		This flag forces the enumeration to include only immediate subclasses of the specified superclass.
wbemQueryFlagDeep
0x0 		This is the default for this parameter. This value forces the enumeration to include all of class in the hierarchy.

objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.

Return Values

If successful, an object of type SWbemObjectSet returns.

Error Codes

The InstancesOf method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user does not have permission to view instances of the specified class.
wbemErrFailed 0x80041001 | An unspecified error occurred.
wbemErrInvalidClass 0x80041010 | The specified class is invalid.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemObjectSet


SWbemServices.InstancesOfAsync

The InstancesOfAsync method of the SWbemServices object creates an enumerator that returns the instances of a specified class according to user-specified selection criteria. This call will return immediately and the results and status will be returned to the caller through the supplied object sink. This method implements a simple query. More complex queries may require the use of SWbemServices.ExecQuery.

Note This method only works for class objects. It is not an error for the returned enumerator to have zero elements.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemServices.InstancesOfAsync(
ObjWbemSink,
strClass,
[iFlags],
[objwbemNamedValueSet=null],
[objWbemAsyncContext=null]
)

Parameters

ObjWbemSink
This is the object sink that will receive the instances asynchronously.
strClass
Required. This is a string containing the name of the class for which instances are desired. This parameter cannot be blank.
iFlags
Optional. This parameter determines how deep the call will enumerate and if this call will return immediately or wait until the call is complete before returning. This parameter can accept the following values.
Value Meaning
wbemQueryFlagShallow
0x1 		This flag forces the enumeration to include only immediate subclasses of the specified superclass.
wbemQueryFlagDeep
0x0 		This is the default for this parameter. This value forces the enumeration to include all of class in the hierarchy.
wbemFlagSendStatus
0x80 		This flag causes asynchronous calls to send status updates to the OnProgress event handler for your object sink.
wbemFlagDontSendStatus
0x0 		This flag prevents asynchronous calls from sending status updates to the OnProgress event handler for your object sink

objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.
objWbemAsyncContext
Optional. This is an object of type SWbemNamedValueSet that returns to the object sink to identify the source of the original asynchronous call. Use this parameter if you are making multiple asynchronous calls using the same object sink. To use this parameter, create an SWbemNamedValueSet object and use the SWbemNamedValueSet.Add method to add a value that identifies the asynchronous call you are making. This SWbemNamedValueSet object will be returned to the object sink and the source of the call can be extracted using the SWbemNamedValueSet.item method.

Return Values

None. If successful, the object sink will receive an object of type SWbemObjectSet that represents the instances.

Error Codes

The InstancesOf method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user does not have permission to view instances of the specified class.
wbemErrFailed 0x80041001 | An unspecified error occurred.
wbemErrInvalidClass 0x80041010 | The specified class is invalid.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Examples

SWbemServices.InstancesOfAsync Examples

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemObjectSet, Making an Asynchronous Call Using the Scripting API


SWbemServices.ReferencesTo

The ReferencesTo method of the SWbemServices object returns a collection of all association classes or instances that refer to a particular source class or instance.

This method performs the same function that the WQL "References Of" query performs.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objWbemObjectSet = objwbemServices.ReferencesTo(
strObjectPath,
[strResultClass=""],
[strRole=""],
[bClassesOnly=FALSE],
[bSchemaOnly=FALSE],
[strRequiredQualifier=""],
[iFlags=wbemFlagReturnImmediately],
[objwbemNamedValueSet=null]
)

Parameters

strObjectPath
Required. This is a string containing the object path of the source for this method.
strResultClass
Optional. This is a string that contains a class name. This parameter, if specified, indicates that the returned association objects must belong to or be derived from the class specified in this parameter.
strRole
Optional. This is a string that contains a property name. If specified, this parameter indicates that the returned association objects must be limited to those in which the source object plays a particular role. The role is defined by the name of a specified property—which must be a reference property—of an association.
bClassesOnly
Optional. This is a Boolean value that indicates whether a list of class names should be returned rather than actual instances of the classes. These are the classes to which the association objects belong. The default value for this parameter is FALSE.
bSchemaOnly
Optional. This is a Boolean value that indicates whether the query applies to schema rather than data. The default value for this parameter is FALSE. It can only be set to TRUE if the strObjectPath parameter specifies the object path of a class. When set to TRUE, the set of returned endpoints represent classes that are suitably associated with the source class in schema.
strRequiredQualifier
Optional. This is a string that contains a qualifier name. This parameter, if specified, indicates that the returned association objects must include the specified qualifier.
iFlags
Optional. This is an integer specifying additional flags to the operation. The default for this parameter is wbemFlagReturnImmediately, which directs the call to return immediately rather than wait until the query has completed. This parameter can accept the following values.
Value Meaning
wbemFlagForwardOnly
0x20 		This flag causes a forward-only enumerator to be returned. Forward-only enumerators are generally much faster and use less memory than conventional enumerators, but they do not allow calls to Clone or Reset.
wbemFlagBidirectional
0x0 		This flag causes WMI to retain pointers to objects of the enumeration until the client releases the enumerator.
wbemFlagReturnImmediately
0x10 		This flag causes the call to return immediately.
wbemFlagReturnWhenComplete
0x0 		This flag causes this call to block until the query has completed.

objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.

Return Values

If the call is successful, an object of type SWbemObjectSet will be returned.

Error Codes

The ReferencesTo method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user does not have permission to view one or more of the classes returned by the call.
wbemErrFailed 0x80041001 | There is an unspecified error.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Remarks

It is not an error for the returned collection to have zero elements.

For information about the associated WQL query "References Of", source instances, and association objects, see Data Queries.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemServices.AssociatorsOf, SWbemObject.References_, SWbemObject.Associators_


SWbemServices.ReferencesToAsync

The ReferencesToAsync method of the SWbemServices object asynchronously returns a collection of all association classes or instances that refer to a particular source class or instance.

This method performs the same function that the WQL "References Of" query performs. This call will return immediately and the results and status will be returned to the caller through the supplied object sink.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemServices.ReferencesToAsync(
ObjWbemSink,
strObjectPath,
[strResultClass=""],
[strRole=""],
[bClassesOnly=FALSE],
[bSchemaOnly=FALSE],
[strRequiredQualifier=""],
[iFlags],
[objwbemNamedValueSet=null],
[objWbemAsyncContext=null]
)

Parameters

ObjWbemSink
Required. This is the object sink that will receive the objects asynchronously.
strObjectPath
Required. This is a string containing the object path of the source for this method.
strResultClass
Optional. This is a string that contains a class name. This parameter, if specified, indicates that the returned association objects must belong to or be derived from the class specified in this parameter.
strRole
Optional. This is a string that contains a property name. If specified, this parameter indicates that the returned association objects must be limited to those in which the source object plays a particular role. The role is defined by the name of a specified property—which must be a reference property—of an association.
bClassesOnly
Optional. This is a Boolean value that indicates whether a list of class names should be returned rather than actual instances of the classes. These are the classes to which the association objects belong. The default value for this parameter is FALSE.
bSchemaOnly
Optional. This is a Boolean value that indicates whether the query applies to schema rather than data. The default value for this parameter is FALSE. It can only be set to TRUE if the strObjectPath parameter specifies the object path of a class. When set to TRUE, the set of returned endpoints represent classes that are suitably associated with the source class in schema.
strRequiredQualifier
Optional. This is a string that contains a qualifier name. This parameter, if specified, indicates that the returned association objects must include the specified qualifier.
iFlags
Optional. This is an integer specifying additional flags to the operation. The default for this parameter is wbemFlagBidirectional. This parameter can accept the following values.
Value Meaning
wbemFlagSendStatus
0x80 		This flag causes asynchronous calls to send status updates to the OnProgress event handler for your object sink.
wbemFlagDontSendStatus
0x0 		This flag prevents asynchronous calls from sending status updates to the OnProgress event handler for your object sink

objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.
objWbemAsyncContext
Optional. This is an object of type SWbemNamedValueSet that returns to the object sink to identify the source of the original asynchronous call. Use this parameter if you are making multiple asynchronous calls using the same object sink. To use this parameter, create an SWbemNamedValueSet object and use the SWbemNamedValueSet.Add method to add a value that identifies the asynchronous call you are making. This SWbemNamedValueSet object will be returned to the object sink and the source of the call can be extracted using the SWbemNamedValueSet.item method. For more information, see Making an Asynchronous Call Using the Scripting API

Return Values

None. If the call is successful, the object sink will receive an object of type SWbemObjectSet representing the association classes or instances.

Error Codes

The ReferencesToAsync method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user does not have permission to view one or more of the classes returned by the call.
wbemErrFailed 0x80041001 | There is an unspecified error.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Remarks

It is not an error for the returned collection to have zero elements.

For information about the associated WQL query "References Of", source instances, and association objects, see Data Queries.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemServices.AssociatorsOf, SWbemObject.References_, SWbemObject.Associators_


SWbemServices.Security_

The Security_ property of the SWbemServices object is used to read or set the security settings for an SWbemServices object. This property is an object of type SWbemSecurity.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemSecurity = objwbemServices.Security_

Examples

SWbemServices.Security_ Examples

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

WMI Scripting Security Issues, Object Creation and Monikers


SWbemServices.SubclassesOf

The SubclassesOf method of the SWbemServices object returns an object of type SWbemObjectSet. This object is a collection of subclasses of a specified class. Items in the returned collection can be obtained by way of standard collection methods. See Collections for information on using collections.

Note This method only works for class objects.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objWbemObjectSet = objwbemServices.SubclassesOf(
[strSuperclass=""],
[iFlags=wbemFlagReturnImmediately+wbemQueryFlagDeep],
[objwbemNamedValueSet=null]
)

Parameters

strSuperclass
Optional. This parameter, if not blank, specifies a superclass name. Only subclasses of this class return in the enumerator. If you leave this parameter blank, and if iFlags is wbemQueryFlagShallow, only the top-level classes (that is, classes that have no parent class or superclass) are returned. If this parameter is blank, and iFlags is wbemQueryFlagDeep, all classes within the namespace are returned.
iFlags
Optional. This determines how deep the enumeration will be. See the flags section below for more details. The default value for this parameter is wbemFlagReturnImmediately and wbemQueryFlagDeep. This parameter can accept the following values.
Value Meaning
wbemQueryFlagShallow
0x1 		It forces the enumeration to include only immediate subclasses of the specified superclass.
wbemQueryFlagDeep
0x0 		This is the default for this parameter. This value forces recursive enumeration into all subclasses derived from the specified superclass. The superclass itself is not returned in the enumeration.
WbemFlagReturnImmediately
0x10 		This flag causes the call to return immediately
wbemFlagReturnWhenComplete
0 		This flag causes this call to block until the call has completed.

objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.

Return Values

If the call is successful, an object of type SWbemObjectSet will be returned.

Error Codes

The SubclassesOf method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user does not have permission to view one or more of the classes returned by the call.
wbemErrFailed 0x80041001 | There is an unspecified error.
wbemErrInvalidClass 0x80041010 | The specified class did not exist.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Remarks

It is not an error for the returned collection to have zero elements.

Examples

SWbemServices.SubclassesOf Examples

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemObjectSet


SWbemServices.SubclassesOfAsync

The SubclassesOfAsync method of the SWbemServices object asynchronously returns a collection of subclasses for a specified class. This call will return immediately and the results and status will be returned to the caller through the supplied object sink. Items in the collection returned to the object sink can be obtained by way of standard collection methods. See Collections for information on using collections.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Note This method only works for class objects.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemServices.SubclassesOfAsync(
ObjWbemSink,
[strSuperclass=""],
[iFlags=wbemQueryFlagDeep],
[objwbemNamedValueSet=null]
[objWbemAsyncContext]
)

Parameters

ObjWbemSink
Required. This is the object sink that will receive the subclasses asynchronously.
strSuperclass
Optional. This parameter, if not blank, specifies a superclass name. Only the classes that are subclasses of this class return in the enumerator. If it is blank, and if iFlags is wbemQueryFlagShallow, only the top-level classes (that is, classes that have no parent class or superclass) are returned. If it is blank, and iFlags is wbemQueryFlagDeep, all classes within the namespace are returned.
iFlags
Optional. This determines how deep the enumeration will be. See the flags section below for more details. The default value for this parameter is wbemQueryFlagDeep. This parameter can accept the following values.
Value Meaning
wbemQueryFlagShallow
0x1 		This flag forces the enumeration to include only immediate subclasses of the specified superclass.
wbemQueryFlagDeep
0x0 		This is the default for this parameter. This value forces recursive enumeration into all subclasses derived from the specified superclass. The superclass itself is not returned in the enumeration.
wbemFlagSendStatus
0x80 		This flag causes asynchronous calls to send status updates to the OnProgress event handler for your object sink.
wbemFlagDontSendStatus
0x0 		This flag prevents asynchronous calls from sending status updates to the OnProgress event handler for your object sink

objwbemNamedValueSet
Optional. Typically, this is undefined. Otherwise, this is an SWbemNamedValueSet object whose elements represent the context information that may be used by the provider that is servicing the request. A provider that supports or requires such information must document the value names that the provider recognizes, the data type of the value, the allowed values, and the semantics.
objWbemAsyncContext
Optional. This is an object of type SWbemNamedValueSet that returns to the object sink to identify the source of the original asynchronous call. Use this parameter if you are making multiple asynchronous calls using the same object sink. To use this parameter, create an SWbemNamedValueSet object and use the SWbemNamedValueSet.Add method to add a value that identifies the asynchronous call you are making. This SWbemNamedValueSet object will be returned to the object sink and the source of the call can be extracted using the SWbemNamedValueSet.item method. For more information, see Making an Asynchronous Call Using the Scripting API .

Return Values

None. If the call is successful, the object sink will receive an object of type SWbemObjectSet that represents the subclasses.

Error Codes

The SubclassesOfAsync method can return the error codes listed in the following table.

Error | Meaning
wbemErrAccessDenied 0x80041003 | The current user does not have permission to view one or more of the classes returned by the call.
wbemErrFailed 0x80041001 | There is an unspecified error.
wbemErrInvalidClass 0x80041010 | The specified class did not exist.
wbemErrInvalidParameter 0x80041008 | An invalid parameter was specified.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.

Remarks

It is not an error for the returned collection to have zero elements if no subclasses are found.

Examples

SWbemServices.SubclassesOfAsync Examples

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

SWbemObjectSet


SWbemSink

SWbemSink is implemented by client applications to receive the results of asynchronous operations and event notifications. To make an asynchronous call you need to create an instance of an SWbemSink object and pass it as the ObjWbemSink parameter. The events in your implementation of SWbemSink are triggered when status or results are returned or the call is complete.

Methods

Method | Description
Cancel | Call this method to cancel all asynchronous operations associated with this sink.

Properties

None.

Events

Event | Description
OnCompleted | This event is triggered when an asynchronous operation is complete.
OnObjectPut | This event is triggered after an asynchronous put operation.
OnObjectReady | This event is triggered when an object provided by an asynchronous call is available.
OnProgress | This event is triggered to provide the status of a asynchronous operation.


SWbemSink.Cancel

The Cancel method of the SWbemSink object cancels all outstanding asynchronous operations associated with this object sink.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemsink.cancel()

Parameters

This method has no parameters.

Return Values

This method has no return values.

Error Codes

The Cancel method can return the error codes listed in the following table.

Error | Meaning
wbemErrFailed 0x80041001 | There is an unspecified error.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.
wbemErrTransportFailure 0x80041015 | A networking error occurred, preventing normal operation.
wbemErrAccessDenied 0x80041003 | The current or specified user name and password were not valid or authorized to make the connection.

Remarks

It is not possible to cancel a single asynchronous call if there are multiple asynchronous calls pending that use this object sink, all the asynchronous calls that use this object sink will be canceled by this method. Asynchronous calls associated with other object sinks will continue unaffected.

Note It is not enough to assign this sink to Nothing to cancel an unwanted asynchronous operation. You must call the Cancel method to make WMI discontinue the operation and free the associated resources. This is particularly important with lengthy asynchronous operations, such as queries, or operations that never complete, such as ExecNotificationQueryAsync.

The following example demonstrates how to cancel an asynchronous call.

objwbemsink.Cancel()
set objwbemsink= Nothing

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

Making an Asynchronous Call Using the Scripting API


SWbemSink.OnCompleted

The OnCompleted event of an SWbemSink object is triggered when an asynchronous call is complete. This event is used to inform the client application of the result of the asynchronous operation or provide error information if the asynchronous call failed.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemsink.OnCompleted(
iHResult,
objWbemErrorObject,
objWbemAsyncContext
)

Parameters

iHResult
This parameter is the hresult of the completed asynchronous method. This is the same as the value returned from equivalent method call form the WMI COM API. You should check this value to determine if the asynchronous call was successful. This parameter will contain the value WBEM_S_NO_ERROR (0) if the asynchronous call was successful, or an error code if the call failed.
objWbemErrorObject
This will contain an object of type SWbemLastError if the asynchronous method failed.
objWbemAsyncContext
This is an object of type SWbemNamedValueSet that was passed to the original asynchronous call. Use this parameter to identify the origin of the asynchronous call that triggered this event if multiple asynchronous calls were made using this object sink.

Return Values

None.

Error Codes

The OnCompleted event can return the error codes listed in the following table.

Error | Meaning
wbemErrFailed 0x80041001 | There is an unspecified error.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.
wbemErrTransportFailure 0x80041015 | A networking error occurred, preventing normal operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

Making an Asynchronous Call Using the Scripting API


SWbemSink.OnObjectPut

The OnObjectPut event of an SWbemSink object is triggered when an asynchronous put operation is complete. This event returns the object path of the instance or class that has been saved.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemsink.OnObjectPut(
objWbemObjectPath,
objWbemAsyncContext
)

Parameters

objWbemObjectPath
This is an object of type SWbemObjectPath, containing the object path of the instance or class that has been successfully committed to WMI.
objWbemAsyncContext
This is an object of type SWbemNamedValueSet that was passed to the original asynchronous call. Use this parameter to identify the origin of the asynchronous call that triggered this event if multiple asynchronous calls were made using this object sink.

Return Values

No return values.

Error Codes

The OnObjectPut event can return the error codes listed in the following table.

Error | Meaning
wbemErrFailed 0x80041001 | There is an unspecified error.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.
wbemErrTransportFailure 0x80041015 | A networking error occurred, preventing normal operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

Making an Asynchronous Call Using the Scripting API


SWbemSink.OnObjectReady

The OnObjectReady event of an SWbemSink object is triggered when an asynchronous operation returns an object. Use this event to process objects from asynchronous calls such as SWbemObject.InstancesAsync_ or SWbemServices.ExecQueryAsync. Asynchronous calls return an enumeration by calling this event repeatedly. It returns a single SWbemObject object each time until the enumeration is complete.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemsink.OnObjectReady (
objWbemObject,
objWbemAsyncContext
)

Parameters

objWbemObject
This is an object of type SWbemObject. This is similar to what would be returned by the synchronous equivalent of the asynchronous call that triggered this event.
objWbemAsyncContext
This is an object of type SWbemNamedValueSet that was passed to the original asynchronous call. Use this parameter to identify the origin of the asynchronous call that triggered this event if multiple asynchronous calls were made using this object sink.

Return Values

No return values.

Error Codes

The OnObjectReady event can return the error codes listed in the following table.

Error | Meaning
wbemErrFailed 0x80041001 | There is an unspecified error.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.
wbemErrTransportFailure 0x80041015 | A networking error occurred, preventing normal operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

Making an Asynchronous Call Using the Scripting API


SWbemSink.OnProgress

The OnProgress event of SWbemSink is triggered when an asynchronous call returns the status of a call is in progress. If the events, instances or classes are produced from a provider that supports status updates you can place code in this event to provide users with feedback on the status of an asynchronous operation. You must set the iFlags parameter of the asynchronous call to wbemFlagSendStatus (0x80) if you wish to receive status updates, otherwise this event will not be triggered.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objwbemsink.OnProgress (
iUpperBound,
iCurrent,
strMessage,
objWbemAsyncContext
)

Parameters

iUpperBound
This is an integer that describes the total number of tasks to complete.
iCurrent
This parameter is the current item being processed.
strMessage
This is a message that describes the status of the current task.
objWbemAsyncContext
This is an object of type SWbemNamedValueSet that was passed to the original asynchronous call. Use this parameter to identify the origin of the asynchronous call that triggered this event if multiple asynchronous calls were made using this object sink.

Return Values

No return values.

Error Codes

The OnProgress event can return the error codes listed in the following table.

Error | Meaning
wbemErrFailed 0x80041001 | There is an unspecified error.
wbemErrOutOfMemory 0x80041006 | There was not enough memory to complete the operation.
wbemErrTransportFailure 0x80041015 | A networking error occurred, preventing normal operation.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Import Library: Use wbemdisp.tlb.

See Also

Making an Asynchronous Call Using the Scripting API

The OnProgress event is triggered when an asynchronous call returns the status of a call is in progress. If the events, instances, or classes are produced from a provider that supports status updates, you can place code in this event to give users feedback on the status of an asynchronous operation.

The OnComplete event is triggered when an asynchronous call is finished. Place code in this event to finish an asynchronous call or to notify the user that the call is done.

The OnPut event is triggered by asynchronous methods that write changes to the CIM repository such as SWbemObject.PutAsync_. This event receives an object of type SWbemObjectPath that is the path of the new object that has been committed to the CIM repository successfully.

The OnComplete event is triggered when an asynchronous call is finished. Place code in this event to finish processing an asynchronous call or to notify the user that the call is done.


WMI Scripting API Constants

The following tables list Windows Management Instrumentation (WMI) constants. There are three types of constants listed here.

Some constants are used as flags to change the way that WMI scripting API calls will behave. For example, the constant wbemChangeFlagUpdateOnly directs put operations to update only existing classes or instances. There are five groups of constants you can use as flags. They are as follows.

WbemChangeFlagEnum
WbemFlagEnum
WbemQueryFlagEnum
WbemTextFlagEnum
WbemComparisonFlagEnum

You can combine flags to affect more than one aspect of the API call, but some of these flags are mutually exclusive. For example, it makes sense to specify wbemFlagReturnImmediately and wbemFlagForwardOnly as flags to a SwbemServices.ExecQuery call. However, it would make no sense to specify both wbemFlagReturnImmediately and wbemFlagReturnWhenComplete in the same API call. Some of these flags are in groups of three or more such as wbemChangeFlagCreateOrUpdate, wbemChangeFlagUpdateOnly, and wbemChangeFlagCreateOnly. Combining flags such as these may cause unpredictable results.

Other constants define common values that you may use when using the scripting API such as the WMI constant wbemTimeoutInfinite in the group WbemTimeout that determines how long a call will wait for results before returning. Other constants are WbemCimtypeEnum, which is used to specify a CIMtype, and WbemImpersonationLevelEnum, WbemPrivilegeEnum, WbemAuthenticationLevelEnum that are used to set security settings.

Finally, there are constants that are defined in WbemErrorEnum. These constants define the error codes that may be returned by calls to the scripting API. For example, if you make a scripting API call that requires an object path and the one you provide is not valid, the error value defined for wbemErrInvalidObjectPath (0x8004103A) may be returned. If you check for these error values, your applications may be able recover from or handle errors.


WbemChangeFlagEnum

WbemChangeFlagEnum defines the semantics of putting a Class or Instance. These flags are used by SWbemObject.Put_ and SWbemObject.PutAsync_.

Constant | Value (Dec) | Description
wbemChangeFlagCreateOrUpdate | 0 | This flag causes the class or instance to be created if it does not exist or overwritten if it exists already.
wbemChangeFlagUpdateOnly | 1 | This flag causes the call to update. The class or instance must exist for the call to be successful.
wbemChangeFlagCreateOnly | 2 | This flag is used for creation only. The call will fail if the class or instance already exists.
wbemChangeFlagUpdateCompatible | 0 | This flag allows a class to be updated if there are no derived classes and there are on instances for that class. It also allows updates in all cases if the change is just to non-important qualifiers (for example the description qualifier). If the class has instances the update will fail. This flag is used for compatibility with previous versions of WMI.
wbemChangeFlagUpdateSafeMode | 32 | This flag allows updates of classes even if there are child classes as long as the change does not cause any conflicts with child classes. An example of an update in this flag would allow would be to add a new property to the base class that was not previously mentioned in any of the child classes. If the class has instances the update will fail.
wbemChangeFlagUpdateForceMode | 64 | This flag forces updates of classes when conflicting child classes exist. An example of an update this flag will force would be if a class qualifier was defined in a child class, and the base class tries to add the same qualifier and in conflict with the existing one. In force mode this conflict would be resolved by deleting the qualifier in the child class. If the class has instances the update will fail.


WbemFlagEnum

These flags are used by SWbemServices.ExecQuery, SWbemServices.ExecQueryAsync, SWbemServices.SubclassesOf, SWbemServices.InstancesOf.

Constant | Value (Dec) | Description
wbemFlagReturnImmediately | 16 | This flag causes the call to return immediately.
wbemFlagReturnWhenComplete | 0 | This flag causes this call to block until the call has completed.
wbemFlagBidirectional | 0 | This flag causes WMI to retain pointers to objects of the enumeration until the client releases the enumerator.
wbemFlagForwardOnly | 32 | This flag causes a forward-only enumerator to be returned. Forward-only enumerators are generally much faster and use less memory than conventional enumerators, but they do not allow calls to Clone or Reset.
wbemFlagNoErrorObject | 64 | This flag causes asynchronous calls to not return an error object in the event of an error.
wbemFlagReturnErrorObject | 0 | This flag causes asynchronous calls to return an error object in the event of an error.
wbemFlagSendStatus | 128 | This flag causes asynchronous calls to send status updates to the OnProgress event handler for your object sink.
wbemFlagDontSendStatus | 0 | This flag prevents asynchronous calls from sending status updates to the OnProgress event handler for your object sink.
wbemFlagUseAmendedQualifiers | 131072 | This flag causes WMI to return class amendment data along with the base class definition. For more information about amended qualifiers see WMI Localization.


WbemQueryFlagEnum

WbemQueryFlagEnum defines the depth of enumeration or query. These flags are used by SWbemServices.ExecQuery, SWbemServices.SubclassesOf, and SWbemServices.InstancesOf, SWbemObject.Subclasses_, SWbemObject.Instances_.

Constant | Value (Dec) | Description
wbemQueryFlagDeep | 0 | This value forces recursive enumeration into all subclasses derived from the specified superclass. The superclass itself is not returned in the enumeration.
wbemQueryFlagShallow | 1 | This flag forces the enumeration to include only immediate subclasses of the specified superclass.
wbemQueryFlagPrototype | 2 | This flag is used for prototyping. It stops the query from happening and instead returns an object that look like a typical result object.


WbemTextFlagEnum

WbemTextFlagEnum defines the content of generated object text. These flags are used by SWbemObject.GetObjectText_.

Constant | Value (Dec) | Description
wbemTextFlagNoFlavors | 1 | Excludes qualifier flavors from the object text.


WbemComparisonFlagEnum

WbemComparisonFlagEnum defines the settings for object comparison. These flags are used by SWbemObject.CompareTo_.

Constant | Value (Dec) | Description
wbemComparisonFlagIncludeAll | 0 | Use this flag to compare all properties, qualifiers, and flavors.
wbemComparisonFlagIgnoreQualifiers | 1 | All qualifiers (including "key" and "dynamic") should be ignored in comparison.
wbemComparisonFlagIgnoreObjectSource | 2 | The source of the objects, namely the server and the namespace they came from, are ignored in comparison to other objects.
wbemComparisonFlagIgnoreDefaultValues | 4 | Default values of properties should be ignored. This flag is only meaningful when comparing classes.
wbemComparisonFlagIgnoreClass | 8 | This flag instructs the system to assume that the objects being compared are instances of the same class. Consequently, this flag compares instance-related information only. Use this flag to optimize performance. If the objects are not of the same class, the results will be undefined.
wbemComparisonFlagIgnoreCase | 16 | Compares string values in a case-insensitive manner. This applies both to strings and to qualifier values. Property and qualifier names are always compared in a case-insensitive manner whether this flag is specified or not.
wbemComparisonFlagIgnoreFlavor | 32 | Ignore qualifier flavors. This flag still takes qualifier values into account, but ignores flavor distinctions such as propagation rules and override restrictions.


WbemTimeout

WbemTimeout defines the timeout constants. This constant is used by SWbemEventSource.NextEvent.

Constant | Value (Hex) | Description
wbemTimeoutInfinite | 0xFFFFFFFF | Use this constant for parameters that use a time out value such as the iTimeoutMs for ISWbemServices.ExecNotificationQuery and the call will not return unless an event is received.


WbemCimtypeEnum

WbemCimtypeEnum defines the valid CIM types of a property value.

Constant | Value (Dec) | Description
wbemCimtypeSint16 | 2 | Signed 16 bit integer
wbemCimtypeSint32 | 3 | Signed 32 bit integer
wbemCimtypeReal32 | 4 | 32 bit real number
wbemCimtypeReal64 | 5 | 64 bit real number
wbemCimtypeString | 8 | String
wbemCimtypeBoolean | 11 | Boolean value
wbemCimtypeObject | 13 | Cim Object
wbemCimtypeSint8 | 16 | Signed 8 bit integer
wbemCimtypeUint8 | 17 | Unsigned 8 bit integer
wbemCimtypeUint16 | 18 | Unsigned 16 bit integer
wbemCimtypeUint32 | 19 | Unsigned 32 bit integer
wbemCimtypeSint64 | 20 | Signed 64 bit integer
wbemCimtypeUint64 | 21 | Unsigned 64 bit integer
wbemCimtypeDatetime | 101 | Date/Time value
wbemCimtypeChar16 | 103 | 16 bit character


WbemErrorEnum

WbemErrorEnum defines the errors that may be returned by WMI scripting API calls.

Constant | Value (Hex) | Description
wbemNoErr | 0 | The call was successful.
wbemErrFailed | 0x80041001 | The call failed.
wbemErrNotFound | 0x80041002 | The object could not be found.
wbemErrAccessDenied | 0x80041003 | The current user does not have permission to perform the action.
wbemErrOutOfMemory | 0x80041006 | There was not enough memory for the operation.
wbemErrInvalidParameter | 0x80041008 | One of the parameters to the call is not correct.
wbemErrInvalidSuperclass | 0x8004100D | The superclass specified is not valid.
wbemErrInvalidNamespace | 0x8004100E | The namespace specified could not be found.
wbemErrInvalidObject | 0x8004100F | The specified instance is not valid.
wbemErrInvalidClass | 0x80041010 | The specified class is not valid.
wbemErrTransportFailure | 0x80041015 | A networking error occurred, preventing normal operation.
wbemErrInvalidOperation | 0x80041016 | The requested operation is not valid. This error usually applies to invalid attempts to delete classes or properties.
wbemErrInvalidQuery | 0x80041017 | The query was not syntactically valid.
wbemErrInvalidQueryType | 0x80041018 | The requested query language is not supported.
wbemErrAlreadyExists | 0x80041019 | In a Put operation, wbemChangeFlagCreateOnly flag was specified, but the instance already exists.
wbemErrOverrideNotAllowed | 0x8004101A | It is not possible to perform the Add operation on this qualifier because the owning object does not permit overrides.
wbemErrPropagatedQualifier | 0x8004101B | The user attempted to delete a qualifier that was not owned. The qualifier was inherited from a parent class.
wbemErrPropagatedProperty | 0x8004101C | The user attempted to delete a property that was not owned. The property was inherited from a parent class.
wbemErrIllegalOperation | 0x8004101E | The user requested an illegal operation, such as spawning a class from an instance.
wbemErrCannotBeKey | 0x8004101F | There was an illegal attempt to specify a key qualifier on a property that cannot be a key. The keys are specified in the class definition for an object, and cannot be altered on a per-instance basis.
wbemErrIncompleteClass | 0x80041020 | The current object is not a valid class definition. Either it is incomplete, or it has not been registered with WMI using SWbemObject.Put_.
wbemErrReadOnly | 0x80041023 | The property that you are attempting to modify is read only.
wbemErrIllegalNull | 0x80041028 | A value of Nothing was specified for a property that may not be Nothing, such as one that is marked by a key, indexed, or not_null qualifier.
wbemErrInvalidQualifierType | 0x80041029 | The variant value for a qualifier was provided that is not of a legal qualifier type.
wbemErrInvalidPropertyType | 0x8004102A | The CIM type specified for a property is not valid.
wbemErrInvalidCimType | 0x8004102D | The CIM type specified is not valid.
wbemErrInvalidMethod | 0x8004102E | The requested method is not available.
wbemErrInvalidMethodParameters | 0x8004102F | The parameters provided for the method are not valid.
wbemErrInvalidObjectPath | 0x8004103A | The specified object path was invalid.

Automation-specific errors | Value (Hex) | Description
wbemErrTimedout | 0x80043001 | The time specified for a call to complete has been exceeded. You will see this error returned by SWbemEventSource.NextEvent when no events are received and the number of milliseconds specified by iTimeoutMs have passed.
wbemErrResetToDefault | 0x80043002 | The user deleted an override default value for the current class. The default value for this property in the parent class has been reactivated.


WbemAuthenticationLevelEnum

WbemAuthenticationLevelEnum defines the security authentication levels. These constants are used with SWbemSecurity.

Constant | Value (Dec) | Description
wbemAuthenticationLevelDefault | 0 | WMI will use the default Windows Authentication setting,
wbemAuthenticationLevelNone | 1 | Use no authentication.
wbemAuthenticationLevelConnect | 2 | Authenticates the credentials of the client only when the client establishes a relationship with the server.
wbemAuthenticationLevelCall | 3 | Authenticates only at the beginning of each call when the server receives the request.
wbemAuthenticationLevelPkt | 4 | Authenticates that all data received is from the expected client.
wbemAuthenticationLevelPktIntegrity | 5 | Authenticates and verifies that none of the data transferred between client and server has been modified.
wbemAuthenticationLevelPktPrivacy | 6 | Authenticates all previous levels and encrypts the argument value of each remote procedure call.


WbemImpersonationLevelEnum

WbemImpersonationLevelEnum defines the security impersonation levels. These constants are used with SWbemSecurity.

Constant | Value (Dec) | Description
wbemImpersonationLevelAnonymous | 1 | This impersonation hides the credentials of the caller and is specified with the WMI constant.
wbemImpersonationLevelIdentify | 2 | This impersonation allows objects to query the credentials of the caller.
wbemImpersonationLevelImpersonate | 3 | This impersonation allows objects to use the credentials of the caller.
wbemImpersonationLevelDelegate | 4 | This impersonation allows objects to permit other objects to use the credentials of the caller.


WbemPrivilegeEnum

WbemPrivilegeEnum defines privileges. These constants are used with SWbemSecurity to grant the Windows NT/Windows 2000 privileges required for some operations. See Windows NT/Windows 2000 Privilege Strings for more information.

Constant | Value (Dec) | Description
wbemPrivilegeCreateToken | 1 | Required to create a primary token.
wbemPrivilegePrimaryToken | 2 | Required to assign the primary token of a process.
wbemPrivilegeLockMemory | 3 | Required to lock physical pages in memory.
wbemPrivilegeIncreaseQuota | 4 | Required to increase the quota assigned to a process.
wbemPrivilegeMachineAccount | 5 | Required to create a machine account.
wbemPrivilegeTcb | 6 | This privilege identifies its holder as part of the trusted computer base. Some trusted protected subsystems are granted this privilege. This privilege is required to call the LogonUser.
wbemPrivilegeSecurity | 7 | Required to perform a number of security-related functions, such as controlling and viewing audit messages. This privilege identifies its holder as a security operator.
wbemPrivilegeTakeOwnership | 8 | Required to take ownership of an object without being granted discretionary access. This privilege allows the owner value to be set only to those values that the holder may legitimately assign as the owner of an object.
wbemPrivilegeLoadDriver | 9 | Required to load or unload a device driver.
wbemPrivilegeSystemProfile | 10 | Required to gather profiling information for the entire system.
wbemPrivilegeSystemtime | 11 | Required to modify the system time.
wbemPrivilegeProfileSingleProcess | 12 | Required to gather profiling information for a single process.
wbemPrivilegeIncreaseBasePriority | 13 | Required to increase the base priority of a process.
wbemPrivilegeCreatePagefile | 14 | Required to create a paging file.
wbemPrivilegeCreatePermanent | 15 | Required to create a permanent object.
wbemPrivilegeBackup | 16 | Required to perform backup operations.
wbemPrivilegeRestore | 17 | Required to perform restore operations. This privilege enables you to set any valid user or group SID as the owner of an object.
wbemPrivilegeShutdown | 18 | Required to shut down a local system.
wbemPrivilegeDebug | 19 | Required to debug a process.
wbemPrivilegeAudit | 20 | Required to generate audit-log entries.
wbemPrivilegeSystemEnvironment | 21 | Required to modify the nonvolatile RAM of systems that use this type of memory to store configuration information.
wbemPrivilegeChangeNotify | 22 | Required to receive notifications of changes to files or directories. This privilege also causes the system to skip all traversal access checks. It is enabled by default for all users.
wbemPrivilegeRemoteShutdown | 23 | Required to shut down a system using a network request.
wbemPrivilegeUndock | 24 | To be written.
wbemPrivilegeSyncAgent | 25 | To be written.
wbemPrivilegeEnableDelegation | 26 | To be written.


Windows NT/Windows 2000 Privilege Strings

The following table lists the Windows NT/Windows 2000 privilege strings and their corresponding WbemPrivilegeEnum Constants. You will need to use Windows NT/Windows 2000 Privilege strings for the strPrivilege parameter of the SWbemPrivilegeSet.AddAsString method. You can use the WbemPrivilegeEnum constants listed below as for the iPrivilege parameter of the equivalent method, SWbemPrivilegeSet.Add.

Windows NT/Windows 2000 Privilege | WbemPrivilegeEnum Constant | Value (Dec) | Description
SeCreateTokenPrivilege | wbemPrivilegeCreateToken | 1 | Required to create a primary token.
SeAssignPrimaryTokenPrivilege | wbemPrivilegePrimaryToken | 2 | Required to assign the primary token of a process.
SeLockMemoryPrivilege | wbemPrivilegeLockMemory | 3 | Required to lock physical pages in memory.
SeIncreaseQuotaPrivilege | wbemPrivilegeIncreaseQuota | 4 | Required to increase the quota assigned to a process.
SeMachineAccountPrivilege | wbemPrivilegeMachineAccount | 5 | Required to create a machine account.
SeTcbPrivilege | wbemPrivilegeTcb | 6 | This privilege identifies its holder as part of the trusted computer base. Some trusted protected subsystems are granted this privilege. This privilege is required to call the LogonUser.
SeSecurityPrivilege | wbemPrivilegeSecurity | 7 | Required to perform a number of security-related functions, such as controlling and viewing audit messages. This privilege identifies its holder as a security operator.
SeTakeOwnershipPrivilege | wbemPrivilegeTakeOwnership | 8 | Required to take ownership of an object without being granted discretionary access. This privilege allows the owner value to be set only to those values that the holder may legitimately assign as the owner of an object.
SeLoadDriverPrivilege | wbemPrivilegeLoadDriver | 9 | Required to load or unload a device driver.
SeSystemProfilePrivilege | wbemPrivilegeSystemProfile | 10 | Required to gather profiling information for the entire system.
SeSystemtimePrivilege | wbemPrivilegeSystemtime | 11 | Required to modify the system time.
SeProfileSingleProcessPrivilege | wbemPrivilegeProfileSingleProcess | 12 | Required to gather profiling information for a single process.
SeIncreaseBasePriorityPrivilege | wbemPrivilegeIncreaseBasePriority | 13 | Required to increase the base priority of a process.
SeCreatePagefilePrivilege | wbemPrivilegeCreatePagefile | 14 | Required to create a paging file.
SeCreatePermanentPrivilege | wbemPrivilegeCreatePermanent | 15 | Required to create a permanent object.
SeBackupPrivilege | wbemPrivilegeBackup | 16 | Required to perform backup operations.
SeRestorePrivilege | wbemPrivilegeRestore | 17 | Required to perform restore operations. This privilege enables you to set any valid user or group SID as the owner of an object.
SeShutdownPrivilege | wbemPrivilegeShutdown | 18 | Required to shut down a local system.
SeDebugPrivilege | wbemPrivilegeDebug | 19 | Required to debug a process.
SeAuditPrivilege | wbemPrivilegeAudit | 22 | Required to generate audit-log entries.
SeSystemEnvironmentPrivilege | wbemPrivilegeSystemEnvironment | 21 | Required to modify the nonvolatile RAM of systems that use this type of memory to store configuration information.
SeChangeNotifyPrivilege | wbemPrivilegeChangeNotify | 22 | Required to receive notifications of changes to files or directories. This privilege also causes the system to skip all traversal access checks. It is enabled by default for all users.
SeRemoteShutdownPrivilege | wbemPrivilegeRemoteShutdown | 23 | Required to shut down a system using a network request.
SeUndockNamePrivilege | wbemPrivilegeUndock | 24 | .
SeSyncAgentNamePrivilege | wbemPrivilegeSyncAgent | 25 | .
SeEnableDelegationNamePrivilege | wbemPrivilegeEnableDelegation | 26 |


WMI ADSI Extension Reference

[This is preliminary documentation and subject to change.]

This reference section provides information for developers who want to use WMI to manage computer objects returned from an Active Directory Service Interfaces (ADSI) query. This is a dual-language interface that supports Microsoft® Visual Basic®, Microsoft Visual Basic for Applications, Microsoft Visual Basic Scripting Edition, Microsoft® JScript®, C and C++.

The following table describes WMI objects and how they are used.

Object | Description
IWMIExtension | The IWMIExtension object extends ADSI computer objects returned from the LDAP namespace.


IWMIExtension

[This is preliminary documentation and subject to change.]

The IWMIExtension object extends ADSI computer objects returned from the LDAP namespace. The ADSI extension adds methods to those objects that let you manage them using WMI. For more information on this ADSI extension, see WMI ADSI Extension.

The following tables list the methods and properties that the IWMIExtension object adds to the ADSI computer object.

Methods

Method | Description
GetWMIObject | Returns the WMI computer object identified by the ADSI computer object.
GetWMIServices | Returns the WMI services object that you can use to perform other WMI actions, such as executing methods or invoking queries.

Properties

Property | Description
WMIObjectPath | A string value that contains a moniker. The moniker identifies the object path for the WMI computer object.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in Wbemads.h (C/C++).
Library: Use Wbemadsi.tlb (Visual Basic) or Wbemuuid.lib (C/C++).


IWMIExtension.GetWMIObject

[This is preliminary documentation and subject to change.]

The GetWMIObject method of IWMIExtension returns the Win32_ComputerSystem object identified by the ADSI computer object.

Syntax

[Visual Basic]objWMIObject = objwmiextension.GetWMIObject()

[C/C++]HRESULT IWMIExtension::GetWMIObject(
ISWbemObject **ppWMIObject
);

Parameters

[Visual Basic]None.

[C/C++]ppWMIObject
[out] The Win32_ComputerSystem object identified by the ADSI computer object.

Return Values

[Visual Basic]If the method is successful, the return value is an object of type SWbemObject.

[C/C++]An HRESULT object that contains the status of the method call.

Error Codes

[C/C++, Visual Basic]This method may return errors associated with SWbemLocator.ConnectServer and SWbemServices.Get.

[C/C++]

The GetWMIObject method may also return the error codes listed in the following table.

Error | Meaning
wbemErrInvalidParameter 0x80041008 | Returned if NULL is passed to this method. C language users must pass the address of an ISWbemObject object.

Remarks

[Visual Basic]Visual Basic users must select the WMI ADSI Extension Type Library reference for the project. The GetWMIObject method is available through the ADSI object for Visual Basic and scripting users when the ADSI object is instantiated.

[C/C++]This is a dual-language interface. You must query the ADSI object for the IWMIExtension interface before they can use this method. For more information on how to use the dual interface with C, see Automation Interfaces.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in Wbemads.h (C/C++).
Library: Use Wbemadsi.tlb (Visual Basic) or Wbemuuid.lib (C/C++).

See Also

Getting an Object with Getting anObject with GetWMIObject


IWMIExtension.GetWMIServices

[This is preliminary documentation and subject to change.]

The GetWMIServices method of IWMIExtension returns a WMI services object for the cimv2 namespace. You can then use this object to get other objects in the namespace, execute methods, and invoke WMI queries.

Syntax

[Visual Basic]objWMIServices = objwmiextension.GetWMIServices()

[C/C++]HRESULT IWMIExtension::GetWMIServices(
ISWbemServices **ppWMIServices
);

Parameters

[Visual Basic]None.

[C/C++]ppWMIServices
[out] A WMI services object that you can use in the cimv2 namespace to perform other WMI actions.

Return Values

[Visual Basic]If the method is successful, the return value is an object of type SWbemServices.

[C/C++]An HRESULT object that contains the status of the method call.

Error Codes

[C/C++, Visual Basic]This method may return errors associated with SWbemLocator.ConnectServer.

[C/C++]

The GetWMIServices method may also return the error codes listed in the following table.

Error | Meaning
wbemErrInvalidParameter 0x80041008 | Returned if NULL is passed to this method. C language users must pass the address of an ISWbemServices object.

Remarks

[Visual Basic]Visual Basic users must select the WMI ADSI Extension Type Library reference for the project. The GetWMIServices method is available through the ADSI object for Visual Basic and scripting users when the ADSI object is instantiated.

[C/C++]This is a dual-language interface. You must query the ADSI object for the IWMIExtension interface before they can use this method. For more information on how to use the dual interface with C, see Automation Interfaces.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in Wbemads.h (C/C++).
Library: Use Wbemadsi.tlb (Visual Basic) or Wbemuuid.lib (C/C++).

See Also

Getting a Service with GetWMIServices


IWMIExtension.WMIObjectPath

[This is preliminary documentation and subject to change.]

The WMIObjectPath property contains a moniker that is the object path to the WMI computer object. This property is read-only.

Syntax

[Visual Basic]sObjectPath = objwmiextension.WMIObjectPath

[C/C++]HRESULT IWMIExtension::get_WMIObjectPath(
BSTR *pbstrWMIOjbectPath
);

Parameters

[Visual Basic]None.

[C/C++]pbstrWMIObjectPath
[out] A moniker that is the object path to the WMI computer object.

Return Values

[Visual Basic]A moniker that is the object path to the WMI computer object.

[C/C++]An HRESULT object that contains the status of the method call. The status is always WBEM_NO_ERROR.

Remarks

[Visual Basic]Visual Basic users must select the WMI ADSI Extension Type Library reference for the project. The WMIObjectPath property is available through the ADSI object for Visual Basic and scripting users when the ADSI object is instantiated.

[C/C++]This is a dual-language interface. You must query the ADSI object for the IWMIExtension interface before they can access this property. For more information on how to use the dual interface with C, see Automation Interfaces.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in Wbemads.h (C/C++).
Library: Use Wbemadsi.tlb (Visual Basic) or Wbemuuid.lib (C/C++).

See Also

Getting the WMI Object Path


ActiveX Controls for WMI

The Windows Management (WMI) software development kit (SDK) provides a suite of Microsoft ActiveX controls that uses the native WMI APIs to perform logically related functions. These controls are the GUI components that form the WMI Object Browser and WMI CIM Studio applications included in the WMI SDK. Developers can use the controls to include GUI functionality in their WMI-based client applications.

The WMI SDK includes the following ActiveX controls:

Control | Description
WMI Class Navigator | Displays a tree view of the class structure in a namespace of the Common Information Model (CIM) repository.
WMI Provider Wizard | Generates C++ provider framework code for specified objects.
WMI EventList | Displays events that are forwarded to the event list.
WMI Event Registration | Displays event filters, event consumers, and their bindings.
WMI MOF Compiler Wizard | Compiles a specified .mof file.
WMI MOF Generator Wizard | Generates a .mof file for specified objects.
WMI Multiple Instances Viewer | Displays the details for one or more objects in a table format.
WMI Namespace Picker | Allows users to browse and select namespaces.
WMI Instance Navigator | Displays the associations between objects in a namespace in the CIM repository.
WMI Login | Provides login services for WMI ActiveX controls.
WMI Object Viewer | Displays the details for a specified object.
WMI Object Viewer Container | Provides navigation features for the WMI Object Viewer and the WMI Multiple Instances Viewer.


WMI Class Navigator

The WMI Class Navigator ActiveX control displays a tree view of the class structure of the Common Information Model (CIM) repository. In WMI CIM Studio, this control occupies the left pane.

Selecting a class in the tree initiates an EditExistingClass event, which notifies the container that the user has selected a class. In WMI CIM Studio, for example, this event notifies the right pane to display the details of the selected class. The GetIWbemServices event, which occurs when the control seeks to connect to a namespace, retrieves an IWbemServices pointer for the current namespace. This event is typically processed by the WMI Login. Successful opening of the namespace triggers the NotifyOpenNameSpace, which in turn notifies the container.

You select these classes by checking the boxes in the tree. This extended selection is useful for operations that involve multiple classes. For example, you can use the extended selection in WMI CIM Studio as the input to the WMI MOF Generator Wizard that generates Managed Object Format (.mof) files for all selected classes. GetSingleSelection returns the full path to the currently selected class.

Note These boxes must also be checked if you use this control with the WMI Provider Wizard, or the WMI MOF Generator Wizard.

When you call the MofCompiled method, you are notifying the control that a new .mof file has been compiled and that as a result, currently selected classes may have been modified. Calling this method refreshes the view of the current namespace and incorporates any modifications.

Properties

NameSpace

Methods

GetExtendedSelection, GetSingleSelection, MofCompiled, OnReadySignal

Events

EditExistingClass, GetIWbemServices, OpenNameSpace


WMI Class Navigator Properties

This section contains properties for the WMI Class Navigator control.


NameSpace Property of WMI Class Navigator

The NameSpace property returns the namespace currently displayed in the control or sets a new namespace. The NameSpace property, which is defined as BSTR NameSpace, defaults to **Root\Cimv2.

A Get operation returns the namespace currently displayed in the control. A Set operation changes the namespace. If a valid namespace is specified, the control logs in to Windows Management Instrumentation (WMI) and changes the property to the specified namespace.


WMI Class Navigator Methods

This section describes WMI Class Navigator control methods.


GetExtendedSelection Method of WMI Class Navigator

The GetExtendedSelection method returns the namespace and full paths to all classes chosen with extended selection.

VARIANT GetExtendedSelection();

Parameters

This method has no parameters.

Return Values

The GetExtendedSelection method returns a variant that contains an array of strings. The first element contains the namespace; the remaining elements contain full paths to all classes selected using extended selection.


GetSingleSelection Method of WMI Class Navigator

The GetSingleSelection method returns the full path to the selected class.

BSTR GetSingleSelection();

Parameters

This method has no parameters.

Return Values

If the GetSingleSelection method is successful, it returns the full path to the selected class. A path is always returned because a tree node is always selected.


MofCompiled Method of WMI Class Navigator

The MofCompiled method refreshes the view of the specified namespace and incorporates any modifications. Using the MofCompiled method signals to the control that a new MOF file has been compiled. The namespace that was passed is then refreshed, and any changes are reflected in the tree.

void MofCompiled(
  BSTR lpctstrNamespace
);

Parameters

lpctstrNamespace
The namespace that is refreshed.

Return Values

This method has no return values.


OnReadySignal Method of WMI Class Navigator

The OnReadySignal method notifies the control that it can start firing events. If this method is not called, the control does not correctly fire events to the container and to other controls in the container.

void OnReadySignal();

Parameters

This method has no parameters.

Return Values

This method has no return values.


WMI Class Navigator Events

This section describes events for the WMI Class Navigator control.


EditExistingClass Event of WMI Class Navigator

The EditExistingClass event asynchronously notifies the container that a class has been selected.

void EditExistingClass(
  VARIANT vExistingClass
);

Parameters

vExistingClass
A VT_BSTR variant containing a class path or an empty string.


GetIWbemServices Event of WMI Class Navigator

The WMI Class Navigator GetIWbemServices event retrieves an IWbemServices pointer to the current namespace and object path. This event occurs when the control tries to connect to a namespace.

void GetIWbemServices(
  BSTR lpctstrNamespace,
  VARIANT *pvarUpdatePointer,
  VARIANT *pvarServices,
  VARIANT *pvarSC,
  VARIANT *pvarUserCancel
);

Parameters

lpctstrNamespace
Namespace that the control connects to.
pvarUpdatePointer
Tells the DLL to get a new pointer.
pvarServices
The returned services pointer.
pvarSC
S_OK on success or failure code.
pvarUserCancel
Notifies the control that the user canceled.

See Also

IWbemServices


NotifyOpenNameSpace Event of WMI Class Navigator

The NotifyOpenNameSpace event asynchronously notifies the container that the specified namespace has been successfully opened.

void NotifyOpenNameSpace(
  BSTR lpcstrNameSpace
);

Parameters

lpcstrNameSpace
The namespace that was successfully opened.


WMI Provider Wizard

The WMI Provider Wizard ActiveX control generates C++ provider code. The provider code is based on the Provider Framework. The Windows Management Instrumentation (WMI) SDK uses this control as a component of WMI CIM Studio. Double-clicking the icon representing the control causes the control to fire the GenerateCPPs event. The container, or the client processing this event, is expected to set the CPPTargets. When set, this property is an array. The first element in the array is the namespace in which the control operates. The rest are the selected classes for which the provider code needs to be generated. Setting this property begins framework code generation for the selected classes. The GetIWbemServices event fires to retrieve an IWbemServices pointer to the specified namespace.

Properties

CPPTargets

Methods

None.

Events

GenerateCPPs, GetIWbemServices


WMI Provider Wizard Properties

This section describes properties for the WMI Provider Wizard control. This wizard is responsible for controlling the parameters of the framework provider code generator.


CPPTargets Property of WMI Provider Wizard

The CPPTargets property specifies or returns the classes for which provider framework code is generated. This property, which is defined as VARIANT CPPTargets, is an array of BSTRs.

A Set operation expects the namespace to be the first element of the array, followed by paths for the classes for which code will be generated. If the array elements are null or invalid, the control returns an error. Setting this value launches the framework code generation wizard.

A Get operation returns an array that has the namespace in the first element and object paths in subsequent elements.


WMI Provider Wizard Events

This section describes events for the WMI Provider Wizard control. This wizard is responsible for controlling the parameters of the framework provider code generator.


GenerateCPPs Event of WMI Provider Wizard

The GenerateCPPs event signals that the control is ready to receive a list of classes (and a namespace) to generate code for. The event handler should respond by setting the CPPTargets property. Upon setting this property, the WMI Provider Wizard becomes visible.

void GenerateCPPs();

Parameters

This event has no parameters.


GetIWbemServices Event of WMI Provider Wizard

The GetWbemServices event occurs when the control tries to connect to a namespace. This event retrieves an IWbemServices pointer for the current namespace and object path.

void GetIWbemServices(
  BSTR lpctstrNamespace,
  VARIANT *pvarUpdatePointer,
  VARIANT *pvarServices,
  VARIANT *pvarSC,
  VARIANT *pvarUserCancel
);

Parameters

lpctstrNamespace
Namespace that the control connects to.
pvarUpdatePointer
A pointer to a flag which notifies the DLL to get new pointer.
pvarServices
Services pointer that is returned.
pvarSC
S_OK on success or failure code.
pvarUserCancel
Notifies the control if the user canceled.

See Also

IWbemServices


WMI EventList

The WMI EventList ActiveX control displays the events that a registered consumer forwards to it. It is used, for example, in the WMI Event Viewer application. The Event Viewer event consumer registers its event consumer with Windows Management Instrumentation (WMI), which then forwards events received by its provider to this control. The consumer calls the control's AddWbemEvent, passing the logical consumer object as its first parameter, and the event object to display as its second parameter. The WMI EventList control then displays the event in the events list. The WMI EventList control uses properties in the consumer instance to customize the display, such as a description text that is displayed for the event, and the severity attached to it. Severity is indicated by the following list of message box (Msgbox) icons.

Severity | Displayed
1 | Error icon
2 | Warning icon
3 or higher | Information icons

The Clear method clears the events list, while the DoDetails method launches the WMI Object Viewer to allow a user to browse detailed event information. The OnSelChanged event fires when an event is selected in the events list.

For more information about WBEM events and consumers, see Event Notification.

Properties

MaxItems, ItemCount

Methods

AddWbemEvent, Clear, DoDetails

Events

OnSelChanged


WMI EventList Properties

This section contains properties for the WMI EventList control.


MaxItems Property of WMI EventList

The MaxItems property indicates the maximum number of events that can be displayed by the control at any given time. When the number of events received by the control exceeds the maximum, events are purged from the control according to their age; older events are purged first.

This property is defined as long maxItems.


ItemCount Property of WMI EventList

The ItemCount property contains the current number of events displayed by the control.

This property is defined as long ItemCount.


WMI EventList Methods

This section describes methods for the WMI EventList control.


AddWbemEvent Method of WMI EventList

The AddWbemEvent method adds an event to the consumer.

long AddWbemEvent(
  IUnknown *LogicalConsumer,
  IUnknown *Event
);

Parameters

LogicalConsumer
The logical consumer name.

This parameter must be an instance of EventViewerConsumer or an instance of a class derived from EventViewerConsumer.

Event
The event being added to the consumer.

If these parameters are NULL or invalid, the control returns an error.

Return Values

If the AddWbemEvent method is successful, it returns S_OK. If the parameters are incorrect, the control returns a failure code.


Clear Method of WMI EventList

The Clear method deletes items in the event selection list. The item that is deleted is passed as a parameter. If the item is not currently selected, an OnSelChanged event fires; another item is not automatically selected.

long Clear(
  long item
);

Parameters

item
The item number that is deleted. If the value of item is -1, then all items are deleted.

Return Values

If the Clear method is successful, the instance is created, and the method returns S_OK. If the method is unsuccessful,, it returns a failure code.


DoDetails Method of WMI EventList

The DoDetails method launches the WMI Object Viewer to display the selected object's information.

void DoDetails();

Parameters

This method has no parameters.

Return Values

This method has no return values.

See Also

WMI Object Viewer


WMI EventList Control Events

This section describes events of the WMI EventList control.

For more information about WMI events and consumers, see Event Notification.


OnSelChanged Event of WMI EventList

The OnSelChanged event occurs whenever the item selection in a control changes.

void OnSelChanged(
  long selected
);

Parameters

selected
Value indicates the item currently selected.

A value of -1 is sent when an item was not selected when the Clear method was called.

The selected parameter, which corresponds to a zero-based index, refers to the item's row in the EventList control. Resorting the list control changes an item's index.


WMI Event Registration

The WMI Event Registration ActiveX control provides a simple user interface used to define WMI event filters and consumers and to bind them together. The control displays class listings ,of currently defined event filters and event consumers and lists timer instructions. In the Windows Management Instrumentation (WMI) SDK, it is a component of the WMI Event Registration application.

The control's GetIWbemServices event occurs when the control seeks to connect to a namespace. The event retrieves an IWbemServices pointer to the current namespace.

NameSpace returns the current namespace, or sets a new one. The RootConsumerClass property returns or changes the current root consumer class. This property sets the scope of the control to display only consumers that are derived from a particular consumer class, instead of displaying all consumers in the namespace, which is the control's default setting.

In the RootFilterClass property, a Get operation returns the current root filter class; a Set operation changes the current root filter class. The RootFilterClass property also controls a displayed filter's scope by specifying that it be of a particular filter class or derived from a particular filter class.

The ViewMode property gets or changes the control's current view mode. The different modes determine whether the control displays filters, consumers, or timers in the tree view located in the left pane.

For more information about WMI events and consumers, see Event Notification.

Properties

NameSpace, RootConsumerClass, RootFilterClass, ViewMode

Methods

None.

Events

GetIWbemServices


WMI Event Registration Properties

This section contains properties for the WMI Event Registration control.


NameSpace Property of WMI Event Registration

The NameSpace property returns the namespace currently displayed in the control or sets a new namespace. A Get operation returns the namespace currently displayed in the control.

A Set operation changes the namespace. If a valid namespace is specified, the control logs in to WMI and changes the property to the specified namespace.

The NameSpace property, which is defined as BSTR NameSpace, has a default value of NULL.


RootConsumerClass Property of WMI Event Registration

The RootConsumerClass property returns or changes the current root consumer class. A Get operation returns the current root consumer class. A Set operation changes the root consumer class. If an incorrect root consumer class is specified, the control uses the default.

This property is defined as BSTR RootConsumerClass.


RootFilterClass Property of WMI Event Registration

The RootFilterClass property returns or changes the current root filter class. A Get operation returns the current root filter class; a Set operation changes the root filter class. If an incorrect root consumer class is specified, the control uses the defaults.

This property is defined as BSTR RootFilterClass.


ViewMode Property of WMI Event Registration

The ViewMode property returns or changes the current view of the control. This property defaults to NULL. A Get operation returns the current view of the control. A Set operation changes the view. If an incorrect root consumer class is specified, the control uses the default.

This property is defined as BSTR ViewMode.


WMI Event Registration Events

This section contains WMI Event Registration control events .


GetIWbemServices Event of WMI Event Registration

The GetIWbemServices event occurs when the control tries to connect to a namespace. This event retrieves an IWbemServices pointer for the current namespace and object path.

void GetIWbemServices(
  BSTR lpctstrNamespace,
  VARIANT *pvarUpdatePointer,
  VARIANT *pvarServices,
  VARIANT *pvarSC,
  VARIANT *pvarUserCancel
);

Parameters

lpctstrNamespace
Namespace that the control connects to.
pvarUpdatePointer
Tells DLL to get new pointer.
pvarServices
Services pointer that is returned.
pvarSC
The success or failure code.
pvarUserCancel
A pointer to a variable that notifies the control if the user cancels the operation.

See Also

IWbemServices


WMI MOF Compiler Wizard

The WMI MOF Compiler Wizard ActiveX control provides a user interface, from which the user can select s options for compiling a specified Managed Object Format (.mof) file. The Windows Management Instrumentation (WMI) SDK uses it as a component of WMI CIM Studio.The control connects to a namespace using the GetIWbemServices event, which retrieves an IWbemServices pointer to the current namespace and object path. The WMI Login control typically obtains this pointer. A handler for GetIWbemServices would typically invoke the WMI Login. The ModifiedNamespace event indicates which namespace was modified when the MOF file was compiled. This event can also notify other components that information they retrieve from a particular namespace may have changed as a result of the compilation, and that their data needs to be refreshed.

The WMI MOF Compiler Wizard includes the following events; there are no properties or methods.

GetIWbemServices, ModifiedNamespace


WMI MOF Compiler Wizard Events

This section describes events for the WMI MOF Compiler Wizard control.


GetIWbemServices Event of WMI MOF Compiler Wizard

The GetIWbemServices event occurs when the control tries to connect to a namespace. This event retrieves an IWbemServices pointer for the current namespace and object path.

void GetIWbemServices(
  BSTR lpctstrNamespace,
  VARIANT *pvarUpdatePointer,
  VARIANT *pvarServices,
  VARIANT *pvarSC,
  VARIANT *pvarUserCancel
);

Parameters

lpctstrNamespace
Namespace that the control connects to.
pvarUpdatePointer
Tells DLL to get new pointer.
pvarServices
Services pointer that is returned.
pvarSC
S_OK on success or failure code.
pvarUserCancel
Notifies the control if the user canceled the operation.

See Also

IWbemServices


ModifiedNamespace Event of WMI MOF Compiler Wizard

The ModifiedNamespace event is fired when a namespace has been modified by the compilation of a .mof file.

void ModifiedNamespace(
  BSTR lpcstrNamespace
);

Parameters

lpcstrNamespace
The modified namespace.


WMI MOF Generator Wizard

The WMI MOF Generator Wizard ActiveX control generates a Managed Object Format (.mof) file for specified objects. The Windows Management Instrumentation (WMI) SDK uses it as part of WMI CIM Studio. The control connects to a namespace by initiating the GetIWbemServices event to retrieve an IWbemServices pointer to the current namespace and object path. Double-clicking the control fires the GenerateMOFs event. The container processing this event is expected to set the MOFTargets property. When set, the MOFTargets property specifies the namespace from which to generate the .mof file, and the classes for which the MOF file is to be generated. Getting this property returns an array of object paths for which the .mof file is generated.

The WMI MOF Generator Wizard includes the following properties and events; there are no methods.

Properties

MOFTargets

Events

GenerateMOFs, GetIWbemServices


WMI MOF Generator Wizard Properties

This section contains the properties of the WMI MOF Generator Wizard Active X control.


MOFTargets Property of WMI MOF Generator Wizard

The MOFTargets property specifies or returns the objects for which the .mof file will be generated. This property, which is defined as VARIANT MOFTargets, is an array of BSTRs (a VARIANT of type VT_ARRAY | VT_BSTR).

A Set operation starts the .mof file generation process. To set this property, you must specify the namespace as the first element of the array, followed by paths for the objects for which the .mof file will be generated. If the array elements are NULL or invalid, the control returns an error.

A Get operation returns the contents of the property; you are returned an array of object paths only. If the array elements are NULL or invalid, the control returns an error.

The array must contain at least the namespace and one object or the control returns an error.


WMI MOF Generator Wizard Events

This section contains events for the WMI MOF Generator Wizard Active X control.


GenerateMOFs Event of WMI MOF Generator Wizard

The GenerateMOFs event signals that the control is ready to receive a list of classes (and a namespace) to generate code for. The event handler responds by setting the MOFTargets property. If this property is not set, the control reports an error. Otherwise, on return from the handler, the MOF Generator Wizard becomes visible.

void GenerateMOFs();

Parameters

This event has no parameters.


GetIWbemServices Event of WMI MOF Generator Wizard

[To be written.]


GetIWbemServices

The GetIWbemServices event occurs when the control wants to connect to a namespace. This event retrieves an IWbemServices pointer for the current namespace and object path.

void GetIWbemServices(
  BSTR lpctstrNamespace,
  VARIANT *pvarUpdatePointer,
  VARIANT *pvarServices,
  VARIANT *pvarSC,
  VARIANT *pvarUserCancel
);

Parameters

lpctstrNamespace
Namespace that the control connects to.
pvarUpdatePointer
Tells the DLL to get new pointer.
pvarServices
Services pointer that is returned.
pvarSC
S_OK on success or failure code.
pvarUserCancel
Notifies the control if the user cancels the operation.

See Also

IWbemServices


WMI Multiple Instances Viewer

The WMI Multiple Instances Viewer ActiveX control displays the details for one or more objects in a tabular format. The NameSpace property The PropertyFilter property indicates whether all of the control's properties are displayed, or only a subset.

The control connects to a namespace when the GetIWbemServices event retrieves an IWbemServices pointer for the current namespace and object path. A NotifySelectionChanged event notifies the container when you select a new object in the objects list. The NotifyViewObjectSelected event fires when you double-click a row handle or row cell. The event notifies the container to display that instance.

three different ways to specify which instances the control displays. QueryViewInstances is passed a query, which the control executes, and displays the resulting instances. ViewInstances receives an array of object paths, and displays the instances represented by these paths.ViewClassInstances is called with a class name and the control enumerates all instances of that class and displays them.

GetContext saves the control's current state in a context object, and returns a handle to the context object. RestoreContext restores the state of the control to the previously saved context. Context is used by the container to navigate back and forward through views. The context object contains all information the control requires to return to the state it was in when the context was saved.

The AddContextRef method increments the reference count for the specified context handle. ReleaseContext decrements the reference count.

GetEditMode returns TRUE if the control supports editing data, or FALSE if the data appears for browsing only. SetEditMode allows you to pass BOOL values to set the control's edit mode to edit or read-only.

The QueryObjectSelected method determines whether an object is selected. The GetObjectPath method gets the object path of the currently selected, first object in the list, or last object in the list, depending on the parameter passed in. SelectObjectByPath uses the object path to select the specified object in the object list. SelectObjectByPosition selects an object using its current position in the list. StartObjectEnumeration starts an enumeration of objects in the list, either from the currently object or from some specified position in the list. The NextObject method can then be used to enumerate through the next objects in the list. The PrevObject enumerates objects in the list in reverse order.

GetObjectTitle retrieves a display string for the currently selected object. GetTitle returns a title string and an accompanying icon that represent the information currently displayed by the control, both of which can be displayed by the container as a short caption for what the control shows. Currently, this control does not implement methods that support custom views.

QueryCanDeleteInstance must be called to determine whether an instance can be deleted. DeleteInstance deletes the selected instance. The user implements the method by pressing the DELETE key when the row for that instance is selected.

When the control uses Windows Management Instrumentation (WMI) to create a new instance of a WMI managed object, it calls ExternInstanceCreated. Similarly, ExternInstanceDeleted notifies the control when a managed object is deleted from WMI.

Properties

NameSpace, PropertyFilter

Methods

AddContextRef, ExternInstanceCreated, ExternInstanceDeleted, GetContext, GetEditMode, GetObjectPath, GetObjectTitle, GetTitle, GetViewTitle, NextObject, NextViewTitle, PrevObject, PrevViewTitle, QueryCanDeleteInstance, QueryNeedsSave, QueryObjectSelected, QueryViewInstances, RefreshView, ReleaseContext, RestoreContext, SelectObjectByPath, SelectObjectByPosition, SetEditMode, StartObjectEnumeration, StartViewEnumeration, ViewClassInstances, ViewInstances

Events

GetIWbemServices, NotifySelectionChanged, NotifyViewObjectSelected


WMI Multiple Instances Viewer Properties

This section contains properties for the WMI Multiple Instances Viewer control.


NameSpace Property of WMI Multiple Instances Viewer

The NameSpace property returns the namespace currently displayed in the control or sets a new namespace.

This property, which is defined as BSTR NameSpace, has a default value of NULL.

A Get operation returns the namespace currently displayed in the control.

A Set operation changes the namespace. If a valid namespace is specified, the control logs in to WMI and changes the property to the specified namespace.


PropertyFilter Property of WMI Multiple Instances Viewer

The PropertyFilter property indicates whether the control is displaying all of or only a subset of a control's properties.

This property is defined as long PropertyFilter.

Return Values

The PropertyFilter property returns one of the following bit values.

Value | Description
Bit 0 | Indicates whether to display system properties or not (1-display, 0-hide).
Bit 1 | Indicates whether to display inherited properties or not.
Bit 2 | Indicates whether to display local properties or not.


WMI Multiple Instances Viewer Methods

This section contains methods for the WMI Multiple Instances Viewer control.


AddContextRef Method of WMI Multiple Instances Viewer

The AddContextRef method increments the reference count for the specified context handle.

long AddContextRef(
  long lCtxtHandle
);

Parameters

lCtxtHandle
The context handle.

If this parameter is NULL or invalid, the control returns an error.

Return Values

If the AddContextRef method is successful, the reference count is incremented, and the method returns S_OK. If the method is unsuccessful, it returns an error.


DeleteInstance Method of WMI Multiple Instances Viewer

The DeleteInstance method deletes the current instance.

long DeleteInstance();

Parameters

This method has no parameters.

Return Values

If the DeleteInstance method is successful, the instance is deleted, and the method returns S_OK . If the method is unsuccessful, it returns a failure code.


ExternInstanceCreated Method of the WMI Multiple Instances Viewer Control

The ExternInstanceCreated method notifies the control when a WMI object instance is created.

void ExternInstanceCreated(
  BSTR szObjectPath
);

Parameters

szObjectPath
The full path of the WMI class object.

Return Values

This method has no return values.


ExternInstanceDeleted Method of the WMI Multiple Instances Viewer Control

The ExternInstanceDeleted method notifies the control when the WMI object instance is deleted. With this method, a custom view can indicate the non-existence of a specified object.

void ExternInstanceDeleted(
  BSTR szObjectPath
);

Parameters

szObjectPath
The full path of the WMI class object.

Return Values

This method has no returned values.


GetContext Method of the WMI Multiple Instances Viewer Control

The GetContext method takes a snapshot of the current state of the control, saves the state in a context object, and returns a handle to the context object. The initial reference count to the context object is one. The context object is deleted when its reference count is decremented to zero.

long GetContext(
  long *plCtxtHandle
);

Parameters

plCtxtHandle
Pointer to the location where the context handle should be returned. If this parameter is NULL or invalid, the control returns an error.

Return Values

If the GetContext method is successful, the context is successfully returned, and the method returns S_OK. If the method is unsuccessful, it returns a failure code.


GetEditMode Method of the WMI Multiple Instances Viewer Control

The GetEditMode method returns the current state of the edit mode flag.

long GetEditMode();

Parameters

This method has no parameters.

Return Values

If the GetEditMode method is successful, the view's data can be edited, and the method returns 1 (TRUE) . If the method is unsuccessful, the view's data is for browsing only, and the method returns 0 (FALSE).

See Also

IWbemServices


GetObjectPath Method of the WMI Multiple Instances Viewer Control

The GetObjectPath method returns the object path at the given object position.

BSTR GetObjectPath(
  [in] long lPosition
);

Parameters

lPosition
The object position in the current view.

For the WMI Object Viewer, zero is the only valid lPosition value. Any other value returns an error.

Return Values

If the GetObjectPath method is successful, an object exists at the specified position, and the method returns the object's path. If no object exists at the specified position, the method returns NULL.


GetObjectTitle Method of WMI Multiple Instances Viewer

The GetObjectTitle method returns a title for the specified object that is suitable for display to the user. The title is not necessarily the object path.

BSTR GetObjectTitle(
  long lPosition
);

Parameters

lPosition
The object position in the current view. The value of this parameter must be zero.

Return Values

If the GetObjectTitle method is successful, the value of lPosition is zero, and the method returns the title of the current object. If the method is unsuccessful, it returns an empty string.


GetTitle Method of WMI Multiple Instances Viewer

The GetTitle method retrieves the title and icon to display in the title bar.

long GetTitle(
  BSTR *pszTitle,
  IDispatch **lpPictureDisp
);

Parameters

pszTitle
Pointer to the place where the view's title should be returned.

If this parameter is NULL or invalid, the control returns an error.

lpPictureDisp
The picture dispatch pointer for the title bar icon to be displayed.

If no icon should be displayed, this parameter should be NULL . If this parameter is invalid, the control returns an error.

Return Values

If the GetTitle method is successful, it returns the object title and icon and a value of S_OK. If the method is unsuccessful, it returns E_FAIL.


GetViewTitle Method of WMI Multiple Instances Viewer

The GetViewTitle method retrieves the title of the view at the specified position. There is no view title for this control.

BSTR GetViewTitle(
  long lPosition
);

Parameters

lPosition
Position of the view that is retrieved. The parameter can be one of the following values.
Value | Description
0 | Default view
1 | Current view
2 | First view
3 | Last view

If the value specified is less than 0 or greater than 3, the control returns an error. If the value is NULL or invalid, the control returns an error.

Return Values

The GetViewTitle method returns an empty string, indicating there is no view title.


NextObject Method of WMI Multiple Instances Viewer

The NextObject method returns the position of the next object in the current view.

long NextObject(
  long lPosition
);

Parameters

lPosition
Position value returned by StartObjectEnumeration, PrevObject, or NextObject. If this parameter is NULL or invalid, the control returns an error.

Return Values

If the NextObject method is successful, it returns the position of the next object. If the method is unsuccessful, it returns an error.

See Also

PrevObject, StartObjectEnumeration


NextViewTitle Method of WMI Multiple Instances Viewer

The NextViewTitle method retrieves the title of the view at the next position.

long NextViewTitle(
  long lPosition,
  BSTR *pbstrTitle
);

Parameters

lPosition
The view position that is retrieved. The initial value is obtained by calling StartViewEnumeration.
pbstrTitle
Receives the view title.

If these parameters are NULL or invalid, the control returns an error.

Return Values

If the NextViewTitle method is successful, it returns the value -1, indicating there is no next view title,

See Also

PrevViewTitle, StartViewEnumeration


PrevObject Method of WMI Multiple Instances Viewer

The PrevObject method returns the position of the previous object in the current view.

long PrevObject(
  long lPosition
);

Parameters

lPosition
Position value returned by StartObjectEnumeration, PrevObject, or NextObject.If this parameter is NULL or invalid, the control returns an error.

Return Values

If the PrevObject method is successful, it returns the position of the previous object. If the method is unsuccessful, the control returns an error.

See Also

NextObject, StartObjectEnumeration


PrevViewTitle Method of WMI Multiple Instances Viewer

The PrevViewTitle method retrieves the title of the view at the previous position.

long PrevViewTitle(
  long lPosition,
  BSTR *pbstrTitle
);

Parameters

lPosition
The view position.

You can retrieve the initial value by calling StartViewEnumeration. If this parameter is null or invalid, the control returns an error.

pbstrTitle
Receives the view title.

Return Values

The PrevViewTitle method returns the value -1, indicating there is no previous view title.

See Also

NextViewTitle, StartViewEnumeration


QueryCanDeleteInstance Method of WMI Multiple Instances Viewer

The QueryCanDeleteInstance method determines whether to delete the current instance by calling DeleteInstance If this method is called after the call to DeleteInstance, the control returns an error.

long QueryCanDeleteInstance();

Parameters

This method has no parameters..

Return Values

If the QueryCanDeleteInstance method is successful, the current instance can be deleted, and the method returns TRUE. If the method is unsuccessful, the current instance cannot be deleted or there is no current instance to delete; the method returns FALSE..

See Also

DeleteInstance


QueryNeedsSave Method of WMI Multiple Instances Viewer

The QueryNeedsSave method determines whether the current object has been modified and must be saved.

long QueryNeedsSave();

Parameters

This method has no parameters.

Return Values

The QueryNeedsSave method returns FALSE.


QueryObjectSelected Method of WMI Multiple Instances Viewer

The QueryObjectSelected method determines whether the object is selected.

long QueryObjectSelected();

Parameters

This method has no parameters.

Return Values

If the QueryObjectSelected method is successful, the object is selected, and the method returns TRUE. If the method is unsuccessful, it returns FALSE.


QueryViewInstances Method of WMI Multiple Instances Viewer

The QueryViewInstances method displays the instances returned by a query.

void QueryViewInstances(
  BSTR szTitle,
  BSTR szQueryType,
  BSTR szQuery,
  BSTR szClass
);

Parameters

szTitle
Label used only for display purposes.
szQueryType
The query language used to return the instances. You can specify either WQL or SQL.
szQuery
The actual query syntax.
szClass
The result class that you specify. This parameter is optional.

Return Values

This method has no return values.


RefreshView Method of WMI Multiple Instances Viewer

The RefreshView method reloads the contents of the current view from the Common Information Model (CIM) repository.

long RefreshView();

Parameters

This method has no parameters.

Return Values

If the RefreshView method is successful, the view is reloaded, and the method returns S_OK. If the method is unsuccessful, it returns a failure code.


ReleaseContext Method of WMI Multiple Instances Viewer

The ReleaseContext method decrements the reference count of the specified context handle.

long ReleaseContext(
  long lCtxtHandle
);

Parameters

lCtxtHandle
The context handle.

If this parameter is NULL or invalid, the control returns an error.

Return Values

If the ReleaseContext method is successful, the reference count is decremented, and the method returns S_OK. If the method is unsuccessful, it returns a failure code.


RestoreContext Method of WMI Multiple Instances Viewer

The RestoreContext method restores the state of the control to the previously saved context.

long RestoreContext(
  long lCtxtHandle
);

Parameters

lCtxtHandle
Handle of the context, to which the state should be restored.

If this parameter is NULL or invalid, the control returns an error.

Return Values

If the RestoreContext method is successful, the view's context is restored, and the method returns S_OK. If the method is unsuccessful, , it returns a failure code.


SelectObjectByPath Method of WMI Multiple Instances Viewer

The SelectObjectByPath method selects the specified object by using the object path.

long SelectObjectByPath(
  BSTR szObjectPath
);

Parameters

szObjectPath
The WMI object path. The object path must be an absolute path.

If this parameter is NULL or invalid, the control returns an error.

Return Values

If the SelectObjectByPath method is successful, the object is selected, and the method returns S_OK. If the method is unsuccessful it returns an error.


SelectObjectByPosition Method of WMI Multiple Instances Viewer

The SelectObjectByPosition method selects an object in the current view by using the object's position. This method provides a means to jump to an object that appears in a custom view of the current object.

long SelectObjectByPosition(
  long lPosition
);

Parameters

lPosition
The object's position in the current view.

Return Values

If the SelectObjectByPosition method is successful, the object selection succeeds, and the method returns S_OK. If the method is unsuccessful, it returns a failure code.


SetEditMode Method of WMI Multiple Instances Viewer

The SetEditMode method sets the view's edit mode flag.

void SetEditMode(
  long lMode
);

Parameters

lMode
A flag that determines whether the fields of a property can be modified. lMode must be one of the following values:
Value | Description
0 = EDITMODE_BROWSER | Only the value field of a property may be modified.
1 = EDITMODE_STUDIO | All fields in the property may be modified.
2 = EDITMODE_READONLY | No fields in the property may be modified.

Return Values

This method has no return values.


StartObjectEnumeration Method of WMI Multiple Instances Viewer

The StartObjectEnumeration method starts the object enumeration process.

long StartObjectEnumeration(
  long lWhere
);

Parameters

lWhere
The position of the enumerated object.

lWhere must be one of the following values:
Value | Description
0 | Current object.
1 | First object
2 | Last object

Any other value returns an error.

Return Values

If the StartObjectEnumeration method is successful, the object selection is successful, and the method returns S_OK. If the method is unsuccessful, it returns E_FAILED.


StartViewEnumeration Method of WMI Multiple Instances Viewer

The StartViewEnumeration method starts the enumeration of custom views.

long StartViewEnumeration(
  [in] long lWhere
);

Parameters

lWhere
The view from which to start enumerating.

lWhere can be one of the following values:
Value | Description
0 | Default view
1 | Current object.
2 | First object
3 | Last object

Values less than 0 or greater than 3 return an error. If an invalid parameter is specified, the control returns an error.

Return Values

The StartViewEnumeration method returns -1, indicating that there are no alternate views.


ViewClassInstances Method of WMI Multiple Instances Viewer

The ViewClassInstances method retrieves the instance enumeration of the specified class and displays the instances.

void ViewClassInstances(
  BSTR lpszClassName
);

Parameters

lpszClassName
The path to the class whose instances you want to display.

Errors and exceptions are reported to the user.

Return Values

This method has no return values.


ViewInstances Method of WMI Multiple Instances Viewer

The ViewInstances method displays instances of views.

long ViewInstances(
  BSTR szTitle,
  VARIANT varPathArray
);

Parameters

szTitle
The view title.

If this parameter is NULL or invalid, the control returns an error.

varPathArray
An array pointer that expects an array of strings.

The first element in the array can be the class in the instance paths, or it can be empty; this element is ignored. The remaining array elements contain instance paths.

Errors and exceptions are reported to the user.

Return Values

This method has no return values.


WMI Multiple Instances Viewer Control Events

This section describes events for the WMI Multiple Instances Viewer control.


GetIWbemServices Event of WMI Multiple Instances Viewer

The GetIWbemServices event occurs when the control wants to connect to a namespace. This event retrieves an IWbemServices pointer for the current namespace and object path.

void GetIWbemServices(
  BSTR lpctstrNamespace,
  VARIANT *pvarUpdatePointer,
  VARIANT *pvarServices,
  VARIANT *pvarSC,
  VARIANT *pvarUserCancel
);

Parameters

lpctstrNamespace
Namespace that the control connects to.
pvarUpdatePointer
Tells DLL to get a new pointer.
pvarServices
Services pointer that is returned.
pvarSC
A flag containing S_OK on success; otherwise it contains an error code.
pvarUserCancel
Tells the control if the user canceled.

See Also

IWbemServices


NotifySelectionChanged Event of WMI Multiple Instances Viewer

The NotifySelectionChanged event occurs when the user clicks selects an instance in the viewer using the left mouse button. The event notifies the container that a new object is selected in a custom view.

void NotifySelectionChanged();

Parameters

This event has no parameters.


NotifyViewObjectSelected Event of WMI Multiple Instances Viewer

The NotifyViewObjectSelected event occurs when a user double-clicks an object.

void NotifyViewObjectSelected(
  BSTR szObjectPath
);

Parameters

szObjectPath
Path of the selected object.


RequestUIActive Event of WMI Multiple Instances Viewer

The RequestUIActive event occurs when the control wants to go UI active and may be embedded in an ActiveX control.

void RequestUIActive();

Parameters

This event has no parameters.


WMI Namespace Picker

With the WMI Namespace Picker ActiveX control, users can enter and select namespaces. In the Windows Management Instrumentation (WMI) SDK, the control is used as part of the Class Explorer and the Connect to Namespace dialog box in WMI CIM Studio.

The control's NameSpace property defaults to NULL. Setting the namespace logs the control on to WMI and changes the property to the indicated namespace.

A GetIWbemServices event indicates that the control wants to connect to a namespace, and it retrieves a pointer for the requested namespace. When the namespace opens successfully, the NotifyNameSpaceChanged event fires. The control redraws to reflect the changed namespace, which is indicated by the NameSpaceEntryRedrawn event. When the control seeks to become active in the user interface, and can be embedded in an ActiveX control, the RequestUIActive event occurs.

The first parameter passed to the OpenNameSpace method indicates the namespace to open. The method returns an error for an invalid or null namespace. The second parameter is a BOOLEAN value that determines whether the NotifyNameSpaceChanged event occurs.

The ClearNamespaceText method removes the text from the edit box, but leaves the namespace in the namespace history.

The ClearOnLoseFocus method sets a flag that tells the control to clear the text from the edit box when the control loses focus.

The SetFocusToEdit method sets the input focus to the edit control.

The GetNameSpaceText method returns the text currently displayed by the control's Namespace combo box. This can be the valid namespace or some text the user entered and might not be a valid namespace.

IsTextValid determines if the text is a valid namespace name.

SetNameSpaceText sets the text in the control to the specified namespace and changes the text color to blue.

Properties

NameSpace

Methods

ClearNamespaceText, ClearOnLoseFocus, GetNamespaceText,

IsTextValid, OpenNamespace,

SetFocusToEdit, SetNamespaceText

Events

GetIWbemServices, NotifyNameSpaceChanged, NameSpaceEntryRedrawn, RequestUIActive


WMI Namespace Picker Properties

This section describes the properties of the WMI Namespace Picker control.


NameSpace Property of WMI Namespace Picker

The WMI Namespace Picker NameSpace property returns the namespace currently displayed in the control or sets a new namespace.

The default value of the NameSpace property is NULL. A Get operation returns the namespace currently displayed in the control. A Set operation changes the namespace. If a valid namespace is specified, the control logs in to WMI and changes the property to the specified namespace.

This section contains methods for the WMI Namespace Picker control.


ClearNamespaceText Method of WMI Namespace Picker

The ClearNamespaceText method removes the text from the edit box but leaves the namespace in the namespace history. If it is not already part of the history, it is added.

void ClearNamespaceText(
  BSTR lpctstrNamespace
);

Parameters

lpctstrNamespace
The namespace currently displayed in the control.

Return Values

This method has no return values.


ClearOnLoseFocus Method of WMI Namespace Picker

The ClearOnLoseFocus method sets a flag that tells the control to clear the text from the edit box when the control loses focus.

void ClearOnLoseFocus(
  long lClearOnLoseFocus
);

Parameters

lClearOnLoseFocus
A flag that tells the control to clear the text from the edit box when the control loses focus, if lClearOnListFocus is not zero.

Return Values

This method has no return values.


GetNameSpaceText Method of WMI Namespace Picker

The GetNameSpaceText method returns the namespace text, which can be a valid namespace or can be dirty text. The text can be the valid namespace or some user-entered text that might not be a valid namespace.

BSTR GetNameSpaceText();

Parameters

This method has no parameters.

Return Values

If the GetNameSpaceText method is successful, it returns the namespace text.


IsTextValid Method of WMI Namespace Picker

The IsTextValid method determines whether the namespace text contains a valid namespace.

long IsTextValid();

Parameters

This method has no parameters.

Return Values

If the IsTextValid method is successful, the namespace text contains a valid namespace, and the method returns a non-zero value. If the IsTextValid method is unsuccessful, it returns zero.


OpenNamespace Method of WMI Namespace Picker

The OpenNamespace method opens the specified namespace.

long OpenNamespace(
  BSTR bstrNamespace,
  long longNoFireEvent
);

Parameters

bstrNamespace
Namespace that is opened.
longNoFireEvent
Result of the attempt to open the specified namespace. If the parameter value is FALSE, the NotifyNameSpaceChanged event fires. If the value is TRUE, the NotifyNameSpaceChanged event does not occur.

If these parameters are NULL or invalid, the control returns an error.

Return Values

If the OpenNamespace method is successful, the namespace is opened, and the method returns S_OK. If the OpenNamespace method is unsuccessful, it returns an error.

See Also

NotifyNameSpaceChanged


SetNamespaceText Method of WMI Namespace Picker

The SetNamespaceText method sets the text in the control to the specified namespace and the text color to blue.

void SetNamespaceText(
  BSTR lpctstrNamespace
);

Parameters

lpctstrNamespace
The namespace that displays in the control.

Return Values

Nothing.


SetFocusToEdit Method of WMI Namespace Picker

The SetFocusToEdit method sets the input focus to the edit control in the combo box. This allows containing controls or clients to notify the WMI Namespace Picker control when it has the input focus. This is useful with the user has given a containing control or client the input focus via the tab or arrow key

void SetFocusToEdit();

Parameters

This method has no parameters.

Return Values

This method has no return values.


WMI Namespace Picker Events

This section contains events for the WMI Namespace Picker control.


GetIWbemServices Event of WMI Namespace Picker Control

The GetIWbemServices event occurs when the control is ready to connect to a namespace. This event retrieves an IWbemServices pointer for the current namespace and object path.

void GetIWbemServices(
  BSTR lpctstrNamespace,
  VARIANT *pvarUpdatePointer,
  VARIANT *pvarServices,
  VARIANT *pvarSC,
  VARIANT *pvarUserCancel
);

Parameters

lpctstrNamespace
Namespace the control connects to.
pvarUpdatePointer
Tells the DLL to get a new pointer.
pvarServices
Services pointer that is returned.
pvarSC
The success or failure code returned by this event.
pvarUserCancel
A pointer to a variable that notifies the control if the user canceled.

See Also

IWbemServices


NameSpaceEntryRedrawn Event of WMI Namespace Picker

The NameSpaceEntryRedrawn event notifies the container that the control has redrawn itself.

void NameSpaceEntryRedrawn();

Parameters

This event has no parameters.


NotifyNameSpaceChanged Event of WMI Namespace Picker

The NotifyNameSpaceChanged event notifies the container when the specified namespace opens.

void NotifyNameSpaceChanged(
  BSTR bstrNewNameSpace,
  long longValid
);

Parameters

bstrNewNameSpace
The namespace that is opened.
longValid
This parameter always has a value of TRUE.


RequestUIActive Event of WMI Namespace Picker

The RequestUIActive event occurs when the control is ready to go UI-active and is ready to be embedded in an ActiveX control.

void RequestUIActive();

Parameters

This event has no parameters.


WMI Instance Navigator

The WMI Instance Navigator ActiveX control displays a tree of objects in the currently selected namespace in the Common Information Model (CIM) repository. The control also shows the associations between these objects. Objects in the repository are represented by nodes in the tree. Other nodes are used as grouping nodes. Use an association type to group objects with the same association type under one parent node. Instances of objects of the same class are also grouped under one parent node.

The control uses GetIWbemServices when it wants to connect to a namespace. Setting the NameSpace property changes the namespace to which the control is currently connected. Successful opening of a namespace is indicated by the NotifyOpenNameSpace event.

The OnReadySignal method notifies the control that all its dependencies are properly initialized, and the control can start normal operation. This method must be called before any other operation is performed in the control.

ViewObject events occur when the user selects a node that represents an instance in the navigator tree, or when an association is requested to be displayed (the latter is selected through a right-click context menu option). When you select a "grouping node" in the tree, the QueryViewInstances event fires, specifying through its parameters a WQL query that identifies the selected node. For example, if you select the association-type node representing "Win32_DependentService.Dependent", which is the node that hangs off of the instance node "Win32_Service.Name="Alerter"", the query passed in will be: "references of {Win32_Service.Name="Alerter""} where RequiredQualifier=Association ResultClass=Win32_DependentService Role=Dependent".

Properties

NameSpace.

Methods

OnReadySignal, ChangeRootOrNamespace

Events

GetIWbemServices, NotifyOpenNameSpace, QueryViewInstances, ViewObject


WMI Instance Navigator Properties

This section contains properties for the WMI Instance Navigator control.


NameSpace Property of WMI Instance Navigator

Definition

The WMI Instance Navigator NameSpace property returns the namespace currently displayed in the control or sets a new namespace.

The default value of the NameSpace property is NULL.

A Get operation returns the namespace currently displayed in the control. A Set operation changes the namespace. If a valid namespace is specified, the control logs in to Windows Management Instrumentation (WMI) and changes the property to the specified namespace.


WMI Instance Navigator Methods

This section contains methods for the WMI Instance Navigator control.


OnReadySignal Method of WMI Instance Navigator

The OnReadySignal method notifies the control that it can start firing events. If this method is not called, the control does not correctly fire events to the container and to other controls in the container.

void OnReadySignal();

Parameters

This method has no parameters.

Return Values

this method has no return values.


ChangeRootOrNamespace Method of WMI Instance Navigator

The ChangeRootOrNamespace method synchronizes the tree with the view in the WMI Object Viewer Container control.

long ChangeRootOrNamespace(
  BSTR lpctstrRootOrNamespace,
  long lMakeNamespaceCurrent,
  long lFireEvents
);

Parameters

lpctstrRootOrNamespace
An instance path or namespace, depending on the value of IMakeNamespaceCurrent.
lMakeNamespaceCurrent
If lMakeNamespaceCurrent is TRUE, the lpctstrRootOrNamespace parameter contains a namespace that is opened.
lFireEvents
If lFireEvents is TRUE, events appropriate to the completed operations will occur.

Return Values

If lpctstrRootOrNamespace is an instance path, it becomes the tree root. If the parameter is NULL, WBEM_E_INVALID_PARAMETER is returned. If the instance does not exist, WBEM_E_FAILED is returned.

Errors and exceptions are reported to the user when the namespace is opened.


WMI Instance Navigator Events

This section contains events for the WMI Instance Navigator control.


GetIWbemServices Event of WMI Instance Navigator

The GetIWbemServices event occurs when the control is ready to connect to a namespace. This event retrieves an IWbemServices pointer for the current namespace and object path.

void GetIWbemServices(
  BSTR lpctstrNamespace,
  VARIANT *pvarUpdatePointer,
  VARIANT *pvarServices,
  VARIANT *pvarSC,
  VARIANT *pvarUserCancel
);

Parameters

lpctstrNamespace
Namespace that the control connects to.
pvarUpdatePointer
A pointer to a variable that tells the DLL to get a new pointer.
pvarServices
Services that is pointer returned.
pvarSC
S_OK on success or failure code.
pvarUserCancel
Tells the control if the user canceled.

See Also

IWbemServices


NotifyOpenNameSpace Event of WMI Instance Navigator

The NotifyOpenNameSpace event occurs when the control asynchronously notifies the container that the specified namespace has been successfully opened.

void NotifyOpenNameSpace(
  BSTR lpcstrNameSpace
);

Parameters

lpcstrNameSpace
The namespace that was successfully opened.


QueryViewInstances Event of WMI Instance Navigator

The QueryViewInstances occurs when an association role node or object group node is selected. This event is deprecated because it is no longer fired.

void QueryViewInstances(
  BSTR pLabel,
  BSTR pQueryType,
  BSTR pQuery,
  BSTR pClass
);

Parameters

pLabel
Query label; used for display purposes.
pQueryType
The type of language used to make the query (WQL OR SQL).
pQuery
The query to be performed.
pClass
The class in which the query should be performed. This parameter is optional.


ViewObject Event of WMI Instance Navigator

The WMI Instance Navigator ViewObject event occurs when an instance is selected in the tree control or when an association is displayed.

void ViewObject(
  BSTR bstrPath
);

Parameters

bstrPath
The path to an association class. If this parameter is NULL or invalid, the control returns an error.


WMI Login

The Login ActiveX control provides login services for the Windows Management Instrumentation (WMI) ActiveX controls. Except for the Managed Object Format (MOF) Compiler controlling this section, the other ActiveX controls require the Login control to access information in the Common Information Model (CIM) repository. The LoginComponent property can be set to a text string that represents the application in which the control is being used. The control displays this text string in the caption of the login dialog box, so that the user knows which application requires a login by the user. A client that requires an interface pointer to a WMI namespace calls the GetIWbemServices method on this control, passing in the requested namespace. If needed, the control brings up a login dialog box for the user to specify credentials for connection. Ultimately, the control returns the caller an IWbemServices pointer to the requested namespace. PageUnloading flushes all cached service pointers.

For more information see WMI Application Logon.

Properties

LoginComponent

Methods

GetIWbemServices, PageUnloading

Events

None.


WMI Login Properties

This section contains the properties for the WMI Login control.


LoginComponent Property of WMI Login

The LoginComponent property, which is defined as BSTR LoginComponent, indicates which WMI component to log into, and is used in calls to the exported function in LoginDlg.dll. Setting this property sets the title of the login dialog box. If you retrieve this property it will contain any previously set title text and version numbers for the WMI core and WMI SDK.


WMI Login Methods

This section contains methods for the WMI Login control.


GetIWbemServices Method of WMI Login

The GetIWbemServices method opens the specified namespace by calling the exported function in LoginDlg.dll. The method retrieves an IWbemServices pointer for the current namespace and object path. If you are connecting to a new namespace or if you specify pvarUpdatePointer the login dialog will appear.

void GetIWbemServices(
  BSTR lpctstrNamespace,
  VARIANT *pvarUpdatePointer,
  VARIANT *pvarServices,
  VARIANT *pvarSC,
  VARIANT *pvarUserCancel
);

Parameters

lpctstrNamespace
Namespace that the control connects to.
pvarUpdatePointer
Requests new pointer from DLL.
pvarServices
Services pointer that is returned.
pvarSC
Returns S_OK on success. If the event does not retrieve an IWbemServices pointer or retrieves an invalid pointer, the control returns an error.
pvarUserCancel
Tells the control if the user canceled the call.

Return Values

This method has no return values.


PageUnloading Method of WMI Login

The PageUnloading method uncaches all service pointers by calling the exported function in LoginDlg.dll.

void PageUnloading();

Parameters

This method has no parameters.

Return Values

This method has no return values.


WMI Object Viewer

The WMI Object Viewer ActiveX control displays the details of a specified object, including a tab that displays the object's properties, a tab that describes the object's methods, and a tab with a graphical display of the object's associations to other objects.

The NameSpace property returns the current namespace, to which the viewer is connected. The value of the PropertyFilter property determines whether all properties or only a subset are displayed. Options include hiding system properties or hiding inherited properties.

The current filter can be obtained with GetPropertyFilter and set with SetPropertyFilter.

ReadyState is a stock property that indicates the control's readiness as it downloads. The ReadyStateChange event occurs when the amount of data received by a control causes the event to change to the next readiness state. This event is used during the loading of asynchronous (data path) properties. When the control is ready to be embedded in an ActiveX control, the RequestUIActive event occurs. To connect to a namespace, the control fires the GetIWbemServices event. Because of this, the control eventually receives an IWbemServices pointer for the requested namespace. When the user selects the context menu Make Root or Go To Namespace options in the associations tab for a displayed object, the NOTIFYChangeRootOrNamespace event notifies the container. In the case of a namespace change, the container can change the current namespace to be the one specified in the event. When used in conjunction with the WMI Instance Navigator, the container can request the WMI Instance Navigator to make the specified object the new root of the instances tree.

When the single-object viewer control creates a new Windows Management Instrumentation (WMI) object instance, NotifyInstanceCreated notifies the container. When the current object is modified and must be saved, the NotifySaveRequired event notifies the container. If the view in the control is modified in some way that changes its states, and does not necessarily require that the current object be saved, NotifyViewModified notifies the container.

A NotifySelectionChanged event notifies the container when a new object is selected in the single view's standard view or in a custom view. The JumpToMultipleInstanceView event requests the display of a multiple-instance view of an array of objects.

This control's methods include QueryObjectSelected, which determines whether an object is selected. GetContext retrieves the control's current state, saves the state in a context object, and returns a handle to the context object. This method's parameter must be a pointer to the place to which the context handle must be returned. RestoreContext restores the state of the control to the previously saved context. NotifyContextChanged notifies the container when the current context changes.

The AddContextRef method increments the reference count for the specified context handle, returning an error for either an invalid or NULL parameter. ReleaseContext decrements the reference count.

Editing data is possible if the GetEditMode method returns TRUE. If the return value is FALSE, the data appears for browsing only. SetEditMode passes BOOL values to set a view's edit mode flag.

The GetObjectPath method gets the object path of the selected object position. The parameter this method expects can be zero for the current object, 1 for the first object, and 2 for the last object. Other values return errors. If the call is successful, the method returns the requested object path as a BSTR. SelectObjectByPath uses the object path to select the specified object. StartObjectEnumeration starts the enumeration of objects.

A number of this control's methods obtain objects for views in applications. SelectObjectByPosition selects an object using its position in the current view. If an object has no path, as in the case of an embedded object, SelectObjectByPointer selects the object by using a pointer to the IWbemClassObject. GetObjectTitle retrieves and displays to the user a title for the specified object. GetTitle obtains and displays the title and icon in the title bar. When custom or alternate views exist, you can obtain the title using GetViewTitle. StartViewEnumeration starts the enumeration of custom views. SelectView selects the specified view; its parameters are the view positions returned by NextViewTitle and PrevViewTitle, which obtain titles at the next and previous positions in a view. NextObject and PrevObject return positions of objects in a view; RefreshView reloads the view's contents from the CIM repository.

Calls to QueryCanCreateInstance establish whether you can create an instance of the current class. You must call it before you call CreateInstance to create an instance of the selected class. CreateInstance also makes the new instance the current object. Calling CreateInstanceOfCurrentClass creates an instance of the current class. DeleteInstance deletes the selected instance. However, to determine whether an instance can be deleted, you must call QueryCanDeleteInstance first. QueryNeedsSave determines whether the current object has been modified, and needs to be saved by calling SaveData.

Clients of the WMI Object Viewer call ExternInstanceCreated when an instance is created by WMI. Similarly, ExternInstanceDeleted notifies the control when a managed object is deleted from WMI.

Properties

NameSpace, PropertyFilter, ReadyState

Methods

AddContextRef, CreateInstance, CreateInstanceOfCurrentClass, DeleteInstance, ExternInstanceCreated, ExternInstanceDeleted, GetContext, GetEditMode, GetObjectPath, GetObjectTitle, GetPropertyFilter, GetTitle, GetViewTitle, NextObject, NextViewTitle, PrevObject, PrevViewTitle, QueryCanCreateInstance, QueryCanDeleteInstance, QueryNeedsSave, QueryObjectSelected, RefreshView, ReleaseContext, RestoreContext, SaveData, SelectObjectByPath, SelectObjectByPointer, SelectObjectByPosition, SelectView, SetEditMode, SetPropertyFilter, StartObjectEnumeration, StartViewEnumration

Events

GetIWbemServices, JumpToMultipleInstanceView, NOTIFYChangeRootOrNamespace, NotifyContextChanged, NotifyInstanceCreated, NotifySaveRequired, NotifySelectionChanged, NotifyViewModified, RequestUIActive


WMI Object Viewer Properties

This section contains properties for the WMI Object Viewer control.


NameSpace Property of WMI Object Viewer

The NameSpace property returns the namespace currently displayed in the control or sets a new namespace. A Get operation returns the namespace currently displayed in the control.

A Set operation changes the namespace. If a valid namespace is specified, the control logs in to WMI and changes the property to the specified namespace.

This property, which is defined as BSTR NameSpace, has a default value of NULL.


PropertyFilter Property of WMI Object Viewer

The WMI Object Viewer PropertyFilter property indicates whether the control is displaying all of a control's properties or only a subset. This property is defined as long PropertyFilter.

The property filter can have any combination of the following flags set.

Flag | Meaning
1 | PROPFILTER_SYSTEM
2 | PROPFILTER_INHERITED
4 | PROPFILTER_LOCAL

Setting the flag results in the corresponding properties being displayed.


ReadyState Property of WMI Object Viewer

The Viewer ReadyState property indicates the current state of readiness of a control during a potentially asynchronous download process. This property, which is defined as long ReadyState, cannot be set.

The ReadyState property can have one of the following values.

Value Description
0
READYSTATE_UNINITIALIZED

Indicates that the control is not initialized. This is the default initialization state.
1
READYSTATE_LOADING

Indicates that the control is currently loading its properties.
2
READYSTATE_LOADED

Indicates that the control has been initialized.
3
READYSTATE_INTERACTIVE

Indicates that the control has enough data to be interactive, but asynchronous data is not completely loaded.
4
READYSTATE_COMPLETE

Indicates that the control has all of its data. Currently, this is the only value returned by the control.


WMI Object Viewer Methods

This section contains methods for the WMI Object Viewer control.


AddContextRef Method of WMI Object Viewer

The AddContextRef method increments the reference count for the specified context handle.

long AddContextRef(
  long lCtxtHandle
);

Parameters

lCtxtHandle
The context handle.

If this parameter is NULL or invalid, the control returns an error.

Return Values

If the AddContextRef method is successful, the reference count is incremented, and the method returns S_OK. If the method is unsuccessful, it returns an error.


CreateInstance Method of WMI Object Viewer

The CreateInstance method creates an instance of the specified class and makes this instance the current object.

long CreateInstance(
  BSTR szClassName
);

Parameters

szClassName
The name of the class of which an instance will be created.

If this parameter is NULL or invalid, the control returns an error.

Return Values

If the CreateInstance method is successful, the instance is created, and the method returns S_OK If the method is unsuccessful, it returns a failure code.


CreateInstanceOfCurrentClass Method of WMI Object Viewer

The CreateInstanceOfCurrentClass method creates an instance of the current class.

long CreateInstanceOfCurrentClass();

Parameters

This method had no parameters.

Return Values

If the CreateInstanceOfCurrentClass method is successful, if the instance is successfully created, and the method returns S_OK. If the method is unsuccessful, it returns a failure code.


DeleteInstance Method of WMI Object Viewer

The DeleteInstance method deletes the currently selected instance.

long DeleteInstance();

Parameters

This method has no parameters.

Return Values

If the DeleteInstance method is successful, the instance is successfully deleted, and the method returns S_OK. If the method is unsuccessful, it returns a failure code.


ExternInstanceCreated Method of WMI Object Viewer

The ExternInstanceCreated method notifies the control when a WMI object instance is created

void ExternInstanceCreated(
  BSTR szObjectPath
);

Parameters

szObjectPath
The full path of the WMI class object.

Return Values

This method has no return values.


ExternInstanceDeleted Method of WMI Object Viewer

The ExternInstanceDeleted method notifies the control when the WMI object instance is deleted. This allows a custom view to reflect the non-existence of a specified object.

void ExternInstanceDeleted(
  BSTR szObjectPath
);

Parameters

szObjectPath
The full path of the WMI class object.

Return Values

This method has no return values.


GetContext Method of WMI Object Viewer

The GetContext method takes a snapshot of the current state of the control, saves the state in a context object, and returns a handle to the context object. The initial reference count to the context object is one. The context object is deleted when its reference count is decremented to zero.

long GetContext(
  long *plCtxtHandle
);

Parameters

plCtxtHandle
Pointer to the place where the context handle should be returned. If this parameter is null or invalid, the control returns an error.

Return Values

If the GetContext method is successful, the context is successfully returned, and the method returns S_OK. If the method is unsuccessful, it returns a failure code.


GetEditMode Method of WMI Object Viewer

The GetEditMode method returns the current state of the edit mode flag.

long GetEditMode();

Parameters

This method has no parameters.

Return Values

If the GetEditMode method view's data can be edited, the method returns 1 (TRUE). If the view data is for browsing only, the method returns 0 (FALSE)..


GetObjectPath Method of WMI Object Viewer

The GetObjectPath method returns the object path at a specific object position.

BSTR GetObjectPath(
  [in] long lPosition
);

Parameters

lPosition
The position of the object, which can be one of the following values.
0 | Current object
1 | First object
2 | Last object

If the value specified is less than 0 or greater than 2, the control returns an error. If this parameter is NULL or invalid, the control returns an error.

For the WMI Object Viewer, 0 is the only valid lPosition value; any other value returns an error.

Return Values

If the GetObjectPath method is successful, an object exists at the specified position, and the method returns the object's path, If no object exists at the specified position, the method returns NULL.


GetObjectTitle Method of WMI Object Viewer

The GetObjectTitle method returns a title for the specified object that is suitable for display to the user. The title is not necessarily the object path.

BSTR GetObjectTitle(
  long lPosition
);

Parameters

lPosition
Position of the current object. The value of this parameter must be zero.

Return Values

If the value of lPosition is zero, the GetObjectTitle method returns the title of the current object; otherwise the method returns an error.


GetPropertyFilter Method of WMI Object Viewer

[To be written.]


GetPropertyFilter (WBEM Object Viewer)

The GetPropertyFilter method retrieves the property filter.

long GetPropertyFilter();

Parameters

This method has no parameters.

Return Values

If the GetPropertyFilter method is successful, it returns the PropertyFilter flags.

See Also

PropertyFilter, SetPropertyFilter


GetTitle Method of WMI Object Viewer

The GetTitle method retrieves the title and icon to display in the title bar.

long GetTitle(
  BSTR *pszTitle,
  IDispatch **lpPictureDisp
);

Parameters

pszTitle
Pointer to the place where the view's title is returned.

If this parameter is NULL or invalid, the control returns an error.

lpPictureDisp
The picture dispatch pointer for the title bar icon to be displayed. This parameter should be null if no icon should be displayed. If this parameter is invalid, the control returns an error.

Return Values

If the GetTitle method is successful, the title and icon are returned, and the method returns S_OK . If the method is unsuccessful, it returns E_FAIL.


GetViewTitle Method of WMI Object Viewer

The GetViewTitle method retrieves the title of the view at the specified position. This method provides a way to obtain a specific view 's title when alternate or custom views of an object exist.

BSTR GetViewTitle(
  long lPosition
);

Parameters

lPosition
Specifies the position of the view to be retrieved.

Return Values

If the GetViewTitle method is successful, it returns the view title.


NextObject Method of WMI Object Viewer

The NextObject method returns the position of the next object in the current view.

long NextObject(
  long lPosition
);

Parameters

lPosition
Position value returned by StartObjectEnumeration, PrevObject, or NextObject.

If this parameter is NULL or invalid, the control returns an error.

Return Values

If the NextObject method is successful, it returns the position of the next object. If the method is unsuccessful, it returns an error.

Remarks

This method, which is not yet implemented, returns only a value of -1.

See Also

PrevObject, StartObjectEnumeration


NextViewTitle Method of WMI Object Viewer

The NextViewTitle method retrieves the title of the view at the next position.

long NextViewTitle(
  long lPosition,
  BSTR *pbstrTitle
);

Parameters

If these parameters are NULL or invalid, the control returns an error.

lPosition
The view position given. The initial value is obtained by calling StartViewEnumeration.
pbstrTitle
Receives the view title.

Return Values

If the NextViewTitle method is successful, it returns the position of the view title. If there is no next view, the method returns a value of -1.

See Also

PrevViewTitle, StartViewEnumeration


PrevObject Method of WMI Object Viewer

The PrevObject method returns the position of the previous object in the current view.

long PrevObject(
  long lPosition
);

Parameters

lPosition
Position value returned by StartObjectEnumeration, PrevObject, or NextObject.

If this parameter is NULL or invalid, the control returns an error.

Return Values

If the PrevObject method is successful, it returns the position of the previous object. If the PrevObject method is unsuccessful, it returns an error.

Remarks

This method, which is not yet implemented, returns only a value of -1.

See Also

NextObject, StartObjectEnumeration


PrevViewTitle Method of WMI Object Viewer

The PrevViewTitle method retrieves the title of the view at the previous position. This method is useful when enumerating view titles.

long PrevViewTitle(
  long lPosition,
  BSTR *pbstrTitle
);

Parameters

lPosition
The view position.

The initial value is obtained by calling StartViewEnumeration. If this parameter is NULL or invalid, the control returns an error.

pbstrTitle
A BSTR that receives the view title.

Return Values

If the PrevViewTitle method is successful, it returns the position of the view title. If there is no previous view, the method returns a value of -1.

See Also

NextViewTitle, StartViewEnumeration


QueryCanCreateInstance Method of WMI Object Viewer

The QueryCanCreateInstance method determines whether to call CreateInstance to create an instance of a current class. This method checks various attributes of the current class such as the existence of a key to verify that it makes sense to create a class instance. If this method is not called before calling CreateInstance, the control returns an error.

long QueryCanCreateInstance();

Parameters

This method has no parameters.

Return Values

If the QueryCanCreateInstance method is successful, a new class instance can be created, and the method returns TRUE. If the QueryCanCreateInstance method is unsuccessful, it returns FALSE.

When used in the WMI Multiple Instances Viewer, this method should only return FALSE; any other value returns an error.

See Also

CreateInstance


QueryCanDeleteInstance Method of WMI Object Viewer

The QueryCanDeleteInstance method determines whether to call DeleteInstance to delete the current instance. If this method is not called before calling DeleteInstance, the control returns an error.

long QueryCanDeleteInstance();

Parameters

This method has no parameters.

Return Values

If the QueryCanDeleteInstance method is successful, the current instance can be deleted, and the method returns TRUE.

If the current instance cannot be deleted or if there is no current instance to delete, the method returns FALSE.

See Also

DeleteInstance


QueryNeedsSave Method of WMI Object Viewer

The QueryNeedsSave method determines whether the current object has been modified and must be saved. The modified object can be saved by calling SaveData.

long QueryNeedsSave();

Parameters

This method has no parameters.

Return Values

If the current object has been modified and must be saved, the method returns TRUE; otherwise, it returns FALSE.

When used in the WMI Multiple Instances Viewer, this method should only return FALSE; any other value returns an error.

See Also

SaveData


QueryObjectSelected Method of WMI Object Viewer

The QueryObjectSelected method determines whether an object is selected.

long QueryObjectSelected();

Parameters

This method has no parameters.

Return Values

If an object is selected, the method returns TRUE; otherwise, it returns FALSE.

Remarks

This method, which is not yet implemented, returns only a value of TRUE.


RefreshView Method of WMI Object Viewer

The RefreshView method reloads the contents of the current view from the Common Information Model (CIM) repository.

long RefreshView();

Parameters

This method has no parameters.

Return Values

If the RefreshView method is successful, the contents of the CIM repository reloads, and the method returns S_OK. If the method is unsuccessful, it returns a failure code.


ReleaseContext Method of WMI Object Viewer

The ReleaseContext method decrements the reference count for the specified context handle.

long ReleaseContext(
  long lCtxtHandle
);

Parameters

lCtxtHandle
The context handle.

If this parameter is NULL or invalid, the control returns an error.

Return Values

If the ReleaseContext method is successful, the reference count is decremented, and the method returns S_OK. If the ReleaseContext method is unsuccessful, it returns a failure code.


RestoreContext Method of WMI Object Viewer

The RestoreContext method restores the state of the control to the previously saved context.

long RestoreContext(
  long lCtxtHandle
);

Parameters

lCtxtHandle
Handle of the context to which the state should be restored.

If this parameter is NULL or invalid, the control returns an error.

Return Values

If the RestoreContext method is successful, the view's context is restored, and the method returns S_OK. If the RestoreContext method is unsuccessful, it returns a failure code.


SaveData Method of WMI Object Viewer

The SaveData method saves changes to the current object.

long SaveData();

Parameters

This method has no parameters.

Return Values

If the SaveData method is successful, the changes are saved, and the method returns S_OK.

If the SaveData method is unsuccessful, it returns a failure code.


SelectObjectByPath Method of WMI Object Viewer

Windows Management Instrumentation

Method of WMI Object Viewer

The SelectObjectByPath method selects the specified object using the object path. The object path must be an absolute path.

long SelectObjectByPath(
  BSTR szObjectPath
);

Parameters

szObjectPath
The WMI object path.

If this parameter is NULL or invalid, the control returns an error.

Return Values

If the SelectObjectByPath method is successful, the object is selected, and the method returns S)OK.

If the SelectObjectByPath method is unsuccessful, it returns an error.


SelectObjectByPointer Method of WMI Object Viewer

The SelectObjectByPointer method selects an object given a pointer to the IWbemClassObject. Use this method for selecting objects that have no path, such as objects that are embedded in other objects. This method assumes that the object resides in the most recently used namespace.

long SelectObjectByPointer(
  IUnknown *lpunkWbemServices,
  IUnknown *lpunkClassObject,
  long bExistsInDatabase
);

Parameters

If any of the following parameters is null or invalid, the control returns an error.

lpunkWbemServices
A pointer to an IWbemServices interface.
lpunkClassObject
A pointer to the object, which should be the IWbemClassObject pointer.
bExistsInDatabase
Set to True if the object already exists in the repository. If this value is set to False, the method returns an error.

Return Values

If the SelectObjectByPointer method is successful, the object is selected, and the method returns S_OK .If the method is unsuccessful, it returns an error.

See Also

IWbemClassObject


SelectObjectByPosition Method of WMI Object Viewer

The SelectObjectByPosition method selects an object in the current view by using the object's position. This method provides a means to jump to an object that appears in a custom view of the current object.

long SelectObjectByPosition(
  long lPosition
);

Parameters

lPosition
The object position in the current view.

Return Values

If the SelectObjectByPosition method is successful, the object selection succeeds, and the method returns S_OK.

If the method is unsuccessful, it returns a failure code.

Remarks

This method, which is not yet implemented, returns only S_OK.


SelectView Method of WMI Object Viewer

The SelectView method selects the specified view.

long SelectView(
  long lPosition
);

Parameters

lPosition
The position of the view returned by StartViewEnumeration, NextViewTitle, or PrevViewTitle.

If this parameter is NULL or invalid, the control returns an error.

Return Values

If the SelectView method is successful, the view selection succeeds, and the method returns S_OK. If the method is unsuccessful, it returns an error.

See Also

NextViewTitle, PrevViewTitle, StartViewEnumeration


SetEditMode Method of WMI Object Viewer

The SetEditMode method sets the view's edit mode flag.

void SetEditMode(
  long lMode
);

Parameters

lMode
Determines whether the fields of a property can be modified. lMode must be one of the following values:
Value | Description
0 | EDITMODE_BROWSER | Only the value field of a property may be modified.
1 | EDITMODE_STUDIO | All fields in the property may be modified.
2 | EDITMODE_READONLY | No fields in the property may be modified.

Return Values

This method has no return values.


SetPropertyFilter Method of WMI Object Viewer

The SetPropertyFilter method sets the property filter.

void SetPropertyFilter(
  long lFlags
);

Parameters

lFlags
The property filter can have any combination of the following flags set:
1 | PROPFILTER_SYSTEM
2 | PROPFILTER_INHERITED
4 | PROPFILTER_LOCAL

Setting the flag results in the corresponding properties being displayed.

Return Values

If the SetPropertyFilter method is successful, the PropertyFilter flags are set.

See Also

PropertyFilter, GetPropertyFilter


StartObjectEnumeration Method of WMI Object Viewer

The StartObjectEnumeration method starts the enumeration of objects.

long StartObjectEnumeration(
  long lWhere
);

Parameters

lWhere
Expects zero, which indicates the current object; any other value returns an error.

Return Values

The StartObjectEnumeration method returns success if an object is selected. If the method is unsuccessful, it returns E_FAILED.

Remarks

This method, which is not yet implemented, returns only a value of zero.


StartViewEnumeration Method of WMI Object Viewer

The StartViewEnumeration method starts the enumeration of custom views.

long StartViewEnumeration(
  [in] long lWhere
);

Parameters

lWhere
The view from which to start enumerating.

The parameter can be one of the following values.
0 | Default view
1 | Current view
2 | First view
3 | Last view

Values less than 0 or greater than 3 return an error. If an invalid parameter is specified, the control returns an error.

Return Values

The StartViewEnumeration method returns the view position value. If this value is -1, there are no alternate views.


WMI Object Viewer Control Events

This section contains events for the WMI Object Viewer control.


GetIWbemServices Event of WMI Object Viewer

The GetIWbemServices event occurs when the control wants to connect to a namespace. This event retrieves an IWbemServices pointer for the current namespace and object path.

void GetIWbemServices(
  BSTR lpctstrNamespace,
  VARIANT *pvarUpdatePointer,
  VARIANT *pvarServices,
  VARIANT *pvarSC,
  VARIANT *pvarUserCancel
);

Parameters

lpctstrNamespace
Namespace that the control connects to.
pvarUpdatePointer
Tells DLL to get new pointer.
pvarServices
Services pointer that is returned.
pvarSC
S_OK on success or failure code.
pvarUserCancel
Tells the control if the user canceled.

See Also

IWbemServices


JumpToMultipleInstanceView Event of WMI Object Viewer

The JumpToMultipleInstanceView event requests the display of a multiple-instance view of an array of objects.

void JumpToMultipleInstanceView(
  BSTR szTitle,
  VARIANT varPathArray
);

Parameters

szTitle
The title to be displayed for the multiple instances.
varPathArray
An array of WMI object paths.

If any of these parameters is NULL or invalid, the control returns an error.


NOTIFYChangeRootOrNamespace Event of WMI Object Viewer

The ChangeRootOrNamespace event notifies the container when the user has changed the root or the namespace.

void NOTIFYChangeRootOrNamespace(
  BSTR szRootOrNamespace,
  long bChangeNamespace,
  long bEchoSelectObject
);

Parameters

szRootOrNamespace
The path to the new root or namespace.
bChangeNamespace
If szRootOrNamespace contains a namespace path, this value is TRUE. If szRootOrNamespace contains a root path, this value is FALSE.
bEchoSelectObject
If the code that catches this event should fire back an event to select an object and thus replacing the current selection in the WMI Object Viewer, this contains the value TRUE.

If any of these parameters is NULL or invalid, the control returns an error.


NotifyContextChanged Event of WMI Object Viewer

The NotifyContextChanged event notifies the container when the current context changes.

void NotifyContextChanged(
  long bPushContext
);

Parameters

bPushContext
If the current context is changed in a way that requires the new context to be pushed onto its context stack, the value is TRUE; otherwise, the value is FALSE. If this parameter is NULL or invalid, the control returns an error.


NotifyInstanceCreated Event of WMI Object Viewer

The NotifyInstanceCreated event notifies the container when a new WMI object instance is created.

void NotifyInstanceCreated(
  BSTR szObjectPath
);

Parameters

szObjectPath
The WMI object path for the newly-created instance.

If this parameter is NULL or invalid, the control returns an error.


NotifySaveRequired Event of WMI Object Viewer

The NotifySaveRequired event notifies the container when the current object is modified and must be saved.

void NotifySaveRequired();

Parameters

This event has no parameters.


NotifySelectionChanged Event of WMI Object Viewer

The NotifySelectionChanged event notifies the container that a new object is selected in a custom view. This event occurs when the user clicks selects an instance in the viewer using the left mouse button.

void NotifySelectionChanged();

Parameters

This event has no parameters.


NotifyViewModified Event of WMI Object Viewer

The NotifyViewModified event notifies the container when the view is modified in some way that changes its state but does not necessarily require that the current object be saved.

void NotifyViewModified();

Parameters

This event has no parameters.


RequestUIActive Event of WMI Object Viewer

The RequestUIActive event occurs when the control wants to go UI active and may be embedded in an ActiveX control.

void RequestUIActive();

Parameters

This event has no parameters.


WMI Object Viewer Container

The WMI Object Viewer Container ActiveX control provides navigation features for the WMI Object Viewer and the WMI Multiple Instances Viewer. When the control seeks to connect to a namespace, the GetIWbemServices event fires, thus retrieving an IWbemServices pointer for the current namespace and object path. Get and set operations on the NameSpace, respectively, return the current namespace or connect to a new one. Similarly, the ObjectPath property returns or sets the Windows Management Instrumentation (WMI) object path of an object or class you want to view. When the user changes the root or the namespace, the NOTIFYChangeRootOrNamespace notifies the container.

When you select an object path, StatusCode stores the most recent status code. StudioModeEnabled indicates the access level for a particular class. Setting it to TRUE allows you to edit, while setting it to FALSE allows you only to browse. Calling SaveState saves any WMI objects that have been modified. The QueryViewInstances method displays the instances returned by a query, while ShowInstances provides a view of multiple instances specified by the array of object paths.

ReadyState is a stock property that cannot be set. It indicates the progressive readiness of the control to exchange data as it downloads. Changes to this property trigger the ReadyStateChange event. When the control seeks to become active in the user interface, and it can be embedded in an ActiveX control, the RequestUIActive event fires.

Properties

NameSpace, ObjectPath, ReadyState, StatusCode, StudioModeEnabled

Methods

QueryViewInstances, SaveState, ShowInstances

Events

GetIWbemServices, NotifyChangeRootOrNamespace, RequestUIActive


WMI Object Viewer Container Properties

This section contains properties for the WMI Object Viewer Container control.


NameSpace Property of WMI Object Viewer Container

The NameSpace property returns the namespace currently displayed in the control or sets a new namespace. A Get operation returns the namespace currently displayed in the control.

A Set operation changes the namespace. If a valid namespace is specified, the control logs in to WMI and changes the property to the specified namespace.

This property, which is defined as BSTR NameSpace, has a default value of NULL.


ObjectPath Property of WMI Object Viewer Container

The ObjectPath property returns or sets the WMI object path of the object or class you want to view. This property, which is defined as VARIANT ObjectPath, is an array of BSTRs (a VARIANT of type VT_ARRAY | VT_BSTR).

A Get operation returns the object path of type VARIANT or V_BSTR. A Set operation specifies the path of the WMI object or class you want to view.

If this property is NULL or invalid, the control returns an error.


ReadyState Property of WMI Object Viewer Container

The ReadyState property indicates the current state of readiness of a control during a potentially asynchronous download process. This property, which is defined as long ReadyState, cannot be set.

The ReadyState property can have one of the following values.

Value |  | Description
0 | READYSTATE_UNINITIALIZED | Indicates that the control is not initialized. This is the default initialization state.
1 | READYSTATE_LOADING | Indicates that the control is currently loading its properties.
2 | READYSTATE_LOADED | Indicates that the control has been initialized.
3 | READYSTATE_INTERACTIVE | Indicates that the control has enough data to be interactive, but asynchronous data is not completely loaded.
4 | READYSTATE_COMPLETE | Indicates that the control has all of its data. Currently, this is the only value returned by the control.


StatusCode Property of WMI Object Viewer Container

The StatusCode property stores the most recent status code when an object path is selected. This property is defined as long StatusCode.


StudioModeEnabled Property of WMI Object Viewer Container

The StudioModeEnabled property determines the access level for a specified class. If set to TRUE, the class can be edited. If set to FALSE, the class can only be browsed. If the property is NULL or invalid, the control returns an error.


WMI Object Viewer Container Methods

This section contains methods for the WMI Object Viewer Container control.


QueryViewInstances Method of WMI Object Viewer Container

The QueryViewInstances method displays the instances returned by a query.

void QueryViewInstances(
  BSTR szTitle,
  BSTR szQueryType,
  BSTR szQuery,
  BSTR szClass
);

Parameters

szTitle
Label for display purposes.
szQueryType
Specify either WQL or SQL.
szQuery
The actual query syntax.
szClass
Optional, specify a result class.

Return Values

Nothing.


SaveState Method of WMI Object Viewer Container

The SaveState method saves any WMI objects that have been modified.

long SaveState(
  long bPromptUser,
  long bUserCanCancel
);

Parameters

If any of the following parameters is null or invalid, the control returns an error.

bPromptUser
Set to True if the user will be prompted to save the state. Set to False if the state will be automatically saved without prompting the user.
bUserCanCancel
Set to True if the user will be able to cancel the operation. Set to False if the user will not be able to cancel the operation.

Return Values

Returns S_OK if the state is successfully saved. Returns E_FAIL if the state is not saved or if the user cancels the operation.


ShowInstances Method of WMI Object Viewer Container

The ShowInstances method shows a multiple instance view of the instances specified by the array of object paths.

void ShowInstances(
  BSTR szTitle,
  VARIANT varPathArray
);

Parameters

szTitle
The view title.
varPathArray
The WMI paths to the instances.

If any of these parameters is NULL or invalid, the control returns an error.

Return Values

This method has no return values.


WMI Object Viewer Container Events

This section contains events of the WMI Object Viewer Container control.


GetIWbemServices Event of WMI Object Viewer Container

The GetIWbemServices event occurs when the control wants to connect to a namespace. This event retrieves an IWbemServices pointer for the current namespace and object path.

void GetIWbemServices(
  BSTR lpctstrNamespace,
  VARIANT *pvarUpdatePointer,
  VARIANT *pvarServices,
  VARIANT *pvarSC,
  VARIANT *pvarUserCancel
);

Parameters

lpctstrNamespace
Namespace to connect to.
pvarUpdatePointer
Tells dll to get new pointer.
pvarServices
Services pointer returned.
pvarSC
S_OK on success or failure code.
pvarUserCancel
Tells the control if user canceled.

See Also

IWbemServices


NOTIFYChangeRootOrNamespace Event of WMI Object Viewer Container

The NOTIFYChangeRootOrNamespace event notifies the container when the user has changed the root or the namespace.

void NOTIFYChangeRootOrNamespace(
  BSTR szRootOrNamespace,
  long bChangeNamespace,
  long bEchoSelectObject
);

Parameters

If any of the following parameters is null or invalid, the control returns an error.

szRootOrNamespace
The path to the new root or namespace.
bChangeNamespace
If szRootOrNamespace contains a namespace path, this value is True. If szRootOrNamespace contains a root path, this value is False.
bEchoSelectObject
If the code that catches this event should fire back an event to select an object and thus replacing the current selection in the WMI Object Viewer, this contains the value True.


RequestUIActive Event of WMI Object Viewer Container

The RequestUIActive event occurs when the control wants to go UI active and may be embedded in an ActiveX control.

void RequestUIActive();

Parameters

This event has no parameters.


WMI Utility Classes

[This is preliminary documentation and subject to change.]

For reference material on CHString, CHstringArray, and TRefPointerCollection, see the following sections:

  • CHString Class Reference
  • CHStringArray Class Reference
  • TRefPointerCollection Class Reference


CHString Class Reference

[This is preliminary documentation and subject to change.]

The following table lists the CHString member functions and operators.

Member Function | Description
AllocSysString | Allocates a BSTR from CHString data.
CHString | Constructs CHString objects in various ways.
Collate | Compares two strings (case sensitive, uses locale-specific information).
Compare | Compares two strings (case sensitive).
CompareNoCase | Compares two strings (case insensitive).
Empty | Forces a string to have 0 length.
Find | Finds a character or substring inside a larger string.
FindOneOf | Finds the first matching character from a set.
Format | Formats the string as sprintf does.
FormatMessageW | Formats a message string.
FormatV | Formats the string as vsprintf does.
FreeExtra | Removes any overhead of this string object by freeing any extra memory previously allocated to the string.
GetAllocLength | Returns the size of the string buffer.
GetAt | Returns the character at a given position.
GetBuffer | Returns a pointer to the characters in the CHString.
GetBufferSetLength | Returns a pointer to the characters in the CHString, truncating to the specified length.
GetLength | Returns the number of Unicode characters in a CHString object.
IsEmpty | Tests whether a CHString object contains no characters.
Left | Extracts the left part of a string (like the Basic LEFT$ function).
LoadStringW | Loads an existing CHString object from a resource file.
LockBuffer | Disables reference counting and protects the string in the buffer.
MakeLower | Converts all the characters in this string to lowercase characters.
MakeReverse | Reverses the characters in this string.
MakeUpper | Converts all the characters in this string to uppercase characters.
Mid | Extracts the middle part of a string (like the Basic MID$ function).
Operator LPCWSTR | Directly accesses characters stored in a CHString object as a C-style string.
Operator [] | Returns the character at a given position—operator substitution for GetAt.
Operator = | Assigns a new value to a CHString object.
Operator + | Concatenates two strings and returns a new string.
Operator += | Concatenates a new string to the end of an existing string.
Operator == <, etc. | Comparison operators (case sensitive).
ReleaseBuffer | Releases control of the buffer returned by GetBuffer.
ReverseFind | Finds a character inside a larger string; starts from the end.
Right | Extracts the right part of a string (like the Basic RIGHT$ function).
SetAt | Sets a character at a given position.
SpanIncluding | Extracts a substring that contains only the characters in a set.
SpanExcluding | Extracts a substring that contains only the characters not in a set.
TrimLeft | Trim leading whitespace characters from the string.
TrimRight | Trim trailing whitespace characters from the string.
UnlockBuffer | Enables reference counting and releases the string in the buffer.


CHString::AllocSysString

[This is preliminary documentation and subject to change.]

The AllocSysString member function allocates a new OLE Automation–compatible string of the type BSTR and copies the contents of the CHString object into it, including the terminating NULL character.

BSTR AllocSysString ( ) const
throw( CHeap_Exception );

Parameters

This function has no parameters.

Return Values

If the AllocSysString function is successful, it points to the newly allocated string.

Example

The following example demonstrates the use of CHString::AllocSysString.

CHString str( L"Hockey is Best!" );
BSTR bstr = str.AllocSysString();

// bstr now contains "Hockey is best", and can be
// passed to any OLE function requiring a BSTR.
// Normally, the function receiving the BSTR will
// free the string when it is done using it.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.


CHString::CHString

[This is preliminary documentation and subject to change.]

Each of these constructors initializes a new CHString object with the specified data.

CHString( );

CHString(
const CHString& stringSrc
);

CHString(
  WCHAR ch,
  int nRepeat = 1 )
throw( CHeap_Exception );

CHString(
  LPCWSTR lpch,
  int nLength )
throw( CHeap_Exception );

CHString(
  const unsigned char* psz
);

CHString(
  LPCWSTR lpsz )
throw( CHeap_Exception );

CHString(
  LPCSTR lpsz )
throw( CHeap_Exception );

Parameters

stringSrc
Existing CHString object that is copied into this CHString object.
ch
Single character that is repeated nRepeat times.
nRepeat
Repeat count for ch.
lpch
Pointer to an array of characters of length nLength.
nLength
Count of the number of characters in lpch.
psz
Null-terminated string that is copied into this CHString object.
lpsz
A null-terminated string that is copied into this CHString object.

Remarks

Because the constructors copy the input data into new allocated storage, you should be aware that memory exceptions may result. Some of these constructors act as conversion functions; this approach lets you substitute, for example, an LPWSTR where a CHString object is expected.

  • Several forms of the constructor have special purposes
  • CHString( LPCSTR lpsz ) Constructs a Unicode CHString from an ANSI string.
  • CHString( LPCWSTR lpsz ) Constructs a CHString from a Unicode string.
  • CHString( const unsigned char* psz ) Lets you construct a CHString from a pointer to unsigned char.

Example

The following example demonstrates the use of CHString::CHString.

CHString s1;                    // Empty string
CHString s2( L"cat" );          // From a C string literal
CHString s3 = s2;               // Copy constructor
CHString s4( s2 + " " + s3 );   // From a string expression

CHString s5( 'x' );             // s5 = "x"
CHString s6( 'x', 6 );          // s6 = "xxxxxx"

CHString city = L"Philadelphia"; // NOT the assignment operator

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.


CHString::Collate

[This is preliminary documentation and subject to change.]

The Collate member function uses the wcscoll function to compare a CHString object with another string.

int Collate(
  LPCWSTR lpsz
) const;

Parameters

lpsz
The other string used for comparison.

Return Values

The Collate member function returns the following values.

Value | Description
0 | The strings are identical (ignoring case).
< 0 | The CHString object is less than lpsz.
> 0 | The CHString object is greater than lpsz.

Remarks

The wcscoll function performs a case-sensitive comparison of the strings according to the code page currently in use.

Example

CHString str1 = L"co-op";
CHString str2 = L"con";

int n;

// collation uses language rules, such as ignoring dashes
n = str1.Collate(str2);
assert(n > 0);

// comparison is a strict ASCII comparison with no language rules
n = str1.Compare(str2);
assert(n < 0);

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.

See Also

CHString::Compare, CHString::CompareNoCase


CHString::Compare

[This is preliminary documentation and subject to change.]

The Compare member function uses the wcscmp function to compare this CHString object with another string.

int Compare(
  LPCWSTR lpsz
) const;

Parameters

lpsz
The other string used for comparison.

Return Values

The Compare member function returns the following values.

Value | Description
0 | The strings are identical.
< 0 | The CHString object is less than lpsz.
> 0 | The CHString object is greater than lpsz.

Remarks

The wcscmp function, which performs a case-sensitive comparison of the strings, is not affected by locale.

Example

The following example demonstrates the use of CHString::Compare.

CHString s1( L"abc" );
CHString s2( L"ABC" );

assert( s1.Compare( s2 ) > 0 ); // Compare with another CHString.
assert( s1.Compare( L"abc" ) == 0 ); // Compare with LPCWSTR string.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.

See Also

CHString::CompareNoCase, CHString::Collate


CHString::CompareNoCase

[This is preliminary documentation and subject to change.]

The CompareNoCase member function uses the _wcsicmp function to compare a CHString object with another string.

int CompareNoCase(
  LPCWSTR lpsz
) const;

Parameters

lpsz
The other string used for comparison.

Return Values

The CompareNoCase member function returns the following values.

Value | Description
0 | The strings are identical (ignoring case).
< 0 | The CHString object is less than lpsz (ignoring case).
> 0 | The CHString object is greater than lpsz (ignoring case).

Remarks

The _wcsicmp function, which performs a case-insensitive comparison of the strings, is not affected by locale.

Example

The following example demonstrates the use of CHString::CompareNoCase.

CHString s1( L"abc" );
CHString s2( L"ABD" );

assert( s1.CompareNoCase( s2 ) == 0 ); // Compare with a CHString.
assert( s1.CompareNoCase( L"ABE" ) < 0 ); // Compare with LPCWSTR string.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.

See Also

CHString::Compare, CHString::Collate


CHString Comparison Operators

[This is preliminary documentation and subject to change.]

The CHString comparison operators compare two strings. These operators are a convenient substitute for the case-sensitive Compare member function.

BOOL operator ==( const CHString& s1, const CHString& s2 );
BOOL operator ==( const CHString& s1, LPCWSTR s2 );
BOOL operator !=( const CHString& s1, const CHString& s2 );
BOOL operator !=( const CHString& s1, LPCWSTR s2 );
BOOL operator <( const CHString& s1, const CHString& s2 );
BOOL operator <( const CHString& s1, LPCWSTR s2 );
BOOL operator >( const CHString& s1, const CHString& s2 );
BOOL operator >( const CHString& s1, LPCWSTR s2 );
BOOL operator <=( const CHString& s1, const CHString& s2 );
BOOL operator <=( const CHString& s1, LPCWSTR s2 );
BOOL operator >=( const CHString& s1, const CHString& s2 );
BOOL operator >=( const CHString& s1, LPCWSTR s2 );

Parameters

s1, s2
CHString objects that are compared.

Return Values

Returns a nonzero value if the strings meet the comparison condition; otherwise 0 is returned.

Example

The following example demonstrates the use of CHString Comparison Operators.

CHString s1( L"abc" );
CHString s2( L"abd" );
assert( s1 < s2 ); // Operator is overloaded for both.
assert( L"ABC" < s1 ); // CHString and char*
assert( s2 > L"abe" );

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.


CHString::Empty

[This is preliminary documentation and subject to change.]

The Empty member function makes the CHString object an empty string and frees memory as appropriate.

void Empty( );

Parameters

This function has no parameters.

Example

The following example demonstrates the use of CHString::Empty.

CHString s( L"abc" );
s.Empty();
assert( s.GetLength( ) == 0 );

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.

See Also

CHString::IsEmpty


CHString::Find

[This is preliminary documentation and subject to change.]

The Find member function searches a string for the first match of a substring.

int Find(
 WCHAR ch ) const;

int Find(
  LPCWSTR lpszSub ) const;

Parameters

ch
A single character that the function searches for.
lpszSub
A substring that the function searches for.

Return Values

If the Find member function is successful, it returns the zero-based index of the first character in this CHString object that matches the requested substring or characters. If the substring or character is not found, the function returns a value of -1.

Remarks

The Find function is overloaded to accept both single characters (similar to the runtime function, wcschr) and strings (similar to the runtime function, wcsstr).

Example

The following example demonstrates the use of CHString::Find.

CHString s( L"abcdef" );
assert( s.Find( 'c' ) == 2 );
assert( s.Find( L"de" ) == 3 );

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.

See Also

CHString::ReverseFind, CHString::FindOneOf


CHString::FindOneOf

[This is preliminary documentation and subject to change.]

The FindOneOf member function searches a string for the first character that matches any character contained in lpszCharSet.

int FindOneOf(
  LPCWSTR lpszCharSet ) const;

Parameters

lpszCharSet
String containing characters used in the matching operation.

Return Values

Returns the zero-based index of the first character in the string that is also in lpszCharSet. If there is no match, the function returns a value of -1.

Example

The following example demonstrates the use of CHString::FindOneOf.

CHString s( L"abcdef" );
assert( s.FindOneOf( L"xd" ) == 3 ); // 'd' is first match

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.

See Also

CHString::Find


CHString::Format

[This is preliminary documentation and subject to change.]

The Format member function formats and stores a series of characters and values in a CHString.

void Format(
  LPCWSTR lpszFormat, ... )
throw ( CHeap_Exception );

void Format(
  UINT nFormatID, ... )
throw ( CHeap_Exception );

Parameters

lpszFormat
Format-control string.
nFormatID
String resource identifier that contains the format control string.

Remarks

This function writes formatted data to a CHString in the same way that sprintf formats data into a C-style character array. Each optional argument (if any) is converted and output according to the corresponding format specification in lpszFormat or from the string resource identified by nFormatID.

If the string object is offered as a parameter to Format, the call will fail . For example, the following code will cause unpredictable results.

CHString str = L"Some Data";
str.Format(L"%s%d", str, 123);   // Attention: str is also used in the parameter list.

Note When you pass a character string as an optional argument, you must cast it explicitly as LPCWSTR. The format argument has the same form and function as the format argument for the printf function. A NULL character is appended to the end of the written characters.

Example

The following example demonstrates the use of CHString::Format.

CHString str;

str.Format(L"Floating point: %.2f\n", 12345.12345);
printf("%S", (LPCWSTR) str);

str.Format(L"Left-justified integer: %d\n", 35);
printf("%S", (LPCWSTR) str);

str.Format(IDS_SCORE, 5, 3);
printf("%S", (LPCWSTR) str);

If the application has a string resource with the identifier IDS_SCORE and if that resource contains the string, "Penguins: %d\nFlyers : %d\n", the above code fragment produces the following output.

Floating point: 12345.12
Left-justified integer: 35
Penguins: 5
Flyers  : 3

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.

See Also

CHString::GetBuffer, CHString::FormatV


CHString::FormatMessageW

[This is preliminary documentation and subject to change.]

The FormatMessageW member function formats a message string.

void FormatMessageW(
  LPCWSTR lpszFormat, ... )
throw ( CHeap_Exception );

void FormatMessageW(
  UINT nFormatID, ... )
throw ( CHeap_Exception );

Parameters

lpszFormat
Points to the format-control string.

The control string is scanned for inserts and formatted accordingly. The format string is similar to runtime function printf-style format strings, except that the latter allows the parameters to be inserted in an arbitrary order.

nFormatID
The string resource identifier that contains the unformatted message text.

Remarks

The function requires a message definition as input. The message definition is determined by lpszFormat or from the string resource identified by nFormatID. The function copies the formatted message text to the CHString, processing any embedded insert sequences if requested.

Each insert must have a corresponding parameter that follows the lpszFormat or nFormatID parameter. Within the message text, several escape sequences are supported for dynamically formatting the message. For a description of these escape sequences and their meanings, see the Windows ::FormatMessage function in the Win32 SDK Programmer's Reference.

Example

The following example demonstrates the use of CHString::FormatMessageW.

CHString str;
int nAsked = 5;
int nAgree = 4;

str.FormatMessageW(L"%1!d! of %2!d! developers agree: Hockey is %3%!",
   nAgree, nAsked, L"Best");
assert(str == L"4 of 5 developers agree: Hockey is Best!");

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.

See Also

CHString::Format, CHString::LoadString


CHString::FormatV

[This is preliminary documentation and subject to change.]

The FormatV member function writes a formatted string and a variable list of arguments to a CHString object in the same way that vsprintf formats data into a C-style character array.

void FormatV(
  LPCWSTR lpszFormat,
  va_list argList
);

Parameters

lpszFormat
Format-control string.
argList
List of arguments that are passed.

Remarks

This function formats and stores a series of characters and values in the CHString. The string and arguments are converted and output according to the corresponding format specification in lpszFormat.

If the string object is offered as a parameter to FormatV, the call will fail . For example, the following code will cause unpredictable results.

CHString str = L"Some Data";
str.FormatV("%s%d", str, 123);   // Attention: str is also used in the parameter list.

Example

The following example demonstrates the use of CHString::FormatV.

//Using CHString::FormatV(), you can write functions like the following:

void WriteLogEntry(CStdioFile& refFile, LPCWSTR pstrFormat, ...)
{
   CTime timeWrite;
   timeWrite = CTime::GetCurrentTime();

   // write the time out
   CHString str = timeWrite.Format("%d %b %y %H:%M:%S - ");
   refFile.Write(str, str.GetLength());

   // format and write the data we were given
   va_list args;
   va_start(args, pstrFormat);
   str.FormatV(pstrFormat, args);
   refFile.Write(str, str.GetLength());

   // put a newline
   refFile.Write("\n", 1);
   return;
}

You can call the preceding function with any number of parameters.

   WriteLogEntry(fileLog, "Program started");
   WriteLogEntry(fileLog, "Processed %d bytes", 91341);
   WriteLogEntry(fileLog, "%d error(s) found in %d line(s)", 10, 1351);
   WriteLogEntry(fileLog, "Program completed");

Using the preceding code would generate output similar to the following.

   17 Apr 97 12:34:53 - Program started
   17 Apr 97 12:34:59 - Processed 91341 bytes
   17 Apr 97 12:35:22 - 10 error(s) found in 1351 line(s)
   17 Apr 97 12:35:23 - Program completed

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.

See Also

CHString::Format


CHString::FreeExtra

[This is preliminary documentation and subject to change.]

The FreeExtra member function frees any extra memory that was previously allocated by the string but no longer needed. This function, which reallocates the buffer to the exact length returned by GetLength, should reduce the memory overhead consumed by the string object.

void FreeExtra( ) throw ( CHeap_Exception );

Parameters

This function has no parameters.

Example

The following example demonstrates the use of CHString::FreeExtra.

void PrintLengths(CHString& str)
{
   printf("Alloc length is %d, String length is %d\n",
      str.GetAllocLength(), str.GetLength());
}

int main()
{
   // Create a CHString with 1024 characters
   CHString str('x', 1024);
   PrintLengths(str);

   // Assigning a smaller string won't cause CHString to free its
   // memory, as it assumes the string will grow again anyway.
   str = L"Hockey is Best!";
   PrintLengths(str);

   // This call forces CHString to release the extra
   // memory it doesn't need.
   str.FreeExtra();
   PrintLengths(str);

   return 0;
}

In this example, the results are a printout of the following three lines.

Alloc length is 1024, String length is 1024
Alloc length is 1024, String length is 15
Alloc length is 64, String length is  15

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.


CHString::GetAllocLength

[This is preliminary documentation and subject to change.]

The GetAllocLength member function returns the size of the allocated string buffer.

int GetAllocLength() const;

Parameters

This function has no parameters.

Return Values

The GetAllocLength member function returns an integer containing the size of the allocated string buffer.

Example

See the example for CHString::FreeExtra.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.

See Also

CHString::GetLength


CHString::GetAt

[This is preliminary documentation and subject to change.]

The GetAt member function returns a single character specified by an index number.

WCHAR GetAt(
  int nIndex
) const;

Parameters

nIndex
Zero-based index of the character in the CHString object.

The nIndex parameter must be greater than or equal to 0 and less than the value returned by GetLength. The Debug version of the CHString Library validates the bounds of nIndex; the Release version does not.

Return Values

Returns a WCHAR containing the character at the specified position in the string.

Remarks

You can think of a CHString object as an array of characters.

The overloaded subscript ([]) operator is a convenient alias for GetAt.

Example

The following example demonstrates the use of CHString::GetAt.

CHString s( L"abcdef" );
assert( s.GetAt(2) == 'c' );

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.

See Also

CHString::GetLength, CHString::operator[]


CHString::GetBuffer

[This is preliminary documentation and subject to change.]

The GetBuffer member function returns a pointer to the internal character buffer for the CHString object.

LPWSTR GetBuffer(
  int nMinBufLength );
throw( CHeap_Exception );

Parameters

nMinBufLength
The minimum size of the character buffer in characters. This value does not include space for a null terminator.

Return Values

An LPWSTR pointer to the object's (null-terminated) character buffer.

Remarks

The returned LPWSTR is not const and therefore allows direct modification of CHString contents.

If you use the pointer returned by GetBuffer to change the string contents, you must call ReleaseBuffer before using any other CHString member functions.

After a call to ReleaseBuffer, the address returned by GetBuffer may not be valid because additional CHString operations can cause the CHString buffer to be reallocated. If you do not change the length of the CHString, the buffer will not be reallocated. The buffer memory will be freed automatically when the CHString object is destroyed.

Note that if you keep track of the string length yourself, you should not append the terminating NULL character. You must, however, specify the final string length when you release the buffer with ReleaseBuffer. If you do append a terminating NULL character, you should pass –1 for the length to ReleaseBuffer, which will call wcslen on the buffer to determine its length.

Example

The following example demonstrates the use of CHString::GetBuffer.

CHString s( L"abcd" );

printf("CHString s %S", (LPCWSTR)s);
LPWSTR p = s.GetBuffer( 10 );
wcscpy( p, L"Hello" );   // directly access CHString buffer
s.ReleaseBuffer( );
printf("CHString s %S", (LPCWSTR)s);

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.

See Also

CHString::GetBufferSetLength, CHString::ReleaseBuffer


CHString::GetBufferSetLength

[This is preliminary documentation and subject to change.]

The GetBufferSetLength member function returns a pointer to the internal character buffer for the CHString object, truncating or growing its length if necessary to exactly match the length specified in nNewLength.

LPWSTR GetBufferSetLength(
  int nNewLength )
throw( CHeap_Exception );

Parameters

nNewLength
Exact size of the CHString character buffer, measured in characters.

Return Values

Returns an LPWSTR pointer to the object's (null-terminated) character buffer.

Remarks

The returned LPWSTR pointer, which is not const, allows direct modification of CHString contents.

If you use the pointer returned by GetBuffer to change the string contents, you must call ReleaseBuffer before using any other CHString member functions.

After a call to ReleaseBuffer, the address returned by GetBufferSetLength may not be valid because additional CHString operations may cause the CHString buffer to be reallocated. If you do not change the length of the CHString object, the buffer will not be reassigned. The buffer memory will be freed automatically when the CHString object is destroyed.

Note that if you keep track of the string length yourself, you should not append the terminating NULL character. You must, however, specify the final string length when you release the buffer with ReleaseBuffer. If you do append a terminating NULL character when you call ReleaseBuffer, you should pass –1 (the default) for the length. ReleaseBuffer will perform a wcslen on the buffer to determine its length.

Example

The following example demonstrates the use of CHString::GetBufferSetLength.

CHString str;
LPWSTR pstr = str.GetBufferSetLength(3);
pstr[0] = 'I';
pstr[1] = 'c';
pstr[2] = 'e';

// No need for trailing zero or call to ReleaseBuffer()
// because GetBufferSetLength() set it for us!

str += " hockey is best!";
printf( "str: %S\n", (LPCWSTR)str );

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.

See Also

CHString::GetBuffer, CHString::ReleaseBuffer


CHString::GetLength

[This is preliminary documentation and subject to change.]

The GetLength member function gets a count of the number of wide characters in this CHString object. The count does not include a NULL terminator.

int GetLength( ) const;

Parameters

This function has no parameters.

Return Values

Returns a count of the number of wide characters in the string, not the number of bytes.

Example

The following example demonstrates the use of CHString::GetLength.

CHString s( L"abcdef" );
assert( s.GetLength() == 6 );

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.


CHString::IsEmpty

[This is preliminary documentation and subject to change.]

The IsEmpty member function tests a CHString object for the empty condition.

BOOL IsEmpty( ) const;

Parameters

This function has no parameters.

Return Values

If the CHString object has a length of zero, the IsEmpty member function returns a nonzero value. If the CHString object has a nonzero length, the function returns zero.

Example

The following example demonstrates the use of CHString::IsEmpty.

CString s;
assert( s.IsEmpty() );

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.


CHString::Left

[This is preliminary documentation and subject to change.]

The Left member function extracts the first (that is, leftmost) nCount characters from a CHString object and returns a copy of the extracted substring. If nCount exceeds the string length, then the entire string is extracted.

CHString Left(
  int nCount ) const
throw( CHeap_Exception );

Parameters

nCount
The number of characters extracted from the CHString object.

Return Values

Returns a CHString object containing a copy of the specified range of characters. Note that the returned CHString object may be empty.

Example

The following example demonstrates the use of CHString::Left.

CHString s( L"abcdef" );
assert( s.Left(2) == L"ab" );

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.

See Also

CHString::Mid, CHString::Right


CHString::LoadStringW

[This is preliminary documentation and subject to change.]

The LoadStringW member function reads a Windows string resource (identified by nID) into an existing CHString object.

BOOL LoadStringW(
  UINT nID )
throw( CHeap_Exception );

Parameters

nID
Windows string resource identifier.

Return Values

If the LoadStringW function is successful, the resource string is loaded into the CHString object, and the function returns a nonzero value. If the function is unsuccessful, it returns zero.

Example

The following example demonstrates the use of CHString::LoadStringW.

// Assumes a resource file has been created with a string table
// containing IDS_MYSTRING, which has a value of "Hockey is best".
CHString s;

if (! s.LoadStringW( IDS_MYSTRING) )
{
    printf("Error Loading String: IDS_MYSTRING");
}
else
{
    printf("IDS_MYSTRING resource load: %S", (LPCWSTR)s );
}

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.


CHString::LockBuffer

[This is preliminary documentation and subject to change.]

The LockBuffer member function locks a string in the buffer.

LPWSTR LockBuffer( );

Parameters

This function has no parameters.

Return Values

Returns a pointer to a CHString object or a NULL-terminated string.

Remarks

By calling LockBuffer, you create a copy of the string and then set the reference count to -1. When the reference count is set to -1, the string in the buffer is considered to be in a locked state, which protects the string in two ways.

  • No other string can get a reference to the data in the locked string, even if that string is assigned to the locked string.
  • The locked string will never reference another string, even if that other string is copied to the locked string.

By locking the string in the buffer, you ensure that the string's exclusive hold on the buffer will remain intact.

After you have finished with LockBuffer, call UnlockBuffer to reset the reference count to 1.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.

See Also

CHString::UnlockBuffer


CHString::MakeLower

[This is preliminary documentation and subject to change.]

The MakeLower member function converts a CHString object to a lowercase string.

void MakeLower( )
throw (CHeap_Exception );

Parameters

This function has no parameters.

Example

The following example demonstrates the use of CHString::MakeLower.

CHString s( L"ABC" );
s.MakeLower();
assert( s == L"abc" );

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.

See Also

CHString::MakeUpper


CHString::MakeReverse

[This is preliminary documentation and subject to change.]

The MakeReverse member function reverses the order of the characters in a CString object.

void MakeReverse( )
throw ( CHeap_Exception );

Parameters

This function has no parameters.

Example

The following example demonstrates the use of CHString::MakeReverse.

CHString s( L"abc" );
s.MakeReverse();
assert( s == L"cba" );

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.


CHString::MakeUpper

[This is preliminary documentation and subject to change.]

The MakeUpper member function converts a CHString object to an uppercase string.

void MakeUpper( )
throw ( CHeap_Exception );

Parameters

This function has no parameters.

Example

The following example demonstrates the use of CHString::MakeUpper.

CHString s( L"abc" );
s.MakeUpper();
assert( s == L"ABC" );

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.

See Also

CHString::MakeLower


CHString::Mid

[This is preliminary documentation and subject to change.]

The Mid member function extracts a substring of length nCount characters from a CHString object, starting at position nFirst (zero-based). The function returns a copy of the extracted substring.

CHString Mid(
  int nFirst ) const
throw( CHeap_Exception );

CHString Mid(
  int nFirst,
  int nCount ) const
throw( CHeap_Exception );

Parameters

nFirst
The zero-based index of the first character in this CHString object that is to be included in the extracted substring.
nCount
The number of characters to extract from this CHString object. If this parameter is not supplied, then the remainder of the string is extracted.

Return Values

Returns a CHString object that contains a copy of the specified range of characters. The returned CHString object may be empty.

Remarks

The Mid function is similar to the Basic MID$ function except in the latter, indexes are zero-based.

Example

The following example demonstrates the use of CHString::Mid.

CHString s( L"abcdef" );
assert( s.Mid( 2, 3 ) == L"cde" );

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.

See Also

CHString::Left, CHString::Right


CHString::operator []

[This is preliminary documentation and subject to change.]

The overloaded subscript ([]) operator returns a single character specified by the zero-based index in nIndex. This operator is a convenient substitute for the GetAt member function.

WCHAR operator [](
  int nIndex
) const;

Parameters

nIndex
Zero-based index of a character in the string.

Remarks

Important You can use the subscript ([]) operator to get the value of a character in a CHString, but you cannot use it to change the value of a character in a CHString.

Example

The following example demonstrates the use of CHString::operator [ ].

CHString s( L"abc" );
assert( s[1] == 'b' );

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.

See Also

CHString::GetAt


CHString::operator +

[This is preliminary documentation and subject to change.]

The + concatenation operator joins two strings and returns a CHString object.

friend CHString operator +(
  const CHString& string1,
  const CHString& string2 )
throw( CHeap_Exception );

friend CHString operator +(
  const CHString& string,
  WCHAR ch )
throw( CHeap_Exception );

friend CHString operator +(
  WCHAR ch,
  const CHString& string )
throw( CHeap_Exception );

friend CHString operator +(
  const CHString& string,
  LPCWSTR lpsz )
throw( CHeap_Exception );

friend CHString operator +(
  LPCWSTR lpsz,
  const CHString& string )
throw( CHeap_Exception );

friend CHString operator +(
  const CHString& string,
  char ch )
throw( CHeap_Exception );

friend CHString operator +(
  char ch,
  const CHString& string )
throw( CHeap_Exception );

Parameters

string, string1, string2
CHString objects that are concatenated.
ch
A character that concatenates to a string or a string that concatenates to a character..
lpsz
A pointer to a null-terminated character string.

Return Values

A CHString object that is the temporary result of the concatenation. This return value makes it possible to combine several concatenations in the same expression.

Remarks

One of the two argument strings must be a CHString object; the other can be a character pointer or a character. Be aware that memory exceptions may occur whenever you use the concatenation operator because new storage may be allocated to hold temporary data.

Example

The following example demonstrates the use of CHString::operator +.

CHString s1( L"abc" );
CHString s2( L"def" );
assert( (s1 + s2 ) == L"abcdef" );

CHString s3;
s3 = CHString( L"abc" ) + "def" ; // Correct
s3 = "abc" + "def"; // Wrong! The first argument must be a CHString.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.


CHString::operator +=

[This is preliminary documentation and subject to change.]

The += concatenation operator joins characters to the end of this string. The operator accepts another CHString object, a character pointer, or a single character.

const CHString& operator +=(
  const CHString& string )
throw( CHeap_Exception );

const CHString& operator +=(
  WCHAR ch )
throw( CHeap_Exception );

const CHString& operator +=(
  LPCWSTR lpsz )
throw( CHeap_Exception );

const CHString operator +=(
  char ch )
throw( CHeap_Exception );

Parameters

string
A CHString that concatenates to this string.
ch
A character to concatenate to this string.
lpsz
A pointer to a null-terminated string to concatenate to this string.

Remarks

Be aware that memory exceptions may occur whenever you use this concatenation operator because new storage may be allocated for characters added to this CHString object.

Example

The following example demonstrates the use of CHString::operator +=.

CHString s( L"abc" );
assert( ( s += L"def" ) == L"abcdef" );

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.


CHString::operator =

[This is preliminary documentation and subject to change.]

The CHString assignment (=) operator reinitializes an existing CHString object with new data.

const CHString& operator =(
  const CHString& stringSrc )
throw( CHeap_Exception );

const CHString& operator =(
  WCHAR ch )
throw( CHeap_Exception );

const CHString& operator =(
  const unsigned char* psz )
throw( CHeap_Exception );

const CHString& operator =(
  LPCWSTR lpsz )
throw( CHeap_Exception );

const CHString& operator =(
  LPCSTR lpsz )
throw( CHeap_Exception );

const CHString& operator =(
  CHString *p )
throw( CHeap_Exception );

const CHString& operator =(
  char ch )
throw( CHeap_Exception );

Parameters

This operator has no parameters.

Remarks

If the destination string (that is, the left side) is already large enough to store the new data, no new memory allocation is performed. However, be aware that memory exceptions may occur whenever you use the assignment operator because new storage is often allocated to hold the resulting CHString object.

Example

The following example demonstrates the use of CHString::operator =.

CHString s1, s2;        // Empty CHString objects

s1 = L"cat";            // s1 = "cat"
s2 = s1;               // s1 and s2 each = "cat"
s1 = L"the " + s1;      // Or expressions
s1 = 'x';              // Or just individual characters

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.

See Also

CHString::CHString


CHString::operator LPCWSTR

[This is preliminary documentation and subject to change.]

The LPCWSTR conversion operator provides an efficient method to access the null-terminated C string contained in a CHString object.

operator LPCWSTR ( ) const;

Parameters

This operator has no parameters.

Return Values

Returns a character pointer to the string's data.

Remarks

No characters are copied; only a pointer is returned. Use this operator carefully. If you change a CHString object after you obtain the character pointer, you may cause a reallocation of memory that invalidates the pointer.

Example

The following example demonstrates the use of CHString::operator LPCWSTR.

// If the prototype of a function is known to the compiler,
// the LPCWSTR conversion operator may be invoked implicitly

CHString strSports("Hockey is Best!");
TCHAR sz[1024];

// conversion operator implicitly invoked
wcscpy((unsigned short*)sz, strSports);

// If the prototype isn't known, or is a va_arg prototype,
// you must invoke the conversion operator explicitly. For example,
// the va_arg part of a call to wsprintf() needs the cast:

wsprintf(sz, "I think that %S\n", (LPCWSTR)strSports);

// Note that some situations are ambiguous. This line will
// put the address of the strSports object to stdout:

wcout << strSports;

// while this line will put the content of the string to stdout:

wcout << (LPCWSTR) strSports;

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.


CHString::ReleaseBuffer

[This is preliminary documentation and subject to change.]

The ReleaseBuffer member function ends the use of a buffer allocated by GetBuffer.

void ReleaseBuffer(
  int nNewLength = -1
) throw ( CHeap_Exception );

Parameters

nNewLength
The new length of the string in characters, not counting a null terminator.

If the string is null-terminated, the -1 default value sets the CHString size to the current length of the string.

Remarks

If you know that the string in the buffer is null-terminated, you can omit the nNewLength argument. If your string is not null-terminated, then use nNewLength to specify its length. The address returned by GetBuffer is invalid after the call to ReleaseBuffer or any other CHString operation.

Example

The following example demonstrates the use of CHString::ReleaseBuffer.

CHString s( L"abc" );
LPWSTR p = s.GetBuffer( 1024 );

wcscpy(p, L"abc");   // use the buffer directly
assert( s.GetLength() == 3 ); // String length = 3
s.ReleaseBuffer();  // Surplus memory released, p is now invalid.
assert( s.GetLength() == 3 ); // Length still 3

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.

See Also

CHString::GetBuffer


CHString::ReverseFind

[This is preliminary documentation and subject to change.]

The ReverseFind member function searches a CHString object for the last match of a substring. This function is similar to the runtime function, wcsrchr.

int ReverseFind(
  WCHAR ch ) const;

Parameters

ch
The character that the function searches for.

Return Values

Returns the index of the last character in the CHString object that matches the requested character. If the character is not found, the function returns a value of -1.

Example

The following example demonstrates the use of CHString::ReverseFind.

CHString s( L"abcabc" );
assert( s.ReverseFind( 'b' ) == 4 );

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.

See Also

CHString::Find, CHString::FindOneOf


CHString::Right

[This is preliminary documentation and subject to change.]

The Right member function extracts the last (that is, rightmost) nCount characters from a CHString object and returns a copy of the extracted substring. If nCount exceeds the string length, then the entire string is extracted.

CHString Right(
  int nCount ) const
throw( CHeap_Exception );

Parameters

nCount
The number of characters extracted from the CHString object.

Return Values

Returns a CHString object that contains a copy of the specified range of characters. Note that the returned CHString object may be empty.

Example

The following example demonstrates the use of CHString::Right.

CHString s( L"abcdef" );
assert( s.Right(2) == L"ef" );

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.

See Also

CHString::Mid, CHString::Left


CHString::SetAt

[This is preliminary documentation and subject to change.]

The SetAt member function overwrites a single character specified by an index number. If the index exceeds the bounds of the existing string, SetAt will not enlarge the string.

void SetAt(
  int nIndex,
  WCHAR ch
) throw ( CHeap_Exception );

Parameters

nIndex
Zero-based index of the character in the CHString object.

The nIndex parameter must be greater than or equal to 0 and less than the value returned by GetLength.

ch
The character to insert.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.

See Also

CHString::GetAt


CHString::SpanExcluding

[This is preliminary documentation and subject to change.]

The SpanExcluding member function extracts and returns all characters preceding the first occurrence of a character from lpszCharSet.

CHString SpanExcluding(
  LPCWSTR lpszCharSet ) const
throw( CHeap_Exception );

Parameters

lpszCharSet
A string interpreted as a set of characters.

Return Values

The SpanExcluding member function returns a substring that begins with the first character in the string and ends with the first character found in the string that is also in lpszCharSet.

If no character in lpszCharSet is found in the string, the function returns the entire string.

Example

The following function returns the first portion of the src param.

// Portions are delimited by a semi-colon( ; ),
//  a comma( , ), a period( . ), a dash( - ),
// or a colon( : ).

CHString GetFirstPart( CHString src)
{
    return src.SpanExcluding( L";,.- :");
}

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.

See Also

CHString::SpanIncluding


CHString::SpanIncluding

[This is preliminary documentation and subject to change.]

The SpanIncluding member function extracts characters of a string that are identified by lpszCharSet.

CHString SpanIncluding(
  LPCWSTR lpszCharSet ) const
throw( CHeap_Exception );

Parameters

lpszCharSet
A string interpreted as a set of characters.

Return Values

The SpanIncluding member function returns a substring that contains characters in the string that are in lpszCharSet.

If the first character in the string is not in the specified set, the function returns an empty substring.

Remarks

This member function starts with the first character of the string and stops when a character is found in the string but not in lpszCharSet.

Example

The following example demonstrates the use of CHString::SpanIncluding.

CHString str( L"cabbage" );
CHString res = str.SpanIncluding( L"abc" );

assert( res == L"cabba" );
res = str.SpanIncluding( L"xyz" );
assert( res.IsEmpty( ) );

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.

See Also

CHString::SpanExcluding, CHString::IsEmpty


CHString::TrimLeft

[This is preliminary documentation and subject to change.]

The TrimLeft member function trims leading whitespace characters from the string by removing new line, space, and tab characters.

void TrimLeft( )
throw ( CHeap_Exception );

Parameters

This function has no parameters.

Example

The following example demonstrates the use of CHString::TrimLeft.

In this example, the string, "\t\t ****Hockey is best!", becomes "****Hockey is best!":

CHString strBefore;
CHString strAfter;

strBefore = L"\t\t ****Hockey is best!";
strAfter = strBefore;
strAfter.TrimLeft();

printf("Before: \"%S\"\n", (LPCWSTR) strBefore);
printf("After : \"%S\"\n", (LPCWSTR) strAfter);

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.

See Also

CHString::TrimRight


CHString::TrimRight

[This is preliminary documentation and subject to change.]

The TrimRight member function trims trailing whitespace characters from the string by removing trailing newline, space, and tab characters.

void TrimRight( )
throw ( CHeap_Exception );

Parameters

This function has no parameters.

Example

The following example demonstrates the use of CHString::TrimRight.

CHString strBefore;
CHString strAfter;

strBefore = L"Hockey is Best    ";
strAfter = strBefore;
strAfter.TrimRight();
printf("Before: \"%S\"\n", (LPCWSTR) strBefore);
printf("After : \"%S\"\n\n", (LPCWSTR) strAfter);

In this example, the string containing, "Hockey is Best ", becomes "Hockey is Best".

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.

See Also

CHString::TrimLeft


CHString::UnlockBuffer

[This is preliminary documentation and subject to change.]

The UnlockBuffer member function unlocks the buffer that was previously secured by calling LockBuffer and resets the reference count to 1.

void UnlockBuffer( );

Parameters

This function has no parameters.

Remarks

The CHString destructor implies UnlockBuffer to ensure that you do not leave the buffer locked when the destructor is called.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstring.h.
Library: Use framedyn.lib.

See Also

CHString::LockBuffer


CHStringArray Class Reference

[This is preliminary documentation and subject to change.]

The following table lists the CHStringArray member functions and operators.

Member Function | Description
Add | Adds an element to the end of the array; the array grows if necessary.
Append | Appends another array to the array; the array grows if necessary.
CHStringArray | Constructs an empty array for CHString objects.
Copy | Copies another array to the array; the array grows if necessary.
ElementAt | Returns a temporary reference to the element pointer within the array.
FreeExtra | Frees all unused memory above the current upper bound.
GetAt | Returns the value at a given index.
GetData | Allows access to elements in the array. The value can be NULL.
GetSize | Gets the number of elements in the array.
GetUpperBound | Returns the largest valid index.
InsertAt | Inserts an element (or all the elements in another array) at a specified index.
Operator [] | Sets or gets the element at the specified index.
RemoveAll | Removes all the elements from this array.
RemoveAt | Removes an element at a specific index.
SetAt | Sets the value for a given index; the array is not allowed to grow.
SetAtGrow | Sets the value for a given index; the array grows if necessary.
SetSize | Sets the number of elements to be contained in this array


CHStringArray::Add

[This is preliminary documentation and subject to change.]

The Add member function adds a new element to the end of an array, growing the array by one.

int Add(
  LPCWSTR newElement
) throw ( CHeap_Exception );

Parameters

newElement
The element to be added to the array.

Return Values

If the Add member function is successful, it returns the index of the added element.

Remarks

If SetSize has been used with an nGrowBy value greater than 1, then extra memory may be allocated. However, the upper bound will increase by only one.

Example

The following example demonstrates the use of CHStringArray::Add.

    CHStringArray array;
    CHString s( L"String 2");

    array.Add( L"String 1" ); // Element 0
    array.Add( s );           // Element 1

The above code fragment produces the following results:

    [0] = String 1
    [1] = String 2

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstrarr.h; include chstrarr.h and chstring.h.
Library: Use framedyn.lib.

See Also

CHStringArray::Append, CHStringArray::Copy


CHStringArray::Append

[This is preliminary documentation and subject to change.]

The Append member function adds the contents of another array to the end of the given array.

int Append(
  const CHStringArray& src
) throw ( CHeap_Exception );

Parameters

src
Source of the elements to be appended to the array.

Return Values

If the Append member function is successful, it returns the index of the first appended element.

Remarks

If necessary, Append may allocate extra memory to accommodate the elements appended to the array.

Example

The following example demonstrates the use of CHStringArray::Append.

CHStringArray myArray1, myArray2;
int idx, size;

// Add elements to the second array.
myArray2.Add( L"String 2" );
myArray2.Add( L"String 3" );

// Add elements to the first array and also append the second array.
myArray1.Add( L"String 1" );
myArray1.Append( myArray2 );

size = myArray1.GetSize();
for (idx=0; idx<size; idx++)
   printf("[%d]: %S\n", idx, myArray1[idx]);

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstrarr.h; include chstrarr.h and chstring.h.
Library: Use framedyn.lib.

See Also

CHStringArray::Add, CHStringArray::Copy


CHStringArray::CHStringArray

[This is preliminary documentation and subject to change.]

The CHStringArray constructor constructs an empty CHStringArray array.

CHStringArray( );

Parameters

This function has no parameters.

Example

The following example demonstrates the use of CHStringArray::CHStringArray.

//Array with default blocksize
CHStringArray array;

//Array on the heap with default blocksize
CHStringArray* pArray = new CHStringArray;

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstrarr.h; include chstrarr.h and chstring.h.
Library: Use framedyn.lib.


CHStringArray::Copy

[This is preliminary documentation and subject to change.]

The Copy member function overwrites the elements of the given array with the elements of another array.

void Copy(
  const CHStringArray& src
) throw ( CHeap_Exception );

Parameters

src
Source of the elements to be copied to the array.

Remarks

Copy does not free memory, but it will allocate extra memory to accommodate the elements copied to the array.

Example

The following example demonstrates the use of CHStringArray::Copy.

CHStringArray a1, a2;
int idx, size;

a1.Add( L"String 1" );
a1.Add( L"String 2" );
a2.Add( L"String 5" );

size = a1.GetSize();
for (idx=0; idx<size; idx++)
   printf("[%d]: %S\n", idx, a1[idx]);

a1.Copy(a2);
size = a1.GetSize();
for (idx=0; idx<size; idx++)
   printf("[%d]: %S\n", idx, a1[idx]);

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstrarr.h; include chstrarr.h and chstring.h.
Library: Use framedyn.lib.

See Also

CHStringArray::Append, CHStringArray::Add


CHStringArray::ElementAt

[This is preliminary documentation and subject to change.]

The ElementAt member function returns a temporary reference to the element pointer within the array.

CHString& ElementAt(
  int nIndex
);

Parameters

nIndex
An integer index that is greater than or equal to 0 and less than or equal to the value returned by GetUpperBound.

Return Values

If the ElementAt member function is successful, it returns a reference to the CHString at the nIndex position in the CHStringArray.

Remarks

Use this function to implement the left-side assignment operator for arrays. This is an advanced function, which you should use only to implement special array operators.

Example

See the example for CHStringArray::GetSize.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstrarr.h; include chstrarr.h and chstring.h.
Library: Use framedyn.lib.

See Also

CHStringArray::GetAt, CHStringArray::SetAt, CHStringArray::GetData


CHStringArray::FreeExtra

[This is preliminary documentation and subject to change.]

The FreeExtra member function frees any extra memory that was allocated while the array was grown. This function has no effect on the size or upper bound of the array.

void FreeExtra() throw ( CHeap_Exception );

Parameters

This function has no parameters.

Example

See the example for CHStringArray::GetData.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstrarr.h; include chstrarr.h and chstring.h.
Library: Use framedyn.lib.

See Also

CHStringArray::RemoveAll


CHStringArray::GetAt

[This is preliminary documentation and subject to change.]

The GetAt member function gets the array element at the specified index.

CHString GetAt(
  int nIndex
) const;

Parameters

nIndex
An integer index that is greater than or equal to 0 and less than or equal to the value returned by GetUpperBound.

Return Values

If the GetAt member function is successful, it returns the CHString pointer element currently at this index.

Remarks

Passing a negative value or a value greater than the value returned by GetUpperBound will result in a failed assertion for debug builds.

Example

The following example demonstrates the use of CHStringArray::GetAt.

CHStringArray array;

array.Add( L"String 1" ); // Element 0
array.Add( L"String 2" ); // Element 1
assert( array.GetAt( 0 ) == "String 1" );

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstrarr.h; include chstrarr.h and chstring.h.
Library: Use framedyn.lib.

See Also

CHStringArray::Add, CHStringArray::SetAt, CHStringArray::operator [], CHStringArray::ElementAt, CHStringArray::GetData


CHStringArray::GetData

[This is preliminary documentation and subject to change.]

The GetData member function gains direct access to the elements in the array.

const CHString* GetData() const;

CHString* GetData();

Parameters

This function has no parameters.

Return Values

If the GetData member function is successful, it returns a pointer to the array of CHString pointers.

Remarks

If no elements are available, GetData returns a NULL value.

Although direct access to the elements of an array can help you work more quickly, use caution when calling GetData; any errors you make directly affect the elements of your array.

Example

The following example demonstrates the use of CHString::GetData.

CHStringArray myArray;
int idx, size;
char buf[5];

// Allocate memory for at least 32 elements.
myArray.SetSize(32, 128);
size = myArray.GetSize();

// Add elements to the array.
CHString *ppStrings = myArray.GetData();
for (idx=0; idx<size; idx++)
   ppStrings[idx] = CHString( L"String" ) + _itoa(idx, buf, 10);

// Print the elements of the array
for (idx=0; idx<size; idx++)
   printf("[%d]: %S\n", idx, (LPCWSTR) myArray[idx]);

// Only keep first 5 elements. This will truncate the array and
// free the extra (unused) bytes.
myArray.SetSize(5, 128);

// Print the elements of the array
size = myArray.GetSize();
for (idx=0; idx<size; idx++)
   printf("[%d]: %S\n", idx, (LPCWSTR) myArray[idx]);

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstrarr.h; include chstrarr.h and chstring.h.
Library: Use framedyn.lib.

See Also

CHStringArray::SetSize, CHStringArray::GetAt, CHStringArray::SetAt, CHStringArray::ElementAt, CHStringArray::FreeExtra


CHStringArray::GetSize

[This is preliminary documentation and subject to change.]

The GetSize member function gets the size of the array. Because indexes are zero-based, the size is 1 greater than the largest index.

int GetSize( ) const;

Parameters

This function has no parameters.

Return Values

If the GetSize member function is successful, it returns the number of elements in the array.

Example

See the example for CHStringArray::GetData.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstrarr.h; include chstrarr.h and chstring.h.
Library: Use framedyn.lib.

See Also

CHStringArray::Add, CHStringArray::GetUpperBound, CHStringArray::SetSize


CHStringArray::GetUpperBound

[This is preliminary documentation and subject to change.]

The GetUpperBound member function gets the current upper bound of an array. Because array indexes are zero-based, this function returns a value 1 less than GetSize.

int GetUpperBound( ) const;

Parameters

This function has no parameters.

Return Values

If the GetUpperBound member function is successful, it returns the upper bounds of this array. A value of -1 indicates that the array contains no elements.

Example

The following example demonstrates the use of CHStringArray::GetUpperBound.

CHStringArray array;

array.Add( L"String 1" ); // Element 0
array.Add( L"String 2" ); // Element 1
assert( array.GetUpperBound() == 1 ); // Largest index

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstrarr.h; include chstrarr.h and chstring.h.
Library: Use framedyn.lib.

See Also

CHStringArray::Add, CHStringArray::GetSize, CHStringArray::SetSize


CHStringArray::InsertAt

[This is preliminary documentation and subject to change.]

The InsertAt member function inserts an element (or all the elements in another array) at a specified index.

void InsertAt(
  int nIndex,
  LPCWSTR newElement,
  int nCount = 1
) throw ( CHeap_Exception );

void InsertAt(
  int nStartIndex,
  CHStringArray* pNewArray
) throw ( CHeap_Exception );

Parameters

nIndex
An integer index that may be greater than the value returned by GetUpperBound.
newElement
The CHString pointer to be placed in this array.

A value of NULL is allowed.

nCount
The number of times this element should be inserted (the default is 1).
nStartIndex
An integer index that may be greater than the value returned by GetUpperBound.
pNewArray
Another array that contains elements to be added to the array.

Remarks

The first version of InsertAt inserts one element (or multiple copies of an element) at a specified index in an array. The element at the specified index and all elements to its right shift up by one index value.

The second version inserts all the elements from another CHStringArray array, starting at the nStartIndex position.

The SetAt function, in contrast, replaces one specified array element and does not shift any elements.

Example

The following example demonstrates the use of CHStringArray::InsertAt.

CHStringArray a, a2;
CHString s( L"String 5" );
int idx, size;

a.Add( L"a.String 1" );
a.Add( L"a.String 2" );
a2.Add( L"a2.String 1" );
a2.Add( L"a2.String 2" );

a.InsertAt( 2, L"String 15" );
a.InsertAt( 1, s, 3 );

a2.InsertAt( 4, L"String 10");

a.InsertAt( 3, &a2 );

size = a.GetSize();
for(idx=0; idx<size; idx++)
   printf("[%d]: %S\n", idx, (LPCWSTR) a[idx]);

The results from this program are as follows:

[0] = a.String 1
[1] = String 5
[2] = String 5
[3] = a2.String 1
[4] = a2.String 2
[5] =
[6] =
[7] = String 10
[8] = String 5
[9] = a.String 2
[10] = String 15

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstrarr.h; include chstrarr.h and chstring.h.
Library: Use framedyn.lib.

See Also

CHStringArray::Add, CHStringArray::RemoveAt


CHStringArray::operator []

[This is preliminary documentation and subject to change.]

These subscript operators set or get the element at the specified index. These operators are a convenient substitute for the SetAt and GetAt functions.

CHString& operator [](
  int nIndex
);

CHString operator [](
  int nIndex
) const;

Parameters

nIndex
An integer index that is greater than or equal to zero and less than or equal to the value returned by GetUpperBound.

Return Values

The subscript operators return the CHString pointer element currently at this index.

Remarks

You can use the first operator, which calls for arrays that are not const, on either the right (r-value) or the left (l-value) side of an assignment statement. The second, which calls for const arrays, may be used only on the right.

The Debug version of the library asserts if the subscript (either on the left or right side of an assignment statement) is out of bounds.

Example

The following example demonstrates the use of CHStringArray::operator [].

CHStringArray array;
CHString s;

array.Add( L"String 1" ); // Element 0
array.Add( L"String 2" ); // Element 1
s = array[0]; // Get element 0
assert( s == L"String 1" );

array[0] = L"String 3"; // Replace element 0
assert( array[0] == L"String 3" );

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstrarr.h; include chstrarr.h and chstring.h.
Library: Use framedyn.lib.

See Also

CHStringArray::Add, CHStringArray::GetAt, CHStringArray::SetAt


CHStringArray::RemoveAll

[This is preliminary documentation and subject to change.]

The RemoveAll member function removes all the CHString members from this array.

void RemoveAll();

Parameters

This function has no parameters.

Remarks

This function works on empty arrays.

Example

The following example demonstrates the use of CHStringArray::RemoveAll.

CHStringArray array;

array.Add( L"String 1" ); // Element 0
array.Add( L"String 2" ); // Element 1
assert( array.GetSize() == 2 );
array.RemoveAll();
assert( array.GetSize() == 0 );

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstrarr.h; include chstrarr.h and chstring.h.
Library: Use framedyn.lib.

See Also

CHStringArray::FreeExtra


CHStringArray::RemoveAt

[This is preliminary documentation and subject to change.]

The RemoveAt member function removes one or more elements starting at a specified index in an array.

void RemoveAt(
  int nIndex,
  int nCount = 1
);

Parameters

nIndex
An integer index that is greater than or equal to zero and less than or equal to the value returned by GetUpperBound.
nCount
The number of elements to remove.

Remarks

In the process of removing elements, RemoveAt shifts down all the elements located above the elements that are removed. The function decrements the upper bound of the array but does not free memory.

Example

The following example demonstrates the use of CHStringArray::RemoveAt.

CHStringArray array;

array.Add( L"String 1" ); // Element 0
array.Add( L"String 2" ); // Element 1
array.RemoveAt( 0 );  // Element 1 moves to 0.
assert ( array[0] == L"String 2" );

The results from this program are as follows:

[0] = String 2

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstrarr.h; include chstrarr.h and chstring.h.
Library: Use framedyn.lib.

See Also

CHStringArray::Add, CHStringArray::GetAt, CHStringArray::InsertAt


CHStringArray::SetAt

[This is preliminary documentation and subject to change.]

The SetAt member function sets the array element at the specified index.

void SetAt(
  int nIndex
  LPCWSTR newElement
);

Parameters

nIndex
An integer index that is greater than or equal to zero and less than or equal to the value returned by GetUpperBound.
newElement
The object pointer that is inserted in this array. A NULL value is allowed.

Remarks

SetAt will not cause the array to grow. Use SetAtGrow if you want the array to grow automatically.

You must ensure that your index value represents a valid position in the array.

Example

The following example demonstrates the use of CHStringArray::SetAt.

CHStringArray array;

array.Add( L"String 1" ); // Element 0
array.Add( L"String 2" ); // Element 1
array.SetAt( 0, L"String 3" );  // Replace element 0.
assert( array[0] == "String 3" );

This example results in a CHStringArray with 2 elements.

    [0] = String 3
    [1] = String 2

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstrarr.h; include chstrarr.h and chstring.h.
Library: Use framedyn.lib.

See Also

CHStringArray::Add, CHStringArray::GetAt, CHStringArray::operator [], CHStringArray::ElementAt, CHStringArray::GetData


CHStringArray::SetAtGrow

[This is preliminary documentation and subject to change.]

The SetAtGrow member function sets the array element at the specified index. The array grows automatically if necessary, adjusting the upper bound to accommodate the new element.

void SetAtGrow(
  int nIndex,
  LPCWSTR newElement)
throw ( CHeap_Exception );

Parameters

nIndex
An integer index that is greater than or equal to 0.
newElement
The object pointer to be added to this array. A NULL value is allowed.

Example

The following example demonstrates the use of CHStringArray::SetAtGrow.

CHStringArray array;

array.Add( L"String 1" ); // Element 0
array.Add( L"String 2" ); // Element 1
array.SetAtGrow( 3, L"Sting 3" ); // Element 2 deliberately skipped.

The results from this program are as follows:

[0] = String 1
[1] = String 2
[2] =
[3] = String 3

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstrarr.h; include chstrarr.h and chstring.h.
Library: Use framedyn.lib.

See Also

CHStringArray::SetAt, CHStringArray::operator []


CHStringArray::SetSize

[This is preliminary documentation and subject to change.]

The SetSize member function establishes the size of an empty or existing array.

void SetSize(
  int nNewSize,
  int nGrowBy = -1
) throw ( CHeap_Exception );

Parameters

nNewSize
The new array size (number of elements). The value must be greater than or equal to zero.
nGrowBy
The minimum number of element slots to allocate if a size increase is necessary.

Remarks

This function allocates memory if necessary. If the new size is smaller than the old size, then the array is truncated, and all unused memory is released. For efficiency, call SetSize to set the size of the array before using it. This prevents the need to reallocate and copy the array each time an item is added.

The nGrowBy parameter affects internal memory allocation while the array is growing. Its use never affects the array size as reported by GetSize and GetUpperBound.

Example

See the example for CHStringArray::GetData.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in chstrarr.h; include chstrarr.h and chstring.h.
Library: Use framedyn.lib.

See Also

CHStringArray::GetSize, CHStringArray::GetUpperBound, CHStringArray::GetData


TRefPointerCollection Class Reference

[This is preliminary documentation and subject to change.]

The TRefPointerCollection class acts as a container to collect pointers to objects. These pointers can be enumerated.


TRefPointerCollection Class Methods

[This is preliminary documentation and subject to change.]

The following table lists the TRefPointerCollection Class methods available to TRefPointerCollection.

TRefPointerCollection Methods | Description
Add | Adds an item to the list (addrefs it)
BeginEnum | Call this method before enumerating (traversing) the list and pass in a cursor to be initialized (REFPTRCOLLECTION_POSITION)
GetNext | Gets next item from the list and addrefs it. (The user must release the pointer when done and pass in the same cursor each time.)
EndEnum | Call this method when the enumerating operation is finished.
Empty | Empties out the list, releasing all held pointers
GetSize | Returns the number of items in the list.
TRefPointerCollection | Constructs a new TRefPointerCollection object.


TRefPointerCollection::Add

[This is preliminary documentation and subject to change.]

The Add method adds a reference to the collection.

BOOL Add(
  TYPED_PTR *ptr
);

Parameters

ptr
The pointer to be added to the collection.

Return Values

If the Add method is successful, it returns TRUE; otherwise, it returns FALSE.

Remarks

The Add method calls the AddRef method on this pointer.


TRefPointerCollection::BeginEnum

[This is preliminary documentation and subject to change.]

The BeginEnum method starts enumerating the collection.

BOOL BeginEnum(
  REFPTRCOLLECTION_POSITION& pos
);

Parameters

pos
A value used to denote the position of an item in a TRefPointer collection.

Return Values

If the BeginEnum method is successful, it returns TRUE; otherwise, the method returns FALSE.

See Also

TRefPointerCollection::EndEnum


TRefPointerCollection::GetNext

[This is preliminary documentation and subject to change.]

The GetNext method gets a pointer to the next instance in the collection.

TYPED_PTR* GetNext(
  REFPTRCOLLECTION_POSITION& pos
);

Parameters

pos
A value used to denote the position of an item in a TRefPointer collection.

Return Values

The GetNext method returns the address of the next item by position in the TRefPointer collection.


TRefPointerCollection::EndEnum

[This is preliminary documentation and subject to change.]

The EndEnum method ends the enumeration of the collection.

void EndEnum(
  void
);

Parameters

This method has no parameters.

See Also

TRefPointerCollection::BeginEnum


TRefPointerCollection::Empty

[This is preliminary documentation and subject to change.]

The Empty method removes all items from the collection.

void Empty( void );

Parameters

This method has no parameters.


TRefPointerCollection::GetSize

[This is preliminary documentation and subject to change.]

The GetSize method returns how many items are in the list.

int GetSize( void ) const;

Parameters

This method has no parameters.


TRefPointerCollection::TRefPointerCollection

[This is preliminary documentation and subject to change.]

This constructor initializes a new TRefPointerCollection object.

TRefPointerCollection ( );

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP4 or later.
Windows 95/98: Requires Windows 95 OSR2 or later.
Windows CE: Unsupported.
Header: Declared in refptrco.h.
Library: Use framedyn.lib.


SQL for the WMI ODBC Adapter

This section lists in alphabetical order only the supported Windows Management Instrumentation (WMI) ODBC functions. The descriptions of the functions include design issues relevant to the implementation of the function.

For error codes and parameter descriptions, see the Microsoft ODBC 2.0 Programmer's Reference and SDK Guide.


ODBC Minimum SQL Grammar

The WMI ODBC adapter supports a subset of the ODBC minimum SQL grammar. It does not support data definition language (DDL) constructs and writeable data manipulation language (DML) constructs. If the data provider supports queries, the adapter decomposes the ODBC minimum SQL into a series of WMI Level 1 queries, and then passes the queries to the data provider. Thus, queries can be optimized for specific data providers.

The following table shows SELECT statement grammar (minimum level ODBC SQL conformance).

Statement Meaning
select-statement ::=
 SELECT [ALL|DISTINCT] select-list

FROM table-reference-list

[WHERE search-condition]

[order-by-clause]

select-list ::=
 * | select-sublist[,select-sublist]
select-sublist ::=
 Expression
Expression ::=
 Term|expression {+|-} term
term ::=
 Factor | term {*|/} factor
factor ::=
 [+|-] primary
primary ::
Column-name |

Dynamic-parameter |

Literal |

(expression)

dynamic-parameter :=
 ?
literal ::=
 Character-string-literal
character-string-literal ::=
 '{character}...'
character ::=
 our character set
column-name ::=
 [table-name.]column-identifier
column-identifier ::=
 user-defined-name
user-defined-name ::=
 letter[digit|letter|_]...
table-reference-list ::=
 table-reference[table-reference]..
table-reference ::=
 table-name
table-name ::=
 table-identifier | table-identifier aliasname
table-identifier ::=
 user-defined-name
search-condition ::=
 Boolean-term [OR search-condition]
Boolean-term ::=
 Boolean-factor [AND Boolean-term]
Boolean-factor ::=
 [NOT]Boolean-primary
Boolean-primary ::=
 predicate | (search-condition)
predicate ::=
 comparison-predicate |

like-predicate |

null-predicate

Comparison-predicate ::=
 expression comparison-operator expression
Comparison-operator ::=
 <|>|<=|>=|=|<>
like-predicate ::=
 Expression [NOT] LIKE
pattern-value ::=
 Character-string-literal | dynamic-parameter
null-predicate ::=
 Column-name IS [NOT] NULL
order-by-clause ::=
 ORDER BY sort-specification[,sort-specification]
sort-specification ::=
 {unsigned-integer | column} [ASC |DESC]


Level 1 Provider SQL Grammar

In Level 1 provider SQL grammar, all operations are on a single table, and dynamic parameters are not supported. This grammar can be converted into postfix notation (meaning that functions are preceded by all their operands) to facilitate the implementation of a simpler, stack-based SQL parser in the data provider.

The following table shows Level 1 provider SQL grammar.

Statement Meaning
Select-statement ::=
 SELECT [ALL|DISTINCT] select-list

FROM table-reference-list

[WHERE search-condition]

[GROUP BY column-name [, column-name]]

[HAVING search-condition]

[order-by-clause]

Select-list ::=
 * | select-sublist[,select-sublist]
Select-sublist ::=
 Expression | Expression aliasname | Expression AS aliasname
Expression ::=
 Term|expression {+|-} term
Term ::=
 Factor | term {*|/} factor
Factor ::=
 [+|-] primary
Primary ::=
Column-name |

Literal |

Realnumber |

Scalar |

USER |

Date |

Time |

Timestamp |

AggregateFunctionTerm |

(expression)

Literal ::=
 Character-string-literal
Character-string-literal ::=
 '{character}...'
Character ::=
 Our character set
Scalar ::=
 ScalarEscape | ScalarShorthand
ScalarEscape ::=
 --(*VENDOR(MICROSOFT),PRODUCT(ODBC) FN fn *)--
ScalarShorthand ::=
 { FN fn }
Fn ::=
 Functionname (valuelist) | Functionname ( )
AggregateFunctionTerm ::=
 COUNT (*) | AVG (expression) | MAX (expression) | MIN (expression) |

SUM (expression)

Column-name ::=
 [table-name.]column-identifier
Column-identifier ::=
 User-defined-name
User-defined-name ::=
 Letter[digit|letter|_]...
Table-reference-list ::=
 Table-reference [, Table-reference]
Table-reference ::=
 Table-name | Outerjoin
Outerjoin::=
 Ojescape | Ojshorthand
Ojescape::=
 --(*VENDOR(MICROSOFT),PRODUCT(ODBC) OJ Oj*)--
Ojshorthand::=
 { OJ Oj }
Oj::=
 Table-name LEFT OUTER JOIN table-name ON Boolean-term |

Table-name LEFT OUTER JOIN Oj ON Boolean-term

Table-name ::=
 [TableQualifier.]Table-identifier | [TableQualifier.]Table-identifier aliasname
Table-identifier ::=
 Aliasname
TableQualifer ::=
 Fully qualified namespace path in double quotes (e.g. "root\default" )
Search-condition ::=
 Boolean-term [OR search-condition]
Boolean-term ::=
 Boolean-factor [AND Boolean-term]
Boolean-factor ::=
 [NOT]Boolean-primary
Boolean-primary ::=
 Predicate | (search-condition)
Predicate ::=
 Comparison-predicate |

Like-predicate |

Null-predicate |

In-predicate |

Exists-predicate

Comparison-predicate ::=
 Expression comparison-operator expression |

Expression comparison-operator [ |ALL|ANY] Select-statement

Comparison-operator ::=
 <|>|<=|>=|=|<>
Like-predicate ::=
 Expression [NOT] LIKE Pattern-value
Pattern-value ::=
 Character-string-literal | USER
In-predicate ::=
 [NOT] IN (Valuelist) |

[NOT] IN (Select-statement)

Exists-predicate ::=
 EXISTS (Select-statement)
Null-predicate ::=
 Column-name IS [NOT] NULL
Realnumber ::=
 A non-negative real number (including E notation)
Date ::=
 DateEscape | DateShorthand
DateEscape ::=
 --(* VENDOR(MICROSOFT), PRODUCT(ODBC) d Dateval *)--
DateShorthand ::=
 {d Dateval }
Dateval ::=
 A date in yyy-mm-dd format in single quotes (e.g. '1996-02-05')
Time ::=
 TimeEscape | TimeShorthand
TimeEscape ::=
 --(* VENDOR(MICROSOFT), PRODUCT(ODBC) t Timeval *)--
TimeShorthand ::=
 { t Timeval }
Timeval ::=
 A time in hh:mm:ss format in single quotes (for example, '10:19:48')
Timestamp ::=
 TimestampEscape | TimestampShorthand
TimestampEscape ::=
 --(* VENDOR(MICROSOFT), PRODUCT(ODBC) ts Timestampval *)--
TimestampShorthand ::=
 { ts Timestampval }
Timestampval ::=
 A timestamp in yyyy-mm-dd hh:mm:ss[.ffffff] format in single quotes

(for example, '1992-02-05 10:19:48.529')

Aliasname ::=
 User-defined name
Order-by-clause ::=
 ORDER BY sort-specification[,sort-specification]
Sort-specification ::=
 {unsigned-integer | column} [ASC |DESC]


Quick Reference Table

The following table shows all supported WMI ODBC functions. For more information, see the Microsoft ODBC 2.0 Programmer's Reference and SDK Guide.

Function | Description
SQLAllocConnect | Standard ODBC function that allocates memory for a connection handle.
SQLAllocEnv | Allocates memory for an environment handle.
SQLAllocStmt | Allocates memory for a statement handle. This function has been modified to support inclusion of table qualifiers.
SQLBindCol | Binds application data buffers to columns in the result set.
SQLBindParameter | Binds a buffer to a parameter marker in an SQL statement.
SQLCancel | Used to cancel a function executing asynchronously on a statement handle that needs data.
SQLColAttributes | Returns descriptor information for a column in a result set. This function is modified to use information from the WMI repository.
SQLColumns | Returns a list of column names in specified tables.
SQLConnect | Connects to a data source, which can be either a database or a directory of tables. The user of SQLConnect must specify only a data source name.
SQLDataSources | Returns information about a data source. This function is implemented in the ODBC Driver Manager.
SQLDescribeCol | Similar to SQLColumns attributes. Imposes no requirements upon the property qualifiers in the WMI class objects beyond those specified in SQLColumns.
SQLDisconnect | Closes the connection associated with a specific connection handle.
SQLDriverConnect | Connects an application to a data source.
SQLDrivers | Lists driver descriptions and driver attribute keywords. This function is implemented in the ODBC Driver Manager.
SQLError | Provides support for the return of the standard error codes.
SQLExecDirect | Executes a new, preparable SQL statement.
SQLExecute | Executes a prepared statement, using the current values of the parameter marker variables, if any parameter markers exist in the statement.
SQLExtendedFetch | Not supported.
SQLFetch | Retrieves one row from a result set into the locations specified by the previous calls to SQLBindCol. Prepares the driver for a call to SQLGetData for the unbound columns.
SQLFreeConnect | Releases a connection handle and frees all memory allocated for the handle.
SQLFreeEnv | Closes the adapter and releases all associated memory.
SQLFreeStmt | Stops processing associated with a specific hstmt handle, closes any open cursors associated with the hstmt handle, discards pending results, and optionally frees all resources associated with the statement handle.
SQLGetConnectOption |
SQLGetCursorName | Returns the cursor name associated with a specified statement.
SQLGetData | Retrieves data for a single column in the result set. It can be called multiple times to retrieve variable-length data in parts.
SQLGetFunctions | Returns information about whether a driver supports a specific ODBC function. This function has been modified to indicate that the data source write operations are unsupported.
SQLGetInfo | Returns general information about the adapter and data source associated with a connection.
SQLGetStatementOption | Returns the current setting of a statement option.
SQLGetTypeInfo | Returns information about data types supported by the data source. The driver returns the information in the form of an SQL result set.
SQLMoreResults | Determines whether more results are available on a statement containing SELECT, UPDATE, INSERT, or DELETE statements and, if so, initializes processing for those results.
SQLNumResultCols | Returns the number of columns in a result set cursor.
SQLParamData | Used in conjunction with SQLPutData to supply parameter data at statement execution time.
SQLPrepare | Prepares an SQL statement by planning how to optimize and execute the statement. The SQL statement is compiled for execution by SQLExecDirect.
SQLPutData | Allows an application to send data for a parameter or column to the driver at statement execution time. This function can be used to send character or binary data values in parts to a column with a character, binary, or data source–specific data type (for example, parameters of the SQL_LONGVARBINARY or SQL_LONGVARCHAR types).
SQLRowCount | Returns the number of rows affected by an UPDATE, INSERT, or DELETE statement; an SQL_ADD, SQL_UPDATE_BY_BOOKMARK, or SQL_DELETE_BY_BOOKMARK operation in SQLBulkOperations; or an SQL_UPDATE or SQL_DELETE operation in SQLSetPos.
SQLSetConnectOption | Sets options that govern aspects of connections. For a discussion of the options and what they mean for the adapter, see SQLGetConnectOption.
SQLSetCursorName | Associates a cursor name with an active statement handle.
SQLSetScrollOptions | Superseded by SQLSetStmtOption in ODBC version 2.0. ODBC 2.0 Extension Level 2 adapters should implement SQLSetScrollOptions for backward compatibility with ODBC 1.0 applications.
SQLSetStmtOption | Sets options related to a statement handle, hstmt. For a discussion of the options and what they mean for the adapter, see SQLGetStatementOption .
SQLSpecialColumns | Retrieves the optimal set of columns that uniquely identifies a row in the table. Only the SQL_BEST_ROWID value for the fColType parameter is supported.
SQLStatistics | Retrieves a list of statistics about a single table and the indexes associated with the table. The driver returns the information as a result set.
SQLTables | Returns a list of table names stored in a specific data source.


SQLColAttributes (Core)

The SQLColAttributes function is modified to use information from the WMI repository. This function returns descriptor information for a column in a result set. For a description of how this information is retrieved, see SQLColumns. This function does not impose any demands on the qualifiers that must be made available for a property (column) in a class object (table) in a WMI repository. It is possible to ask for an SQL_COLUMN_LABEL label that utilities can use to describe a column. For use with the WMI ODBC adapter, this label can be the column name.


SQLColumns (Extended Level 1)

The SQLColumns function returns a list of column names in specified tables. The information is returned in a result set on the specified hStmt handle.

For example, to get information on the columns in TcpConnectionTable on the (represented by a database) DatabaseName device, the client invokes SqlColumns:

SQLColumns (hstmt, "DatabaseName", SQL_NTS,  // qualifier
NULL, 0,                                     // owner
"TcpConnectionTable", SQL_NTS,               // table
"%",SQL_NTS);                                // all columns

The following table shows the information returned in a rowset.

Column | Data type | Description
TABLE_QUALIFIER_NAME | Varchar (128) | Table qualifier. This corresponds to the database name.
TABLE_OWNER | Varchar (128) | Not used.
COLUMN_NAME | VarChar (128) | Column name (a WMI property name).
TYPE_NAME | VarChar (128), not nullable | Data type name. This is a data source dependent type name.
PRECISION | Integer | Precision of the column in the SNMP Module Information RepositorySMIR).
LENGTH | Integer | Length of the column.
SCALE | SmallInt | Scale of the column.
RADIX | SmallInt | Radii of the column.
NULLABLE | SmallInt, not nullable | Indicates whether the column is nullable.
REMARKS | Varchar (254) | Description of the column.
ATTRIBUTES | Longvarchar (16384) | Column metadata.

For a description of these terms, see the table in WMI to ODBC Mapping.

As can be observed from the preceding table, the WMI ODBC adapter extends the SQLColumns result set by an extra column. This extra column is used to return the column metadata.

The metadata is displayed in the following format:

[metadata name][ metadata value]
[metadata name][ metadata value]

For example,

[ObjectId][1.2.3.4.5.6]
[Syntax][STRING(254)]

If the metadata name or value contains a left or right square bracket ([ or ]), then two such symbols are used instead of one. For example, to show fr[ed]dy, the following is displayed:

[fr[[ed]]dy]

Note Some classes have properties that support a qualifier called Lazy. Properties marked with the Lazy qualifier are expensive to return (require a lot of processor time and memory). WMI improves the performance of queries by not attempting to return the properties marked with the Lazy qualifier.

Because WQL queries containing "lazy" properties may fail, properties marked with the Lazy qualifier will not be returned by the SQLColumns function.


SQLDriverConnect (Extension Level 1)

Use the SQLDriverConnect function to connect an application to a data source.

In the connection string to SQLDriverConnect, the caller specifies either of the following strings (both can optionally include the correlation keywords as described below):

  • "DSN=dataSourceName"
  • "DRIVER=driverName"

In addition to the standard data source name, user name, and password, the adapter uses the attribute-keywords listed in Attribute-Keyword Reference. If you specify the DRIVER keyword, the user is prompted to enter a database category.

If you have not specified enough information in the connection string (and if the fCompletionFlag parameter is not SQL_NO_PROMPT), then the Configure Connection dialog box appears that allows users to select namespaces. This dialog box contains a standard tree control to show the nesting of namespaces. Each namespace has an associated bitmap image to represent its state. For more information, see Selecting a Namespace.

You can also use the dialog box to select namespaces from a remote WMI repository. This functionality is available by means of the Configure Data Source Connection dialog box.

If you choose to manually enter a remote server name in the edit box (maximum length 128 characters), the update does not take place until you exit the edit control using the TAB key. The current tree control is cleared and replaced by the tree control for the new remote server. If the edit box does not contain any text, then the local server is used.

For information on finding remote servers, see Browsing for Namespaces on Remote WMI Servers.


SQLError (Core)

The WMI ODBC adapter provides support for the return of the standard error codes as defined in Appendix A of ODBC 2.0 Programmer's Reference and SDK Guide. These error codes correspond to the SQLSTATE code as defined in the X/Open and SAG SQL CAE Specification (1992).

When the adapter finds an internal error, such as an invalid handle or memory allocation error, the adapter returns the appropriate SQLSTATE code, which is a text string representing the component that originated the error, and a text description of the error. This is in accordance with the guidelines established in ODBC 2.0 Programmer's Reference and SDK Guide.

For example, if the adapter fails to allocate memory, the adapter reports the error with the following arguments.

Argument | Description
szSQLState | "S1001"
pfNativeError | NULL
szErrorMsg | "[Microsoft] [WBEM ODBC Driver] Unable to allocate sufficient memory"
pcberrorMsg | 68

If WMI returns an error code, the adapter qualifies the error message (szErrorMsg) to indicate that the error message originated in WMI. For example, if the client attempts to get the columns (properties) of a particular table (class), the adapter invokes the IMOSProvider::GetClass method. If GetClass returns OLEMS_E_INVALID_CLASS, the adapter reports the error with the following arguments.

Argument | Description
szSQLState | "S0002"
pfNativeError | NULL
szErrorMsg | "[Microsoft][WBEM ODBC Driver][OLE MS] Invalid class name. Class XXXX.YYYY could not be found"
pcberrorMsg | 94

The general method of discovering errors is to invoke SQLError iteratively until it reports no more errors. This is particularly useful in multiple-tier adapters. In accordance with ODBC guidelines, the adapter must have only one outstanding error per statement, connection, or handle. Thus, it is easy to discover where an error originated because an upstream component cannot alter error messages.


SQLGetConnectOption (Extension Level 1)

The following table shows the options you can specify on the SQLGetConnectOption function.

Value | Meaning
SQL_ACCESS_MODE | SQL_MODE_READ_ONLY.
SQL_AUTOCOMMIT | SQL_AUTOCOMMIT_ON.
SQL_CURRENT_QUALIFIER | The current qualifier in use by the data source. In WMI terms, this indicates the current database in use by the data source.
SQL_LOGIN_TIMEOUT | Intended to be the number of seconds to wait for a request to log on to complete before timing out and returning to the application. The adapter does not support this functionality.
SQL_ODBC_CURSORS | Returns an error that the adapter does not support this functionality.
SQL_OPT_TRACE | Implemented in the Adapter Manager.
SQL_OPT_TRACE_FILE | Implemented in the Adapter Manager.
SQL_PACKET_SIZE | Intended to be used to allow the client to specify the network packet size. The adapter does not support this functionality.
SQL_QUIET_MODE | Unsupported.
SQL_TRANSLATE_DLL | Unsupported.
SQL_TX_ISOLATION_LEVEL | Unsupported.


SQLGetFunctions (Extension Level 1)

The SQLGetFunctions function is modified to indicate that the data source write operations are unsupported. The following table shows the core functions of SQLGetFunctions.

Function | Supported
SQL_API_SQLALLOCCONNECT | YES
SQL_API_SQLALLOCENV | YES
SQL_API_SQLALLOCSTMT | YES
SQL_API_SQLBINDCOL | YES
SQL_API_SQLCANCEL | YES
SQL_API_SQLCOLATTRIBUTES | YES
SQL_API_SQLCONNECT | YES
SQL_API_SQLDESCRIBECOL | YES
SQL_API_SQLDISCONNECT | YES
SQL_API_SQLERROR | YES
SQL_API_SQLEXECDIRECT | YES
SQL_API_SQLEXECUTE | YES
SQL_API_SQLFETCH | YES
SQL_API_SQLFREECONNECT | YES
SQL_API_SQLFREEENV | YES
SQL_API_SQLFREESTMT | YES
SQL_API_SQLGETCURSORNAME | YES
SQL_API_SQLNUMRESULTCOLUMNS | YES
SQL_API_SQLPREPARE | YES
SQL_API_SQLROWCOUNT | YES
SQL_API_SQLSETCURSORNAME | YES
SQL_API_SQLSETPARAM | NO
SQL_API_SQLTRANSACT | NO

The following table shows the extended level 1 functions of the SQLGetFunctions function.

Function | Supported
SQL_API_SQLBINDPARAMETER | YES
SQL_API_SQLCOLUMNS | YES
SQL_API_SQLDRIVERCONNECT | YES
SQL_API_SQLGETCONNECTOPTION | YES
SQL_API_SQLGETDATA | YES
SQL_API_SQLGETFUNCTIONS | YES
SQL_API_SQLGETINFO | YES
SQL_API_SQLGETSTMTOPTION | YES
SQL_API_SQLGETTYPEINFO | YES
SQL_API_SQLPARAMDATA | YES
SQL_API_SQLPUTDATA | YES
SQL_API_SQLSETCONNECTOPTION | YES
SQL_API_SQLSETSTMTOPTION | YES
SQL_API_SQLSPECIALCOLUMNS | YES
SQL_API_SQLSTATISTICS | YES
SQL_API_SQLTABLES | YES

The following table shows the extended level 2 functions of the SQLGetFunctions function.

Function | Supported
SQL_API_SQLBROWSECONNECT | NO
SQL_API_SQLCOLUMNPRIVILEGES | NO
SQL_API_DATASOURCES | YES
SQL_API_DESCRIBEPARAM | NO
SQL_API_DRIVERS | YES
SQL_API_EXTENDEDFETCH | NO
SQL_API_FOREIGNKEYS | NO
SQL_API_SQLMORERESULTS | YES
SQL_API_SQLNATIVESQL | NO
SQL_API_SQLNUMPARAMS | NO
SQL_API_SQLPARAMOPTIONS | NO
SQL_API_SQLPRIMARYKEYS | NO
SQL_API_SQLPROCEDURECOLUMNS | NO
SQL_API_SQLPROCEDURES | NO
SQL_API_SQLSETPOS | NO
SQL_API_SQLSETSCROLLOPTIONS | NO
SQL_API_SQLTABLEPRIVILEGES | NO


SQLGetInfo (Extension Level 1)

The following table shows the information types for the SQLGetInfo function.

Information Type | Returns
SQL_ACCESSIBLE_PROCEDURES | 'Y' SQLProcedures is unsupported.
SQL_ACCESSIBLE_TABLES | Returns: 'Y' Can select on all tables returned by SQLTables.
SQL_ACTIVE_CONNECTIONS | Returns: 0 Maximum number of active connections that the adapter can support (0 means no limit).
SQL_ACTIVE_STATEMENTS | Returns: 0 Maximum number of active statements on a given connection (0 means no limit).
SQL_ALTER_TABLE | Returns: 0X0000 Bitmask indicating how the columns of a table can be altered.
SQL_BOOKMARK_PERSISTENCE | Returns: 0x0000 Bitmask indicating persistence of bookmarks. The adapter does not support bookmarks.
SQL_COLUMN_ALIAS | Returns: 'N' Adapter does not support column aliasing.
SQL_CONCAT_NULL_BEHAVIOR | Returns: SQL_CB_NON_NULL Result is the concatenation of non-null valued columns.
SQL_CONVERT_XXXXXXXXX | Returns: 0X0000 Adapter does not support the CONVERT scalar function.
SQL_CONVERT_FUNCTIONS | Returns: 0X0000 Adapter does not support the CONVERT scalar function.
SQL_CORRELATION_NAME | Returns: SQL_CN_ANY Correlation name can be any user-defined name.
SQL_CURSOR_COMMIT_BEHAVIOR | Returns: SQL_CB_CLOSE Closes cursor after a commit operation. Cursors are unsupported.
SQL_CURSOR_ROLLBACK_BEHAVIOR | Returns: SQL_CB_CLOSE Closes cursor after a rollback operation. Cursors are unsupported.
SQL_DATA_SOURCE_NAME | Returns: Data source name
SQL_DATA_SOURCE_READONLY | Returns: 'Y'
SQL_DATABASE_NAME | See SQL_CURRENT_QUALIFIER.
SQL_DBMS_NAME | Returns: MOServer@ServerName. ServerName is obtained from a standard WMI class.
SQL_DBMS_VER | Returns: version number of the MO Server The version number can be obtained from a standard WMI class.
SQL_DEFAULT_TXN_ISOLATION | Returns: 0x0000 Adapter does not support transactions.
SQL_DRIVER_HDBC | Returns: adapter's connection handle Implemented by the ODBC Driver Manager.
SQL_DRIVER_HENV | Returns: Implemented by the ODBC Driver Manager. It returns the adapter's environment handle.
SQL_DRIVER_HLIB | Returns: library handle returned to the ODBC Driver Manager when the manager loaded the adapter library Implemented by the ODBC Driver Manager.
SQL_DRIVER_HSTMT | Returns: adapter's statement handle Implemented by the ODBC Driver Manager.
SQL_DRIVER_NAME | Returns: WBEMDR32.DLL
SQL_DRIVER_ODBC_VERSION | Returns: "02.10.0000"
SQL_EXPRESSION_IN_ORDERBY | Returns: "n" Adapter does not support expressions in the ORDER BY clause.
SQL_FETCH_DIRECTION | Returns: 0x0000 Adapter does not support cursors.
SQL_FILE_USAGE | Returns: SQL_FILE_NOT_SUPPORTED Adapter is not a single-tier adapter.
SQL_GETDATA_EXTENSIONS | Returns: SQL_GD_ANY_COLUMN | SQLGD_ANY_ORDER | SQL_GD_BOUND
SQL_GROUP_BY | Returns: SQL_GROUP_BY_CONTAINS_SELECT: The GROUP BY clause must contain all non-aggregated columns in the select list, and it can contain columns that are not in the select list.
SQL_IDENTIFIER_CASE | Returns: SQL_IC_MIXED Identifiers are case-insensitive and are stored in the system catalog in mixed case, which is how WMI treats class and property names.
SQL_IDENTIFIER_QUOTE_CHAR | Returns: "\"
SQL_KEYWORDS | Returns: "" No data-source specific keywords.
SQL_LOCK_TYPES | Returns: 0x0000
SQL_MAX_BINARY_LITERAL_LEN | Returns: 0L No limit on a binary literal in a SQL statement.
SQL_MAX_CHAR_LITERAL_LEN | Set to 255.
SQL_MAX_COLUMN_NAME_LEN | Returns: 0 No limit.
SQL_MAX_COLUMNS_IN GROUP_BY | Set to 20.
SQL_MAX_COLUMNS_IN_INDEX | Returns: 0 No limit. The limit does not matter, because indexes are not supported.
SQL_MAX_COLUMNS_IN_ORDER_BY | Set to 20.
SQL_MAX_COLUMNS_IN_SELECT | Returns: 0 No limit on the number of columns in a SELECT statement.
SQL_MAX_COLUMNS_IN_TABLE | Returns: 0 No limit on the number of columns in a table.
SQL_MAX_CURSOR_ NAME_LEN | Set to 19.
SQL_MAXINDEX_SIZE | Returns: 0 No limit.
SQL_MAX_OWNER_NAME_LEN | Returns: 0 No limit.
SQL_MAX_PROCEDURE_NAME_LEN | Returns: 0 No limit. The limit does not matter because the adapter does not support procedures.
SQL_MAX_QUALIFIER_NAME_LEN | Returns: 0 No limit.
SQL_MAX_ROW_SIZE | Returns: 0 No limit.
SQL_MAX_ROW_SIZE_INCLUDES_LONG | Returns: "Y" Maximum row size returned by SQL_MAX_ROW_SIZE includes the length of SQL_LONG_VARCHAR and SQL_LONGVARBINARY.
SQL_MAX_STATEMENT_LEN | Returns: 0L No limit on the size of an SQL statement.
SQL_MAX_TABLE_NAME_LEN | Returns: 128
SQL_MAX_TABLES_IN_SELECT | Returns: 0 No limit on the number of tables in a SELECT statement.
SQL_MAX_USER_NAME_LEN | Set to 63.
SQL_MULT_RESULT_SETS | Returns: "N" Adapter does not support multiple result sets.
SQL_MULTIPLE_ACTIVE_TXN | Returns: "N" Does not matter, as transactions are not supported.
SQL_NEED_LONG_DATA_LEN | Returns: "N"
SQL_NON_NULLABLE_COLUMNS | Returns: SQL_NNC_NON_NULL
SQL_NULL_COLLATION | Returns: SQL_NC_LOW NULLs are sorted at the low end of a list.
SQL_NUMERIC_FUNCTIONS | Returns: SQL_FN_NUM_ABS | SQL_FN_NUM_ACOS | SQL_FN_NUM_ASIN | SQL_FN_NUM_ATAN | SQL_FN_NUM_ATAN2 | SQL_FN_NUM_CEILING | SQL_FN_NUM_COS | SQL_FN_NUM_COT | SQL_FN_NUM_DEGREES | SQL_FN_NUM_EXP | SQL_FN_NUM_FLOOR | SQL_FN_NUM_LOG | SQL_FN_NUM_LOG10 | SQL_FN_NUM_MOD | SQL_FN_NUM_PI | SQL_FN_NUM_POWER | SQL_FN_NUM_RADIANS | SQL_FN_NUM_RAND | SQL_FN_NUM_ROUND | SQL_FN_NUM_SIGN | SQL_FN_NUM_SIN | SQL_FN_NUM_SQRT | SQL_FN_NUM_TRUNCATE | SQL_FN_NUM_TAN
SQL_ODBC_API_CONFORMANCE | Returns: SQL_OAC_LEVEL
SQL_ODBC_SAG_CLI_CONFORMANCE | Returns: SQL_OSCC_COMPLIANT
SQL_ODBC_SQL_CONFORMANCE | Returns: SQL_OSC_MINIMUM
SQL_ODBC_OPT_IEF | Returns: "N" Adapter does not support Integrity Enhancement Facility (a subset of SQL designed to maintain the integrity of a database).
SQL_DRIVER_VER | Returns: "01.00.0000"
SQL_ORDER_BY_COLUMNS_IN_SELECT | Returns: "N" Columns in the ORDER BY clause do not need to be in the select list.
SQL_OUTER_JOINS | Returns: "Y"
SQL_OWNER_TERM | Returns: "" Character string with the data source vendor's name for an owner.
SQL_OWNER_USAGE | Returns: 0x0000 Owner is not supported in any statements.
SQL_POS_OPERATIONS | Returns: 0x0000 Adapter does not have cursors.
SQL_POSITIONED_STATEMENTS | Returns: 0x0000 Adapter does not have cursors.
SQL_PROCEDURE_TERM | Returns: "" Adapter does not support procedures.
SQL_PROCEDURES | Returns: "N" Adapter does not support procedures.
SQL_QUALIFIER_LOCATION | Returns: SQL_QL_START Qualifier comes first in a qualified table name; for example, Wellfleet.TcpConnectionTable, and not TcpConnectionTable.Wellfleet.
SQL_QUALIFIER_NAME_SEPARATOR | Returns: "."
SQL_QUALIFIER_TERM | Returns: "Namespace"
SQL_QUALIFIER_USAGE | Returns: SQL_QU_DML_STATEMENTS, at least For example, all DML statements allow this type in SELECT statements. You can use the logical OR with SQL_QU_PROCEDURE_INVOCATION, SQL_QU_TABLE_DEFINITION, and SQL_QU_INDEX_DEFINITION, but beause the adapter does not support procedures, table creation, or indexes, these items are not relevant.
SQL_QUOTED_IDENTIFIER_CASE | Returns: SQL_IC_MIXED Quoted identifiers are case-insensitive and are stored in mixed case.
SQL_ROW_UPDATES | Returns: "N" Adapter does not support scrollable cursors.
SQL_SCROLL_CONCURRENCY | Returns: 0x0000 Adapter does not support scrollable cursors.
SQL_SCROLL_OPTIONS | Returns: 0x0000 Adapter does not support scrollable cursors.
SQL_SEARCH_PATTERN_ESCAPE | Returns: "\" Search pattern escape character for % and _.
SQL_SERVER_NAME | Returns: "" Unnecessary.
SQL_SPECIAL_CHARACTERS | Returns: "" String contains all the special characters (such as characters not in a-z, A-Z, 0-9) that can be included in a table name.
SQL_STATIC_SENSITIVITY | Returns: 0x0000 Adapter does not support cursors.
SQL_STRING_FUNCTIONS | Returns: SQL_FN_STR_ASCII | SQL_FN_STR_CHAR | SQL_FN_STR_CONCAT | SQL_FN_STR_DIFFERENCE | SQL_FN_STR_INSERT | SQL_FN_STR_LCASE | SQL_FN_STR_LEFT | SQL_FN_STR_LENGTH | SQL_FN_STR_LOCATE | SQL_FN_STR_LOCATE2 | SQL_FN_STR_LTRIM | SQL_FN_STR_REPEAT | SQL_FN_STR_REPLACE | SQL_FN_STR_RIGHT | SQL_FN_STR_RTRIM | SQL_FN_STR_SOUNDEX | SQL_FN_STR_SPACE | SQL_FN_STR_SUBSTRING | SQL_FN_STR_UCASE
SQL_SUBQUERIES | Returns: 0x0000 Adapter does not support sub-queries in predicates.
SQL_SYSTEM_FUNCTIONS | Returns: SQL_FN_SYS_DBNAME | SQL_FN_SYS_IFNULL | SQL_FN_SYS_USERNAME
SQL_TABLE_TERM | Returns: "Class"
SQL_TIMEDATE_ADD_INTERVALS | Returns: SQL_FN_TSI_SECOND | SQL_FN_TSI_MINUTE | SQL_FN_TSI_HOUR | SQL_FN_TSI_DAY | SQL_FN_TSI_WEEK | SQL_FN_TSI_MONTH | SQL_FN_TSI_QUARTER | SQL_FN_TSI_YEAR
SQL_TIMEDATE_DIFF_INTERVALS | Returns: SQL_FN_TSI_SECOND | SQL_FN_TSI_MINUTE | SQL_FN_TSI_HOUR | SQL_FN_TSI_DAY | SQL_FN_TSI_WEEK | SQL_FN_TSI_MONTH | SQL_FN_TSI_QUARTER | SQL_FN_TSI_YEAR
SQL_TIMEDATE_FUNCTIONS | Returns: SQL_FN_TD_CURDATE | SQL_FN_TD_CURTIME | SQL_FN_TD_DAYNAME | SQL_FN_TD_DAYOFWEEK | SQL_FN_TD_DAYOFMONTH | SQL_FN_TD_DAYOFYEAR | SQL_FN_TD_HOUR | SQL_FN_TD_MINUTE | SQL_FN_TD_MONTH | SQL_FN_TD_MONTHNAME | SQL_FN_TD_NOW | SQL_FN_TD_QUARTER | SQL_FN_TD_SECOND | SQL_FN_TD_TIMESTAMPADD | SQL_FN_TD_TIMESTAMPDIFF | SQL_FN_TD_WEEK | SQL_FN_TD_YEAR
SQL_TXN_CAPABLE | Returns: SQL_TC_NONE Adapter does not support transactions.
SQL_TXN_ISOLATION_OPTION | Returns: 0x0000 Adapter does not support transactions.
SQL_UNION | Returns: 0x0000 Data source does not support the UNION clause.
SQL_USER_NAME | Returns: "" Not applicable.


SQLGetStatementOption (Extension Level 1)

The following table shows the options you can specify for the SQLGetStatementOption function.

Option | Values
SQL_ASYNC_ENABLE | SQL_ASYNC_ENABLE_ON Call any SQL functions on this statement asynchronously. SQL_ASYNC_ENABLE_OFF Call any SQL functions on this statement synchronously. This is the default.
SQL_BIND_TYPE | Adapter does not support SQLExtendedFetch, so calling the function with this option returns an error (SQL_ERROR).
SQL_CONCURRENCY | dapter does not support cursors, so calling the function with this option returns an error (SQL_ERROR). The client can then invoke SQLError to determine the cause. The SQLError function informs the client that the adapter does not support this facility.
SQL_CURSOR_TYPE | Adapter does not support cursors, so calling the function with this option returns an error (SQL_ERROR). The client can then invoke SQLError to determine the cause. The SQLError function informs the client that the adapter does not support this facility.
SQL_KEYSET_SIZE | Adapter does not support cursors, so calling the function with this option returns an error (SQL_ERROR). The client can then invoke SQLError to determine the cause. The SQLError function informs the client that the adapter does not support this facility.
SQL_MAX_LENGTH | 0 No limit. This is intended for use in two-tier adapters so the client can limit the maximum size of data returned from a binary or character column, to reduce network traffic. It is supported only if the data source supports it. The adapter does not support this option.
SQL_MAX_ROWS | 0 This is similar to SQL_MAX_LENGTH because it is used in two-tier systems to reduce network traffic. In this case, however, the client is limiting the number of rows. The adapter does not support this option.
SQL_NOSCAN | QL_NOSCAN_OFF Adapter scans statements for escape clauses.
SQL_QUERY_TIMEOUT | Number of seconds to wait for a query to execute without returning to the caller.
SQL_RETRIEVE_DATA | Adapter does not support cursors, so calling the function with this option returns an error (SQL_ERROR). The client can then invoke SQLError to determine the cause. The SQLError function informs the client that the adapter does not support this facility.
SQL_ROWSET_SIZE | Adapter does not support cursors, so calling the function with this option returns an error (SQL_ERROR). The client can then invoke SQLError to determine the cause. The SQLError function informs the client that the adapter does not support this facility.
SQL_SIMULATE_CURSOR | Adapter does not support cursors, so calling the function with this option returns an error (SQL_ERROR). The client can then invoke SQLError to determine the cause. The SQLError function informs the client that the adapter does not support this facility.
SQL_USE_BOOKMARKS | Adapter does not support cursors, so calling the function with this option returns an error (SQL_ERROR). The client can then invoke SQLError to determine the cause. The SQLError function informs the client that the adapter does not support this facility.


SQLGetTypeInfo (Extension Level 1)

Windows Management Instrumentation (WMI) uses variants exclusively to return property values. Thus, the base types that the WMI ODBC adapter must support are the variant types. In addition, WMI defines the Cimtype qualifier to attribute extra semantics to the type in addition to those semantics the variant type provides. For example, the variant type can be BSTR and the syntax IpAddress, indicating that the variant BSTR is, in fact, an IP address.


SQLTables (Extension Level 1)

The SQLTables function returns a list of table names stored in a specific data source. The information is returned in a result set. This function can also be used to enumerate either the table qualifiers in the data source or the owners in a given data source. ODBC table qualifiers correspond to WMI namespaces so you can use SQLTables to enumerate all the WMI namespaces.

An extra column is added to the SQLTables result set. This extra column is used to return the table metadata. The format of the metadata is identical to that returned by SQLColumns.


MOF Compiler

The Managed Object Format (MOF) compiler parses a file containing MOF statements and adds the classes and class instances defined in the file to the Common Information Model (CIM) repository. To run the MOF compiler on a file, use the following syntax.

mofcomp
  [-autorecover]
  [-check]
  [-N:<namespacepath>]
  [-class:createonly | -class:forceupdate |
   -class:safeupdate | -class:updateonly ]
  [-instance:updateonly | -instance:createonly]
  [-B:<filename>]
  [-WMI]
  [-P:<Password>]
  [-U:<UserName>]
  [-A:<Authority>]
  [-MOF:<path>]
  [-MFL:<path>]
  [-AMENDMENT:<Locale>]
  <MOFfile>

Switches

-autorecover
Adds the named MOF file to the list of files compiled during repository recovery. The list of autorecover MOF files is stored in the registry key:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WBEM\CIMOM\
 autorecover mofs. The MOF files listed in this registry entry must reside on the local computer because autorecover Mofs cannot recover MOF files located on a remote machine.

-check
Requests that the compiler perform a syntax check only and print appropriate error messages. No other switch can be used with this switch. When this switch is used, no connection to Windows Management Instrumentation (WMI) is established and no modifications to the CIM repository are made.
-N:<namespacepath>
Requests that the compiler load the MOF file into the namespace specified as namespacepath. The default namespace (Root\Default) is used unless this switch is used or a #pragma namespace ("namespace path") statement appears in the MOF file. If both the -N: namespace switch and the #pragma namespace are used, the #pragma namespace takes priority.
-class:createonly
Requests that the compiler not make any changes to existing classes. When this switch is used, the compilation terminates if a class specified in the MOF file already exists.
-class:forceupdate
Forces updates of classes when conflicting child classes exist. For example, suppose a class qualifier is defined in a child class and the base class tries to add the same qualifier. In -class:forceupdate mode, the MOF compiler resolves this conflict by deleting the conflicting qualifier in the child class. If the child class has instances, the forced update fails.
-class:safeupdate
Allows updates of classes even if there are child classes, as long as the change does not cause conflicts with child classes. For example, this flag allows adding a new property to the base class that was not previously mentioned in child classes. If the child classes have instances, the update fails.
-class:updateonly
Requests that the compiler not create any new classes. When this switch is used, the compilation terminates if a class specified in the MOF file does not exist.
-instance:updateonly
Requests that the compiler not create any new instances. When this switch is used, the compilation terminates if an instance specified in the MOF file does not exist.
-instance:createonly
Requests that the compiler not make any changes to existing instances. When this switch is used, the compilation terminates if an instance specified in the MOF file already exists.
-B:<filename>
Requests that the compiler create a binary version of the MOF file with the name filename without making any modifications to the CIM repository.
-WMI
Requests that the compiler perform a WMI syntax check. The -B switch must be used with this switch. The -WMI switch is only used for building binary MOFs for use by WDM device drivers. This switch invokes a separate binary MOF file checker, which runs after the binary MOF file is created. To use this switch under Windows 2000, the Windows 2000 DDK must first be installed.
-P:<Password>
Specifies Password as the password for the computer's user to enter when logging on.
-U:<UserName>
Specifies UserName as the name of the user logging on.
-A:<Authority>
Specifies Authority as the authority (domain name) to use when logging on to WMI.
-MOF:<path>
Name of the language neutral output. Used with the -AMENDEMENT switch to specify the name of the language neutral MOF file that will be generated.
-MFL:<path>
Name of the language specific output. Used with the -AMENDEMENT switch to specify the name of the language specific MOF file that will be generated.
-AMENDMENT:<Locale>
Splits the MOF file into language neutral and specific versions. The MOF compiler will create a language neutral form of the MOF file that has all amended qualifiers removed. A localized version of the MOF file will also be created with a MFL file extension. The Locale parameter specifies the name of the child namespace that will contain the localized class definitions. The format of the locale parameter is MS_xxx where xxx is the hexadecimal value of the Win32 LCID. For example, the locale for American English is MS_409. See WMI Localization for more information about localization.
-<MOFfile>
Specifies MOFfile as the name of the file to parse.

For a thorough description of the authentication schemes supported by WMI, see WMI Security.

Return Values

As its first operation, the MOF compiler performs a syntax check on the MOF file. If the compiler finds any errors, it prints an error message and the process terminates. The MOF compiler can return the following values.

Return value | Description
0 | MOF compilation was successful.
1 | The MOF compiler could not connect with the WMI server, possibly due to a semantic error such as an incompatibility with the existing CIM repository or an actual error such as the failure of the WMI server to start.
2 | One or more command-line switches were invalid.
3 | A MOF syntax error occurred.

If the MOF file is parsed correctly, but an attempt is made to perform an operation that is forbidden by a command-line switch, the compiler returns an error code generated by WMI instead of any of the return codes listed in the table preceding. For example, a WMI error code is returned when the -instance:updateonly switch is specified and the MOF file attempts to create an instance.

Remarks

A file can be compiled with the following simple command-line entries:

mofcomp MOFfile

When special processing is required, one or more of the switches described preceding can be used. All of the switches are optional, and any combination of switches is allowed. However, it does not make sense to use some of the switches in combination with others. For example, to combine the -class:updateonly and -class:createonly switches results in the compiler not performing any action.

A MOF file that uses the Unicode character set contains a signature as the first two bytes of the file. This signature is either U+FFFE or U+FEFF, depending on the byte ordering of the file.

When no errors occur in the parsing process, the MOF compiler connects to the WMI server running on the local computer unless the -check switch is specified. Classes and instances defined in the MOF file are added to the CIM repository.

When an error occurs in updating the CIM repository, the compiler makes no attempt to return the repository to its state before the compiler began processing.

Assigning Floating Point Values to Non-Floating Point Properties

The MOF compiler accepts a floating-point value specified for a non-floating point property. The value is rounded up or down and stored as a non-floating point number. This situation can cause some unexpected results. For example, the following MOF code defines a class called bad in a namespace called Test. This MOF code compiles without errors, but you cannot query for the floating-point value defined for the property bogusUint16 in the instance this code creates.

#pragma namespace ("\\\\.\\Root")

instance of __Namespace
{
    Name = "Test";
};

#pragma namespace ("\\\\.\\Root\\test")

Class bad
{
        [KEY] String testID ;
        Uint16 bogusUint16;
        Real64 bogusReal64;
};

Instance of bad
{
        TestID ="bogusID";
        bogusUint16 = 1000.4;
};

If you issue the following query, you get an error code indicating an invalid query:

Select * from bad where bogusUint16 = 1000.4

However, the following query finds the indicated instance:

Select * from bad where bogusUint16 = 1000

Binary MOF Files and Qualifier Flavors

If you use the [-B:filename] option to create a binary MOF file, only default qualifier flavors are stored in the CIM repository.

The following MOF file defines the class qualtest with a qualifier called myqualifier that has the flavors Propagates to instances, Propagates to derived classes and Allows overrides.

#pragma namespace ("\\\\.\\Root")
instance of __namespace
{
   name = "test";
};
#pragma namespace ("\\\\.\\Root\\test")
[myqualifier: ToInstance EnableOverride ToSubclass]

CLASS qualTest
{
    [key] String prop1 ;
    String prop2 ;
};

If you save this MOF file as Qualflavor.mof, you can create a binary MOF file as shown following:

mofcomp -b:binmof.mof qualflavor.mof

You can use the MOF compiler to compile this binary MOF file as shown following:

mofcomp binmof.mof

However, if you examine the qualifier flavors for the qualifier myqualifier, you see that only Allows overrides flavor is present.

Incomplete Compilation

If the MOF compiler cannot finish compiling a MOF file, the CIM repository may be left in an undefined state. For example, if you are compiling a MOF file and you use the -class:createonly command-line switch or pragma, the compilation terminates if a class specified in the MOF file already exists. The MOF compiler stores in the repository any classes or instances that were defined up to the point where the compiler stops. In some cases, this may leave the CIM repository in an undefined condition.

In this situation, you may need to stop WMI, delete the CIM repository and have WMI rebuild it. All MOF files that contain the -autorecover switch are rebuilt when WMI is restarted. You must manually recompile any MOF files that do not include an -autorecover pragma statement.

For information about how to declare classes and instances using the MOF syntax, see Using the Managed Object Format (MOF) Language.


Backus Naur Form Syntax

The following topics describe Backus Naur Form (BNF) syntax for Managed Object Format (MOF), Structured Query Language version 1 (SQL1), and object paths. BNF is a metalanguage that specifies syntax for programming languages.


BNF Syntax for Managed Object Format (MOF)

//
// Start creating symbol.
//
<Parse> ::= <top_level_decl><Parse>;
<Parse> ::= <qualifier_default><Parse>;
<Parse> ::= <preprocessor_command><Parse>;
<Parse> ::= <>;

//
// Preprocessor commands
//
<preprocessor_command> ::= <pound_include>;
<preprocessor_command> ::= <pound_define>;
<preprocessor_command> ::= TOK_PRAGMA <pound_pragma>;

<pound_include> ::= TOK_INCLUDE <const_string>;

<pound_define> ::= TOK_DEFINE TOK_SIMPLE_IDENT <const_value>;

<pound_pragma> ::= TOK_NAMESPACE
                    TOK_OPEN_PAREN TOK_LPWSTR TOK_CLOSE_PAREN;

<pound_pragma> ::= TOK_CLASSFLAGS
                    TOK_OPEN_PAREN TOK_LPWSTR TOK_CLOSE_PAREN;

<pound_pragma> ::= TOK_INSTANCEFLAGS
                    TOK_OPEN_PAREN TOK_LPWSTR TOK_CLOSE_PAREN;

<top_level_decl> ::= <qualifier_decl> <decl_type>;

<decl_type> ::= <typedef>;
<decl_type> ::= <instance_decl>TOK_SEMI;
<decl_type> ::= <class_decl>;

//
//  Typedef support
//
<typedef> ::= TOK_TYPEDEF <complete_type>
                TOK_SIMPLE_IDENT <opt_subrange> TOK_SEMI;
<complete_type> ::= <type> <opt_ref>;
<complete_type> ::= <enum>;

<enum> ::= TOK_ENUM TOK_OPEN_BRACE <enum_data> TOK_CLOSE_BRACE;

<enum_data> ::= <opt_name><enum_data_rest>;

<enum_data_rest> ::= <const_int> <int_enum_data_rest>;
<enum_data_rest> ::= TOK_LPWSTR <string_enum_data_rest>;

<int_enum_data_rest> ::= <>;
<int_enum_data_rest> ::= TOK_COMMA <int_enum_datum> <int_enum_data_rest>;

<int_enum_datum> ::= <opt_name><const_int>;

<string_enum_data_rest> ::= <>;
<string_enum_data_rest> ::= TOK_COMMA <string_enum_datum>
                                <string_enum_data_rest>;

<string_enum_datum> ::= <opt_name>TOK_LPWSTR;

<opt_name> ::= <>;
<opt_name> ::= TOK_SIMPLE_IDENT TOK_EQUALS;

<opt_subrange> ::= <>;
<opt_subrange> ::= TOK_SUBRANGE TOK_OPEN_PAREN <const_value> TOK_DOT TOK_DOT
                        <const_value> TOK_CLOSE_PAREN;

//
//  Class declaration
//
<class_decl> ::=
    TOK_CLASS
    TOK_SIMPLE_IDENT        // Class name
    <class_def>;

<class_def> ::=
    <as_alias>
    <opt_parent_class>
    TOK_OPEN_BRACE
    <property_decl_list>
    TOK_CLOSE_BRACE
    TOK_SEMI;
<class_def> ::= TOK_SEMI;

<property_decl_list> ::= <PropOrMeth_decl> <property_decl_list>;
<property_decl_list> ::= <>;

<opt_parent_class> ::= TOK_COLON TOK_SIMPLE_IDENT;
<opt_parent_class> ::= <>;

//
// Property and method declarations
//
<PropOrMeth_decl> ::= <qualifier_decl><PropOrMeth_decl2>;

<PropOrMeth_decl2> ::= <TypeAndName> <finish_PropOrMeth>;
<PropOrMeth_decl2> ::= TOK_VOID TOK_SIMPLE_IDENT <finish_meth>;

<finish_PropOrMeth> ::= <finish_prop>;
<finish_PropOrMeth> ::= <finish_meth>;

<finish_prop> ::=
    <opt_array>
    <default_value>
    TOK_SEMI;

<finish_meth> ::=
    TOK_OPEN_PAREN
    <arg_list>
    TOK_CLOSE_PAREN
    TOK_SEMI;

<TypeAndName> ::= <type> <opt_ref> TOK_SIMPLE_IDENT;

<arg_list> ::= <arg_decl> <rest_of_args>;
<arg_list> ::= <>;

<arg_decl> ::= <qualifier_decl><TypeAndName><opt_array><default_value>;

<rest_of_args> ::= TOK_COMMA <arg_decl> <rest_of_args>;
<rest_of_args> ::= <>;

<opt_ref> ::= TOK_REF;
<opt_ref> ::= <>;

<opt_array> ::= TOK_OPEN_BRACKET <opt_array_detail>;
<opt_array> ::= <>;

<opt_array_detail> ::= TOK_UNSIGNED_NUMERIC_CONST TOK_CLOSE_BRACKET;
<opt_array_detail> ::= TOK_CLOSE_BRACKET;

<default_value> ::= <>;
<default_value> ::= TOK_EQUALS <initializer>;

//
//  Instances
//
<instance_decl> ::=
    TOK_INSTANCE TOK_OF
    <type>
    <as_alias>
    TOK_OPEN_BRACE
    <prop_init_list>
    TOK_CLOSE_BRACE;

<prop_init_list> ::= <prop_init><prop_init_list>;
<prop_init_list> ::= <>;
<prop_init> ::= <qualifier_decl> TOK_SIMPLE_IDENT TOK_EQUALS <initializer> TOK_SEMI;

<as_alias> ::= TOK_AS <alias>;
<as_alias> ::= <>;

//
// Qualifiers
//
// The following code allows comma-delimited identifiers, or
// identifiers in functional notation with a constant and parameter
// list.
//
<qualifier_decl>   ::= TOK_OPEN_BRACKET <qualifier_list> TOK_CLOSE_BRACKET;
<qualifier_decl>   ::= <>;

<qualifier_list>   ::= <qualifier><qualifier_list_rest>;

<qualifier_list_rest> ::= TOK_COMMA <qualifier><qualifier_list_rest>;
<qualifier_list_rest> ::= <>;

<qualifier>        ::= TOK_SIMPLE_IDENT <qualifier_parm>;
<qualifier>        ::= TOK_EXTERNAL;

<qualifier_parm>  ::= TOK_OPEN_PAREN <initializer_list> TOK_CLOSE_PAREN <flavor_param>;
<qualifier_parm>  ::= <flavor_param>;

<flavor_param>    ::= TOK_COLON  <flavor_list> ;
<flavor_param>    ::= <>;

<flavor_list> ::= <flavor_value> <flavor_list_rest>;

<flavor_list_rest> ::=  <FLAVOR_VALUE> <flavor_list_rest>;
<flavor_list_rest> ::= <>;

<flavor_value> ::= TOK_TOINSTANCE;
<flavor_value> ::= TOK_NOTTOINSTANCE;
<flavor_value> ::= TOK_TOSUBCLASS;
<flavor_value> ::= TOK_NOTTOSUBCLASS;
<flavor_value> ::= TOK_ENABLEOVERRIDE;
<flavor_value> ::= TOK_DISABLEOVERRIDE;
<flavor_value> ::= TOK_RESTRICTED;

//////////////////////////////////////////////////////////////////////

<type> ::= TOK_SIMPLE_IDENT;

<const_int> ::= TOK_SIGNED_NUMERIC_CONST;
<const_int> ::= TOK_UNSIGNED_NUMERIC_CONST;
<const_int> ::= TOK_SIGNED64_NUMERIC_CONST;
<const_int> ::= TOK_UNSIGNED64_NUMERIC_CONST;

<const_string> ::= TOK_LPSTR;
<const_string> ::= TOK_LPWSTR;

<const_char> ::= TOK_CHAR;
<const_char> ::= TOK_WCHAR;

<const_value> ::= <const_string>;
<const_value> ::= <const_int>;
<const_value> ::= <const_char>;
<const_value> ::= TOK_UUID;
<const_value> ::= TOK_KEYWORD_NULL;

<initializer> ::= <simple_initializer>;
<initializer> ::= TOK_EXTERNAL;
<initializer> ::= TOK_OPEN_BRACE <initializer_list> TOK_CLOSE_BRACE;
<initializer> ::= <class_decl>;

<simple_initializer> ::= <qualifier_decl><instance_decl>;
<simple_initializer> ::= <const_value>;
<simple_initializer> ::= <alias>;

<initializer_list> ::= <simple_initializer><initializer_list>;
<initializer_list> ::= TOK_COMMA <simple_initializer><initializer_list>;
<initializer_list> ::= <>;

<alias> ::= TOK_DOLLAR_SIGN TOK_SIMPLE_IDENT;

//////////////////////////////////////////////////////////////////////
//
//  Qualifier defaults
//
<qualifier_default> ::= TOK_QUALIFIER TOK_SIMPLE_IDENT <flavor_param>;


BNF Syntax for Structured Query Language Version 1 (SQL1)

<parse> ::= SELECT <prop_list> FROM <class_name> <tolerance> <opt_where>
                <opt_aggregation>;

<opt_where> ::= WHERE <expr>;
<opt_where> ::= <>;

<prop_list> ::= <property_name> <prop_list_2>;
<prop_list_2> ::= COMMA <prop_list>;
<prop_list_2> ::= <>;

<property_name> ::= ASTERISK;
<property_name> ::= IDENTIFIER <property_name_2>;
<property_name_2> ::= <>;
<property_name_2> ::= DOT IDENTIFIER <property_name_2>;

<class_name> ::= IDENTIFIER;
<tolerance> ::= <>;
<tolerance> ::= WITHIN <duration>;

<duration> ::= DOUBLE;

// Subexpression nesting.  This particular sequence gives
// a series of AND clauses precedence over OR clauses.

<expr> ::= <term> <expr2>;
<expr2> ::= OR <term> <expr2>;
<expr2> ::= <>;

<term> ::= <simple_expr> <term2>;
<term2> ::= AND <simple_expr> <term2>;
<term2> ::= <>;

// Simple expression types.
// ========================

<simple_expr> ::= NOT <expr>;
<simple_expr> ::= OPEN_PAREN <expr> CLOSE_PAREN;
<simple_expr> ::= <property_name> <leading_ident_expr> <finalize>;
<simple_expr> ::= VARIANT <rel_operator> <trailing_prop_expr> <finalize>;

<trailing_prop_expr> ::=  <property_name>; // <trailing_prop_expr2>;

<leading_ident_expr> ::= <comp_operator> <trailing_const_expr>;
<leading_ident_expr> ::= <equiv_operator> <trailing_or_null>;
<leading_ident_expr> ::= <is_operator> NULL;

<trailing_or_null> ::= NULL;
<trailing_or_null> ::= <trailing_const_expr>;

<trailing_const_expr> ::= <typed_constant>;
<trailing_const_expr> ::= <trailing_ident_expr>;

<trailing_ident_expr> ::= <property_name>;

<typed_constant> ::= VARIANT; // VT_R8, VT_I4, VT_BSTR
<typed_constant> ::= TRUE;
<typed_constant> ::= FALSE;

<finalize> ::= <>;
    // This is just a semantic production in the parser to allow
    // all the important code to be located in one place.

<rel_operator> ::= <equiv_operator>;
<rel_operator> ::= <comp_operator>;

<equiv_operator> ::= EQUIVALENT_OPERATOR; // =, !=, <>
<comp_operator> ::=  COMPARE_OPERATOR;  // <=, >=, <, >, like, isa
<is_operator> ::=  ISNOT_OPERATOR;  // IS, IS NOT

<opt_aggregation> ::= <>;
<opt_aggregation> ::= GROUP <aggregation_params> <opt_having>;
<aggregation_params> ::= <aggregate_by> <opt_aggregate_within>;
<aggregation_params> ::= <aggregate_within> <opt_aggregate_by>;

<opt_aggregate_by> ::= <>;
<opt_aggregate_by> ::= BY <aggregate_by>;

<opt_aggregate_within> ::= <>;
<opt_aggregate_within> ::= WITHIN <aggregate_within>;

<aggregate_within> ::= <duration>;
<aggregate_by> ::= <aggregate_prop_list>;

<aggregate_prop_list> ::= <prop_list>;

<opt_having> ::= <>;
<opt_having> ::= HAVING <expr>;


BNF Syntax for Object Paths

//
// The first part of the grammar is the namespace path.
//
<Parse> ::= BACKSLASH <ns_or_server>;
<Parse> ::= IDENT <ns_or_class>;    // Save initial IDENT, because
                                    // it's not known what it is.
<Parse> ::= COLON <objref>;

//
// In the case of a server or namespace prefix, allow the object
// reference portion to be missing.
//
<ns_or_server> ::= BACKSLASH <dot_or_ident> BACKSLASH <ns_list> <optional_objref>;
<ns_or_server> ::= <ns_list> <optional_objref>;

<dot_or_ident> ::= IDENT;
<dot_or_ident> ::= DOT;

<optional_objref> ::= COLON <objref>;
<optional_objref> ::= <>;

<ns_or_class> ::= COLON <ident_becomes_ns> <objref>;
<ns_or_class> ::= BACKSLASH <ident_becomes_ns> <ns_list> COLON <objref>;
<ns_or_class> ::= <ident_becomes_class> <objref_rest>;

<ns_list> ::= IDENT <ns_list_rest>;

<ns_list_rest> ::= BACKSLASH <ns_list>;
<ns_list_rest> ::= <>;

<ident_becomes_ns> ::= <>;     // <initial_ident> becomes a namespace.
<ident_becomes_class> ::= <>;  // <initial_ident> becomes the class.

//
// The following portion is the object reference within the namespace.
//

<objref> ::= IDENT <objref_rest>;  // IDENT is the class name.

<objref_rest> ::= EQUALS <key_const>;
<objref_rest> ::= DOT <keyref_list>;
<objref_rest> ::= <>;

<keyref_list> ::= <keyref> <keyref_term>;

<keyref_term> ::= COMMA <keyref_list>;      // Used for compound keys
<keyref_term> ::= <>;

<keyref> ::= <propname> EQUALS <key_const>;

<propname>  ::= IDENT;

<key_const> ::= STRING_CONST;
<key_const> ::= INTEGRAL_CONST;
<key_const> ::= REAL_CONST;
<key_const> ::= IDENT;      // Where IDENT is "OBJECT".
                            // This option is for singleton classes.


SNMP Compiler Error Messages

This section describes the various error conditions that can result when the Simple Network Management Protocol (SNMP) information module compiler parses a Management Information Base (MIB) module.

The error messages have three severity levels:

  • Fatal errors
  • Warnings
  • Information messages

The severity level is shown in parentheses at the beginning of the error message description.

See Also

General Information Messages, Running the SNMP Compiler


Errors 101 through 110

Fatal Error 101

Fatal Error 102

Fatal Error 103

Fatal Error 104

Fatal Error 105

Fatal Error 106

Fatal Error 107

Fatal Error 108

Fatal Error 109

Warning 110

See Also

Running the SNMP Compiler


Errors 201 through 210

Fatal Error 201

Fatal Error 202

Fatal Error 203

Fatal Error 204

Fatal Error 205

Fatal Error 206

Fatal Error 207

Information Message 208

Fatal Error 209

Fatal Error 210


Errors 211 through 220

Information Message 211

Fatal Error 212

Fatal Error 213

Fatal Error 214

Fatal Error 215

Fatal Error 216

Fatal Error 217

Fatal Error 218

Fatal Error 219

Fatal Error 220


Errors 221 through 230

Fatal Error 222

Fatal Error 223

Fatal Error 224

Fatal Error 225

Fatal Error 226

Fatal Error 227

Fatal Error 228

Fatal Error 229

Warning 230


Errors 231 through 240

Fatal Error 232

Fatal Error 233

Fatal Error 234

Fatal Error 236


Errors 281 through 290

Fatal Error 282

Fatal Error 283


Errors 1001 through 1010

Fatal Error 1001

Fatal Error 1002

Fatal Error 1003

Warning 1004

Warning 1005

Fatal Error 1006

Fatal Error 1008


Errors 1011 through 1020

Fatal Error 1011

Fatal Error 1012

Fatal Error 1013

Warning 1014

Fatal Error 1015

Fatal Error 1016

Fatal Error 1018

Fatal Error 1020


Errors 1021 through 1030

Fatal Error 1021

Fatal Error 1022

Fatal Error 1023

Fatal Error 1024

Fatal Error 1025

Fatal Error 1026

Warning 1027

Fatal Error 1028

Fatal Error 1029

Fatal Error 1030


Errors 1031 through 1040

Warning 1031

Fatal Error 1032

Fatal Error 1033

Warning 1034

Warning 1036

Fatal Error 1037

Fatal Error 1038

Fatal Error 1039

Fatal Error 1040


Errors 1041 through 1050

Fatal Error 1041

Fatal Error 1042

Warning 1043

Fatal Error 1044

Warning 1045

Warning 1046

Warning 1047

Warning 1048

Fatal Error 1049


Errors 1051 through 1060

Fatal Error 1051

Fatal Error 1054

Fatal Error 1055


Errors 1061 through 1070

Fatal Error 1063

Fatal Error 1064

Fatal Error 1070


Errors 1071 through 1080

Warning 1071

Warning 1072

Fatal Error 1074

Fatal Error 1075

Fatal Error 1077

Fatal Error 1079

Warning 1080


Errors 1081 through 1090

Fatal Error 1081

Fatal Error 1082

Fatal Error 1084

Warning 1085

Warning 1086

Fatal Error 1087

Fatal Error 1089

Fatal Error 1090


Errors 1091 through 1100

Warning 1091

Fatal Error 1092

Fatal Error 1093

Fatal Error 1094

Fatal Error 1095

Fatal Error 1097

Fatal Error 1098

Fatal Error 1099


Errors 1101 through 1110

Fatal Error 1101


Errors 1451 through 1460

Fatal Error 1451

Fatal Error 1453


Errors 1501 through 1510

Fatal Error 1502

Fatal Error 101

<101, Fatal>: "Usage:
smi2smir <DiagnosticArgs> <VersionArgs> <CommandArgs>
smi2smir <DiagnosticArgs> <RegistryArgs>
smi2smir <HelpArgs>"
Command-line syntax error. This is followed by an explanation of the switches.

Fatal Error 102

<102, Fatal>:"Invalid argument on command line after <last correct argument>"
Command-line syntax error. There are some extra arguments or an invalid switch on the command line. The <last correct argument> parameter refers to the last argument that was read correctly on the command line, and can possibly be smi2smir, which is the name of the executable file for the SNMP module information compiler.

Fatal Error 103

<103, Fatal>: "Diagnostic Level not specified for the /m switch"
Command-line syntax error. If you specify the /m switch, you must also specify a diagnostic level of 0, 1, or 2.

Fatal Error 104

<104, Fatal>: "Diagnostic Level must be 0, 1 or 2 for the /m switch"
Command-line syntax error. If you specify the /m switch, you must also specify a diagnostic level of 0, 1, or 2.

Fatal Error 105

<105, Fatal>: "Maximum diagnostic count missing after the /c switch"
Command-line syntax error. If you specify the /c switch, you must also specify a non-negative integer as the maximum count.

Fatal Error 106

<106, Fatal>: "<argument> is not a valid diagnostic count"
Command-line syntax error. If you specify the /c switch, you must also specify a non-negative integer as the maximum count.

Fatal Error 107

<107, Fatal>: "File Name(s) missing"
Command-line semantic error. One or more file names must be specified on the command line for the given combination of switches.

Fatal Error 108

<108, Fatal>: "No command argument specified"
Command-line syntax error. Some action must be specified on the command line.

Fatal Error 109

<109, Fatal>: "Module name missing"
Command-line syntax error.

Warning 110

<110, Warning>: "No include path specified after the /i switch"
Command-line syntax warning. If you specify the /i switch, you must also specify the path to included files.

Fatal Error 201

<201, Fatal>: "<fileName>:<line#>: Syntax Error in the SYNTAX clause, Last token read is <token>"
Module syntax error, OBJECT-TYPE macro invocation. There is an error in the SYNTAX clause of the MIB OBJECT-TYPE definition.

Fatal Error 202

<202, Fatal>: "<fileName>:<line#>: Syntax Error in the ACCESS clause, Last token read is <token>"
Module syntax error, OBJECT-TYPE macro invocation. There is an error in the ACCESS clause of the MIB OBJECT-TYPE definition.

Fatal Error 203

<203, Fatal>: "<fileName>:<line#>: Syntax Error in the STATUS clause, Last token read is <token>"
Module syntax error, OBJECT-TYPE macro invocation. There is an error in the STATUS clause of the MIB OBJECT-TYPE definition.

Fatal Error 204

<204, Fatal>: "<fileName>:<line#>: Syntax Error in the DESCRIPTION clause, Last token read is <token>"
Module syntax error, OBJECT-TYPE or TRAP-TYPE macro invocation. There is an error in the DESCRIPTION clause of the MIB OBJECT-TYPE or TRAP-TYPE definition.

Fatal Error 205

<205, Fatal>: "<fileName>:<line#>: Syntax Error in the REFERENCE clause, Last token read is <token>"
Module syntax error, OBJECT-TYPE or TRAP-TYPE macro invocation. There is an error in the REFERENCE clause of the MIB OBJECT-TYPE or TRAP-TYPE definition.

Fatal Error 206

<206, Fatal>: "<fileName>:<line#>: Syntax Error in the INDEX clause, Last token read is <token>"
Module syntax error, OBJECT-TYPE macro invocation. There is an error in the INDEX clause of the MIB OBJECT-TYPE definition.

Fatal Error 207

<207, Fatal>: "<fileName>:<line#>: Syntax Error in the DEFVAL clause, Last token read is <token>"
Module syntax error, OBJECT-TYPE macro invocation. There is an error in the DEFVAL clause of the MIB OBJECT-TYPE definition.

Information Message 208

<208, Information>: "Skipping OBJECT-TYPE <identifier>"
Whenever errors 201-207 occur, this message informs you that the OBJECT-TYPE invocation is being skipped.

Fatal Error 209

<209, Fatal>:"<fileName>:<line#>: Syntax Error in the ENTERPRISE clause. Last token read is <token>"
Module syntax error, TRAP-TYPE macro invocation. There is a syntax error in the ENTERPRISE clause of the MIB TRAP-TYPE definition.

Fatal Error 210

<210, Fatal>:"<fileName>:<line#>: Syntax Error in the VARIABLES clause. Last token read is <token>"
Module syntax error, TRAP-TYPE macro invocation. There is a syntax error in the VARIABLES clause of the MIB TRAP-TYPE definition.

Information Message 211

<211, Information>: "Skipping TRAP-TYPE <identifier>"
Any errors in the TRAP-TYPE definition generate this message.

Fatal Error 212

<212, Fatal>: "<fileName>:<line#>: Syntax Error in SEQUENCE definition. Last token read is <token>"
Module syntax error in type assignment. There is an error between the left and right braces of a SEQUENCE construct, which amounts to a syntax error in a MIB type assignment.

Fatal Error 213

<213, Fatal>: "<fileName>:<line#>: Syntax Error in Object Identifier value. Last token read is <token>"
Module syntax error in value assignment. There is an error between the left and right braces of an object identifier value.

Fatal Error 214

<214, Fatal>: "<fileName>:<line#>: Syntax Error in the list of symbols in IMPORTS. Last token read is <token>"
Module syntax error in the IMPORTS section.

Fatal Error 215

<215, Fatal>: "<fileName>:<line#>: Syntax Error in IMPORTS (missing module name?). Last token read is <token>"
Module syntax error in the IMPORTS section.

Fatal Error 216

<216, Fatal>: "<fileName>:<line#>: Syntax Error in the IMPORTS section. Last token read is <token>"
Module syntax error in the IMPORTS section.

Fatal Error 217

<217, Fatal>: "<fileName>:<line#>: Syntax error in INTEGER Enumeration. Last token read is <token>"
Any module syntax error between the left and right braces of a MIB enumeration definition generates this message.

Fatal Error 218

<218, Fatal>: "<fileName>:<line#>: Syntax Error in sub-type specification. Last token read is <token>"
Any module syntax error between the parentheses in a sub-type specification generates this message.

Fatal Error 219

<219, Fatal>:"<fileName>:<line#>: Syntax Error in the SIZE specification. Last token read is <token>".
Any module syntax error in the SIZE clause between the left and right parentheses generates this message.

Fatal Error 220

<220, Fatal>:"<fileName>:<line#>: OBJECT-TYPE invocation of SNMPv2SMI not allowed"
Module syntax error. You have used the SNMPv2C-specific OBJECT-TYPE invocation in the MIB, but have specified the /v1 switch, which requires strict conformance to SNMPv1 syntax.

Fatal Error 222

<222, Fatal>: "<fileName>:<line#>: NOTIFICATION-TYPE not allowed in SNMPv1 SMI"
Module syntax error. You have used the SNMPv2C-specific NOTIFICATION-TYPE in the MIB, but have specified the /v1 switch, which requires strict conformance to SNMPv1 syntax.

Fatal Error 223

<223, Fatal>: "<fileName>:<line#>: MODULE-IDENTITY not allowed in SNMPv1 SMI"
Module syntax error. You have used the SNMPv2C-specific MODULE IDENTITY in the MIB, but have specified the /v1 switch, which requires strict conformance to SNMPv1 syntax.

Fatal Error 224

<224, Fatal>: "<fileName>:<line#>: OBJECT-IDENTITY not allowed in SNMPv1 SMI"
Module syntax error. You have used the SNMPv2C-specific OBJECT-IDENTITY in the MIB, but have specified the /v1 switch, which requires strict conformance to SNMPv1 syntax.

Fatal Error 225

<225, Fatal>: "<fileName>:<line#>: TEXTUAL-CONVENTION not allowed in SNMPv1 SMI"
Module syntax error. You have used the SNMPv2C-specific TEXTUAL-CONVENTION in the MIB, but have specified the /v1 switch, which requires strict conformance to SNMPv1 syntax.

Fatal Error 226

<226, Fatal>: "<fileName>:<line#>: OBJECT-GROUP not allowed in SNMPv1 SMI"
Module syntax error. You have used the SNMPv2C-specific OBJECT-GROUP in the MIB, but have specified the /v1 switch, which requires strict conformance to SNMPv1 syntax.

Fatal Error 227

<227, Fatal>: "<fileName>:<line#>: NOTIFICATION-GROUP not allowed in SNMPv1 SMI"
Module syntax error. You have used the SNMPv2C-specific NOTIFICATION-GROUP in the MIB, but have specified the /v1 switch, which requires strict conformance to SNMPv1 syntax.

Fatal Error 228

<228, Fatal>: "<fileName>:<line#>: MODULE-COMPLIANCE not allowed in SNMPv1 SMI"
Module syntax error. You have used the SNMPv2C-specific MODULE-COMPLIANCE in the MIB, but have specified the /v1 switch, which requires strict conformance to SNMPv1 syntax.

Fatal Error 229

<229, Fatal>: "<fileName>:<line#>: AGENT-CAPABILITIES not allowed in SNMPv1 SMI"
Module syntax error. You have used the SNMPv2C-specific AGENT-CAPABILITIES in the MIB, but have specified the /v1 switch, which requires strict conformance to SNMPv1 syntax.

Warning 230

<230, Warning>: "<fileName>:<line#>: '<the wrong token>' used. Assuming '::=' "
The token ":=", "::", or "=" has been used instead of "::=".

Fatal Error 232

<232, Fatal>:"<fileName>:<line#>:Invocation of SNMPv1 SMI OBJECT-TYPE disallowed"
Module syntax error. You have used the SNMPv1-specific OBJECT-TYPE invocation in the MIB, but have specified the /v2c switch, which requires strict conformance to SNMPv2C syntax.

Fatal Error 233

<233, Fatal>: "<fileName>:<line#>: Invocation of SNMPv1 SMI TRAP-TYPE disallowed"
Module syntax error. You have used the SNMPv1-specific TRAP-TYPE invocation in the MIB, but have specified the /v2c switch, which requires strict conformance to SNMPv2C syntax.

Fatal Error 234

<234, Fatal>:"<fileName>:<line#>: MODULE-IDENTITY invocation is allowed only immediately after the IMPORTS section."
Module syntax error. The MODULE-IDENTITY invocation is misplaced.

Fatal Error 236

<236, Fatal>: "<fileName>:<line#>: Number does not fit into the 32 bit representation used by the compiler"
Module syntax error in value assignment. There is a MIB value assignment error in which an integer value is so large that it requires more than 32 bits to represent it.

Fatal Error 282

<282, Fatal>: "<fileName>:<line#>: Syntax error. Last token read is <token>"
This error occurs when the compiler knows that some syntax error has occurred, but is unable to give any more specific information on the syntax error.

Fatal Error 283

<283, Fatal>: "<fileName>:<line##>: Unrecognized character <character> in input"
There is an unrecognized character in the input. Typically, unrecognized characters are ignored, and this error message reports the first unrecognized character.

Fatal Error 1001

<1001, Fatal>: "<fileName>:<line#>: SYNTAX clause of OBJECT-TYPE doesn't resolve to allowed types"
OBJECT-TYPE macro invocation module semantic error. The SYNTAX clause of the OBJECT-TYPE macro must resolve to a type or subtype, formed by using the SIZE or range specification that the SNMPv1 or SNMPv2C SMI allows. If this is not the case, fatal error 1001 is reported.

This error may occur when compiling either an SNMPv1 or SNMPv2C MIB.

Types allowed by the SNMPv1 SMI are:

  • INTEGER
  • NULL
  • OCTET STRING
  • OBJECT IDENTIFIER
  • NetworkAddress
  • IpAddress
  • Counter
  • Gauge
  • TimeTicks
  • Opaque
  • DisplayString
  • PhysAddress

    Types allowed by the SNMPv2C SMI are:

  • INTEGER
  • OCTET STRING
  • OBJECT IDENTIFIER
  • BITS
  • Integer32
  • IpAddress
  • Counter32
  • TimeTicks
  • Opaque
  • Counter64
  • Unsigned32
  • DisplayString
  • PhysAddress
  • MacAddress
  • TruthValue
  • TestAndIncr
  • AutonomousType
  • InstancePointer
  • VariablePointer
  • RowPointer
  • RowStatus
  • TimeStamp
  • TimeInterval
  • DateAndTime
  • StorageType
  • Tdomain
  • Taddress

Fatal Error 1002

<1002, Fatal>: "<fileName>:<line#>: Invalid ACCESS clause <clause>"
OBJECT-TYPE macro invocation module semantic error. For SNMPv1, the ACCESS clause of the OBJECT-TYPE macro must be "read-only," "write-only," "read-write," or "not-accessible."

For SNMPv2C, the MAX-ACCESS clause must be "read-only," "read-create," "read-write," or "not-accessible."

Fatal Error 1003

<1003, Fatal>: "<fileName>:<line#>: Invalid STATUS clause <clause>"
OBJECT-TYPE macro invocation module semantic error. For SNMPv1, the STATUS clause of an OBJECT-TYPE macro invocation must be "mandatory," "optional," "obsolete," or "deprecated."

For SNMPv2C, the STATUS clause of an OBJECT-TYPE macro invocation must be "current," "deprecated," or "obsolete."

Warning 1004

<1004, Warning>: "<fileName>:<line#>: OBJECT-TYPE <identifier>, whose syntax resolves to one of the Counter types does not end with the letter 's' "
OBJECT-TYPE macro invocation module semantic warning. The identifier for an object of SYNTAX Counter (SNMPv1) or Counter32 and Counter64 (SNMPv2C) must be plural.

This warning can occur when compiling either an SNMPv1 or SNMPv2C MIB.

Warning 1005

<1005, Warning>: "<fileName>:<line#>: OBJECT-TYPE with SYNTAX "SEQUENCE OF", should have an ACCESS clause "not-accessible."
OBJECT-TYPE macro invocation module semantic warning. A table or conceptual row (SEQUENCE OF or SEQUENCE object types, respectively) must be "not-accessible."

This warning can occur in either SNMPv1 or SNMPv2C.

Fatal Error 1006

<1006, Fatal>: "<fileName>:<line#> OBJECT-TYPE <identifier>, which is of SYNTAX SEQUENCE, does not have an INDEX or AUGMENTS clause"
OBJECT-TYPE macro invocation module semantic error. For SNMPv1, the INDEX clause must be present for an OBJECT-TYPE definition whose SYNTAX resolves to a SEQUENCE type.

For SNMPv2C, either the INDEX or the AUGMENTS clause must be present for a conceptual row declaration.

Fatal Error 1008

<1008, Fatal>: "<fileName>:<line#>: OBJECT-TYPE <identifier>, which is of SYNTAX "SEQUENCE" has not been referenced"
OBJECT-TYPE macro invocation module semantic error. An OBJECT-TYPE with the SYNTAX clause as a SEQUENCE type must figure in the SYNTAX clause of exactly one OBJECT-TYPE invocation that stands for a table declaration, that is, an object with the SYNTAX clause as a SEQUENCE OF type. The <line#> parameter refers to the second point of reference.

This error can occur in either SNMPv1 or SNMPv2C.

Fatal Error 1011

<1011, Fatal>: "<fileName>:<line#> the SYNTAX of member <identifier> of SEQUENCE, <identifier>, differs from the SYNTAX clause of the OBJECT-TYPE"
OBJECT-TYPE macro invocation module semantic error. An element of a SEQUENCE must be same as the type in the SYNTAX clause of the OBJECT-TYPE definition. The <line#> parameter is the line of the SYNTAX clause of the OBJECT-TYPE definition.

This error can occur in either SNMPv1 or SNMPv2C.

Fatal Error 1012

<1012, Fatal>: "<fileName>:<line#> An INDEX or AUGMENTS clause is required only for SEQUENCE OBJECT-TYPES"
OBJECT-TYPE macro invocation module semantic error. An INDEX clause must only be present in an OBJECT-TYPE definition whose SYNTAX resolves to a SEQUENCE type.

This error can occur when compiling either an SNMPv1 or SNMPv2C MIB.

Fatal Error 1013

<1013, Fatal>: "<fileName><line#>: <identifier> should resolve to a SEQUENCE type"
OBJECT-TYPE macro invocation module semantic error. A type used in the "SEQUENCE OF" construct must resolve to a SEQUENCE type.

This error can occur in either SNMPv1 or SNMPv2C.

Warning 1014

<1014, Warning>: "<fileName>:<line#>: Sub-identifier of value 0 not recommended in OIDs"
OBJECT-TYPE macro invocation module semantic warning. It is recommended that no object in an Internet Standard MIB use a sub-identifier of zero in its OBJECT IDENTIFIER.

This warning can occur in either SNMPv1 or SNMPv2C.

Fatal Error 1015

<1015, Fatal>: "<fileName>:<line#>: OBJECT-TYPEs <identifier> from module <identifier> and <identifier> from module <identifier> are assigned the same OID values"
OBJECT-TYPE macro invocation module semantic error. Two OBJECT-TYPE invocations (in the same or different modules) must not be assigned the same Object Identifier value.

This error can occur in either SNMPv1 or SNMPv2C.

Fatal Error 1016

<1016, Fatal>: "<fileName>:<line#>: Value in the DEFVAL clause does not match the type in the SYNTAX clause"
OBJECT-TYPE macro invocation module semantic error. A value in a DEFVAL clause must be a value of the type mentioned in the SYNTAX clause.

This error can occur in either SNMPv1 or SNMPv2C.

Fatal Error 1018

<1018, Fatal>: "<fileName><line#>: <symbol> in ENTERPRISE clause of TRAP-TYPE does not resolve to an OID value"
TRAP-TYPE macro invocation, SNMPv1-specific module semantic error. The symbol used in the ENTERPRISE clause of a TRAP-TYPE macro invocation must resolve to an Object Identifier value.

Fatal Error 1020

<1020, Fatal>: "<fileName><line#>: Value assigned to TRAP-TYPE <identifier> does not resolve to a positive integer"
TRAP-TYPE macro invocation, SNMPv1-specific module semantic error. A symbol used in specifying the trap value does not resolve to a positive integer.

Fatal Error 1021

<1021, Fatal>: "<fileName><line#>: Identifier <identifier> in the VARIABLES clause of TRAP-TYPE does not resolve to a scalar OBJECT-TYPE"
TRAP-TYPE macro invocation, SNMPv1-specific module semantic error. Each item in the list of variables used in the VARIABLES clause of a TRAP-TYPE macro invocation must resolve to the name of a scalar OBJECT-TYPE instance.

Fatal Error 1022

<1022, Fatal>: "<fileName><line#>: Value does not resolve to type <type>"
Value assignment module semantic error, specific to neither SNMPv1 nor SNMPv2C. The value on the RHS of an INTEGER, NULL, OCTET STRING, or OBJECT IDENTIFIER value assignment is of the wrong type.

Fatal Error 1023

<1023, Fatal>: "<fileName><line#>: Identifier <identifier> does not resolve to the type <identifier>"
Value assignment module semantic error, specific to neither SNMPv1 nor SNMPv2C. A symbol (value reference) on the RHS of an INTEGER, NULL, OCTET STRING, or OBJECT IDENTIFIER value assignment does not resolve to the right type.

Fatal Error 1024

<1024, Fatal>: "<fileName><line#>: Negative integer in OID value definition"
Value assignment module semantic error, specific to neither SNMPv1 nor SNMPv2C. All values in an OID component list must be non-negative (preferably positive) integers.

Fatal Error 1025

<1025, Fatal>: "Identifier <identifier> in OID value does not resolve to a positive integer"
Value assignment module semantic error, specific to neither SNMPv1 nor SNMPv2C. All values in an OID component list must be non-negative (preferably positive) integers.

Fatal Error 1026

<1026, Fatal>: "<fileName><line#>: Identifier <identifier> in OID value neither resolves to an OID value nor a positive integer"
Value assignment module semantic error, specific to neither SNMPv1 nor SNMPv2C. The first component used in an OID value must resolve to an OID value or an INTEGER.

Warning 1027

<1027, Warning>: "<fileName><line#>: Imported symbol <identifier> unused"
IMPORTS section module semantic warning, specific to neither SNMPv1 nor SNMPv2C. A warning is issued for every unused imported symbol.

Fatal Error 1028

<1028, Fatal>: "Module <identifier> not imported in the IMPORTS section"
IMPORTS section module semantic error, specific to neither SNMPv1 nor SNMPv2C. A module name used in referencing a symbol must either be present in the IMPORTS clause, or be the name of the current module.

Fatal Error 1029

<1029, Fatal>: "<fileName><line#>: Current module <identifier> cannot be imported"
IMPORTS section module semantic error, specific to neither SNMPv1 nor SNMPv2C. The name of the current module also figures in the IMPORTS list.

Fatal Error 1030

<1030, Fatal>:"<fileName><line#>: Symbol <identifier> not imported from Module <identifier>"
IMPORTS section module semantic error, specific to neither SNMPv1 nor SNMPv2C. You have used the "Module.Symbol" notation, but the symbol has not been imported from the specified module in the IMPORTS section.

Warning 1031

<1031, Warning>: "<fileName>:<line#>: Standard symbol <identifier> should be imported from module <identifier>. Assuming the standard definition."
IMPORTS section module semantic warning, specific to neither SNMPv1 nor SNMPv2C. If an SNMP identifier known to the compiler is in the IMPORTS section, then the module from which it is imported must be one of the standard modules.

Certain commonly used IMPORTS are "assumed knowledge" on the part of the compiler. It is unnecessary for the compiler to require access to other information modules to resolve these.

The built-in SNMPv1 and SNMPv2C IMPORTS are described in the following tables.

Built-in SNMPv1 IMPORTS

Import Class | Module | Instances
ASN.1 Value | RFC1155-SMI | internet, directory, management, experimental, private, enterprises
 | RFC1213-MIB | mib-2, ip, interfaces, transmission
ASN.1 Type | RFC1155-SMI | NetworkAddress, IpAddress, Counter, Gauge, TimeTicks, Opaque
 | RFC1213-MIB | DisplayString, PhysAddress
ASN.1 Macro | RFC-1212 | OBJECT-TYPE
 | RFC-1215 | TRAP-TYPE

Built-in SNMPv2C IMPORTS

Import Class | Module | Instances
ASN.1 Value | SNMPv2-SMI | org, dod, internet, directory, mgmt, mib-2, transmission, experimental, private, enterprises, security, snmpv2, snmpDomains, snmpProxys, snmpModules
 | SNMPv2-TM | rfc1157Proxy
Object Identity | SNMPv2-SMI | zeroDotZero
 | SNMPv2-TM | snmpUDPDomain, snmpCLNSDomain, smnpCONSDomain, snmpDDPDomain, snmpIPXDomain, rfc1157Domain
ASN.1 Type | SNMPv2-SMI | Integer32, IpAddress, Counter32, TimeTicks, Opaque, Counter64, Unsigned32, Gauge32
ASN.1 Macro | SNMPv2-SMI | MODULE-IDENTITY, OBJECT-IDENTITY, OBJECT-TYPE, NOTIFICATION-TYPE
 | SNMPv2-CONF | OBJECT-GROUP, NOTIFICATION-GROUP, MODULE-COMPLIANCE, AGENT-CAPABILITIES
 | SNMPv2-TC | TEXTUAL-CONVENTION
Textual Convention | SNMPv2-TC | DisplayString, PhysAddress, MacAddress, TruthValue, TestAndIncr, AutonomousType, InstancePointer, VariablePointer, RowPointer, RowStatus, TimeStamp, TimeInterval, DateAndTime, StorageType, Tdomain, Taddress
 | SNMPv2-TM | SnmpUDPAddress, SnmpOSIAddress, SnmpNBPAddress, SnmpIPXAddress

Fatal Error 1032

<1032, Fatal>: "<fileName><line#>: Duplicate value <value> in enumeration"
Module semantic error in an enumeration, specific to neither SNMPv1 nor SNMPv2C. There must not be any duplicate values. The <line#> parameter is the position of the recurrence of the name/value.

Fatal Error 1033

<1033, Fatal>: "<fileName><line#>: Duplicate name <identifier> in enumeration"
Module semantic error in an enumeration, specific to neither SNMPv1 nor SNMPv2C. There must not be any duplicate names. The <line#> parameter is the position of the recurrence of the name/value.

Warning 1034

<1034, Warning>: "<fileName><line#>: A value of 0 disallowed in an enumeration"
Module semantic warning in an enumeration, specific to neither SNMPv1 nor SNMPv2C. It is recommended that a named value of zero not be used in an enumeration.

Warning 1036

<1036, Warning> "<fileName><line#>: Value in enumeration does not resolve to a positive integer"
Module semantic warning in an enumeration, specific to neither SNMPv1 nor SNMPv2C. A negative value is not allowed in an enumeration.

Fatal Error 1037

<1037, Fatal>: "<fileName><line#>: Identifier <identifier> does not resolve to OCTET STRING or Opaque types"
Module semantic error in SIZE specification, specific to neither SNMPv1 nor SNMPv2C. The symbol used in a SIZE specification must resolve to OCTET STRING or Opaque.

Fatal Error 1038

<1038, Fatal>: "<fileName><line#>: Identifier <identifier> does not resolve an INTEGER or Gauge type"
Module semantic error in range specification. This error can occur in either SNMPv1 or SNMPv2C.

In SNMPv1, the symbol used in a Range specification must resolve to INTEGER or Gauge.

In SNMPv2C, the symbol used in a Range specification must resolve to INTEGER, Gauge32, Integer32, or Unsigned32.

Fatal Error 1039

<1039, Fatal>:<fileName><line#>: Negative value used in SIZE specification"
Module semantic error in SIZE specification, specific to neither SNMPv1 nor SNMPv2C. Any value used in specifying the SIZE must be non-negative.

Fatal Error 1040

<1040, Fatal>: "<fileName><line#>: Identifier <identifier> in SIZE specification does not resolve to a non-negative integral value"
Module semantic error in range or size specification, specific to neither SNMPv1 nor SNMPv2C. Any symbol used in specifying a value in a SIZE specification resolves to a non-negative value.

Fatal Error 1041

<1041, Fatal>: "<fileName><line#>: Identifier <identifier> in range specification does not resolve to an integral value".
Module semantic error in range or size specification, specific to neither SNMPv1 nor SNMPv2C. The symbol used in a SIZE specification must resolve to OCTET STRING or Opaque. Any value used in specifying a range must be an integer.

Fatal Error 1042

<1042, Fatal>: "<fileName><line#>: Upper bound of range specification is less than the lower bound"
Module semantic error in range or size specification, specific to neither SNMPv1 nor SNMPv2C. The symbol used in a SIZE specification must resolve to OCTET STRING or Opaque. The lower bound of a range or SIZE specification must be no greater than the upper bound.

Warning 1043

<1043, Warning>: "<fileName>:<line#>: OBJECT-TYPE with SYNTAX "SEQUENCE", should have an ACCESS clause "not-accessible."
OBJECT-TYPE macro invocation module semantic warning. A table or conceptual row (SEQUENCE OF or SEQUENCE object types, respectively) must be "not-accessible."

This warning can occur in either SNMPv1 or SNMPv2C.

Fatal Error 1044

<1044, Fatal>: "<fileName><line#>: Redefinition of symbol <identifier>"
Module semantic error, specific to neither SNMPv1 nor SNMPv2C. Redefinition of object descriptors, macro invocations, and ASN.1 types cause an error.

Warning 1045

<1045, Warning>: "<fileName><lineReference to standard symbol <symbolName> assumed to be for the definition as in <moduleName>. Use the "module.symbol" notations, if you want to refer to the definition in the current module"
Module semantic warning, specific to neither SNMPv1 nor SNMPv2C. A symbol known to the compiler has been redefined, and is being referenced. The compiler assumes the standard definition of the symbol. Therefore, to use a redefinition of the standard symbol, you must use the "Module.Symbol" notation.

Warning 1046

<1046, Warning>: "<fileName><line#>: <symbol> undefined. Assuming standard definition."
Module semantic warning, specific to neither SNMPv1 nor SNMPv2C. A symbol known to the compiler must not be redefined or used without being imported.

Warning 1047

<1047, Warning>: "<fileName><line#>: Type definition <symbol> defined but not referenced"
Module semantic warning, specific to neither SNMPv1 nor SNMPv2C. All value assignments and type definitions must be referenced somewhere.

Warning 1048

<1048, Warning>: "<fileName><line#>: Value definition <symbol< defined but not referenced"
Module semantic warning, specific to neither SNMPv1 nor SNMPv2C. All value assignments and type definitions must be referenced somewhere.

Fatal Error 1049

<1049, Fatal>: "<fileName>:<line#>: DEFVAL clause not allowed for OBJECT-TYPE with SYNTAX NetworkAddress."
OBJECT-TYPE macro invocation SNMPv1-specific module semantic error. The DEFVAL clause is not allowed for an OBJECT-TYPE whose SYNTAX clause resolves to NetworkAddress.

Fatal Error 1051

<1051, Fatal>: "<fileName>:<line#>: Ambiguous reference to symbol <identifier>"
IMPORTS section module semantic error, specific to neither SNMPv1 nor SNMPv2C. Each object descriptor corresponding to an object in an Internet Standard MIB must be unique. Since enterprise MIBs can have common object descriptors, such descriptors imported from two modules must be used unambiguously in the MIB module by using the notation "module.descriptor."

Fatal Error 1054

<1054, Fatal>: "<fileName>:<line#>: <identifier> in INDEX clause does not resolve to one of the allowed types"
OBJECT-TYPE macro invocation module semantic error. The type of an object in the INDEX clause, or any type specified in the INDEX clause, must resolve to a scalar type, that is, a non-SEQUENCE or non-SEQUENCE OF type. Any type specified in the INDEX clause must also resolve to one of these.

This error can occur in either SNMPv1 or SNMPv2C.

Fatal Error 1055

<1055, Fatal>:"<fileName>:<line#>: SYNTAX of INDEX OBJECT-TYPE <identifier>, does not resolve to one of the allowed types"
OBJECT-TYPE macro invocation module semantic error. The type of an object in the INDEX clause, or any type specified in the INDEX clause, must resolve to a scalar type, that is, a non-SEQUENCE or non-SEQUENCE OF type.

This error can occur in either SNMPv1 or SNMPv2C.

Fatal Error 1063

<1063, Fatal<: "<fileName><line#>: Upper bound of SIZE specification is less than the lower bound"
Module semantic error in SIZE specification, specific to neither SNMPv1 nor SNMPv2C. The symbol used in a SIZE specification must resolve to OCTET STRING or Opaque. The lower bound of a range or SIZE specification must be no greater than the upper bound.

Fatal Error 1064

<1064, Fatal>: "<fileName>:<line#>: SEQUENCE item <identifier> does not resolve to an OBJECT-TYPE"
Type assignment module semantic error, specific to neither SNMPv1 nor SNMPv2C. All the individual elements of a SEQUENCE declaration must resolve to an OBJECT-TYPE.

Fatal Error 1070

<1070, Fatal>: "<fileName><line#>: MIB Module <moduleName>, from which symbol <symbolName> is imported, is not present in input"
Module semantic error in cross-referencing, specific to neither SNMPv1 nor SNMPv2C. If one of the modules in the IMPORTS section of the main module or a subsidiary module does not exist and one or more symbols from this module are actually referenced, this fatal error occurs.

Warning 1071

<1071, Warning>: "<fileName><line#>: Symbol <identifier> not present in imported module <identifier>"
Module semantic warning about cross-referencing, specific to neither SNMPv1 nor SNMPv2C. A symbol imported from a module does not resolve to anything in that module. Even though that module is specified in the input, this warning appears.

Warning 1072

<1072, Warning>: "<fileName>:<line#> OBJECT-TYPE <name> is a descendant of OBJECT-TYPE <name> of module <name>"
OBJECT-TYPE macro invocation module semantic warning. A scalar object cannot have any descendant objects.

This warning can occur in either SNMPv1 or SNMPv2C.

Fatal Error 1074

<1074, Fatal>: "<fileName>:<line#> SEQUENCE (Conceptual row) OBJECT-TYPE <name> does not have a SEQUENCE OF (Conceptual table) OBJECT-TYPE as its parent.
OBJECT-TYPE macro invocation module semantic error. Every row object must have a table object as its parent.

This error can occur in either SNMPv1 or SNMPv2C.

Fatal Error 1075

<1075, Fatal>:"<fileName>:<line#>: OBJECT-TYPE <name> cannot be a child of table OBJECT-TYPE <name> of module <name> unless it is in the SEQUENCE of the latter"
OBJECT-TYPE macro invocation module semantic error. Every SEQUENCE object must have exactly the same objects that are mentioned in the SEQUENCE type definition as its children. Similarly, every SEQUENCE OF object must have exactly one child.

This error can occur in either SNMPv1 or SNMPv2C.

Fatal Error 1077

<1077, Fatal>: "<fileName>:<line#>: The syntax of table OBJECT-TYPE <name> is not the SEQUENCE OF the syntax of the child OBJECT-TYPE <name> of module <name>.
OBJECT-TYPE macro invocation module semantic error. The syntax clause of a table object must be the "SEQUENCE OF" of the syntax of the row object.

This error can occur in either SNMPv1 or SNMPv2C.

Fatal Error 1079

<1079, Fatal>:"fileName>:<line#>: OBJECT-TYPE <name> is an extra child of OBJECT-TYPE <name> of module <name>"
OBJECT-TYPE macro invocation module semantic error. Every SEQUENCE OF object must have exactly one child.

This error can occur in either SNMPv1 or SNMPv2C.

Warning 1080

<1080, Warning>: "<fileName><line#>: MIB Module <moduleName>, from which symbol <symbolName> is imported, is not present in input"
Module semantic warning about cross-referencing, specific to neither SNMPv1 nor SNMPv2C. If one of the modules in the IMPORTS section of the main module or a subsidiary module does not exist, but symbols from this module are not referenced, this warning appears.

Fatal Error 1081

<1081, Fatal>: "<fileName>line#>: Symbol <identifier> not present in imported module <identifier>"
Module semantic error in cross-referencing, specific to neither SNMPv1 nor SNMPv2C. A symbol imported from a module does not resolve to anything in that module. If that symbol is actually referenced in the MIB, this error occurs.

Fatal Error 1082

<1082, Fatal>: "<fileName>:<line#>: Invalid STATUS clause <clause>"
OBJECT-IDENTITY macro invocation, SNMPv2C-specific module semantic error. The STATUS clause of an OBJECT-IDENTITY invocation must be "current," "deprecated," or "obsolete."

Fatal Error 1084

<1084, Fatal>: "fileName><line#>: MODULE-IDENTITY required after the IMPORTS section for all SNMPv2 modules"
MODULE-IDENTITY macro invocation, SNMPv2C-specific module semantic error. There must be one and only one MODULE-IDENTITY invocation in an SNMPv2C MIB, immediately after the IMPORTS section.

Warning 1085

<1085, Warning>: "<fileName><line#>: No groups found in module <name>. Could not fabricate MODULE-IDENTITY. Attempt to load the module into the SMIR will fail.
Module semantic SNMPv1-specific warning. This error is generated if no object groups are found in a module.

Warning 1086

<1086, Warning>: "<fileName><line#>: No groups found in module <name>.
Module semantic SNMPv1-specific warning. This error is generated if no object groups are found in a module.

Fatal Error 1087

<1087. Fatal>: "<fileName><line#>: Invalid STATUS clause <clause> for a TEXTUAL-CONVENTION macro."
Type assignment, SNMPv2C-specific module semantic error. The status clause of a TEXTUAL-CONVENTION macro invocation must be "current," "deprecated," or "obsolete."

Fatal Error 1089

<1089, Fatal>: "<fileName>:<line#>: Symbol <identifier> in AUGMENTS clause does not resolve to a row OBJECT-TYPE"
OBJECT-TYPE macro invocation SNMPv2C-specific module semantic error. If an AUGMENTS clause is present, then the identifier in the AUGMENTS clause must resolve to a table OBJECT-TYPE.

Fatal Error 1090

<1090, Fatal>: "<fileName>:<line#> IMPLIED clause is useful only for the last INDEX object"
OBJECT-TYPE macro invocation SNMPv2C-specific module semantic error. The IMPLIED clause can be associated only with the last object in the INDEX clause.

Warning 1091

<1091, Warning>: "<fileName>:<line#> IMPLIED clause is not allowed for fixed size objects"
OBJECT-TYPE macro invocation SNMPv2C-specific module semantic warning. The IMPLIED keyword can only be present for an object having a variable-length syntax, such as an OBJECT IDENTIFIER or variable-length OCTET STRING, in the INDEX clause.

Fatal Error 1092

<1092, Fatal>: "<fileName>:<line#> IMPLIED clause not allowed for potentially zero-length objects"
OBJECT-TYPE macro invocation SNMPv2C-specific module semantic error. The IMPLIED clause cannot be used on a variable-length object if that object can have a zero length.

Fatal Error 1093

<1093. Fatal>: "<fileName><line#>: Only the type "INTEGER" can be enumerated according to the V1 SMI."
Type assignment, SNMPv1-specific module semantic error. An SNMPv1 MIB enumeration can use only the type INTEGER.

Fatal Error 1094

<1094. Fatal>: "<fileName><line#>: The type used in the enumeration does not resolve to one of the allowed types"
Type assignment, SNMPv2C-specific module semantic error. The type used in an enumeration must be INTEGER or an equivalent type, or another enumeration.

Fatal Error 1095

<1095. Fatal>: "<fileName><line#>: Enumeration member is not a member of the parent enumeration"
Type assignment, SNMPv2C-specific module semantic error. If another enumeration is used, its set of items must be a subset of the parent enumeration's set of items.

Fatal Error 1097

<1097, Fatal>: "<fileName><line#>: identifier <name> does not resolve to an integer value"
Type assignment, SNMPv2C-specific module semantic error. The values in the BITS type must be integer values.

Fatal Error 1098

<1098, Fatal>: "<fileName><line#>: Duplicate value <value> in BITS construct"
Type assignment, SNMPv2C-specific module semantic error. There must be no duplicate names and values in a BITS construct. The <line#> parameter is the position of the recurrence of the name/value.

Fatal Error 1099

<1099, Fatal>: "<fileName><line#>: Duplicate name <identifier> in BITS construct"
Type assignment, SNMPv2C-specific module semantic error. There must be no duplicate names and values in a BITS construct. The <line#> parameter is the position of the recurrence of the name/value.

Fatal Error 1101

<1101, Fatal>: "<fileName><line#>: The length of the range is too long for the compiler (Does not fit into 4 bytes)"
Module semantic error in range or size specification, specific to neither SNMPv1 nor SNMPv2C. The size of a set of ranges must be less than 232. The size of a set of ranges is defined as the difference between the largest value and the smallest value in the set.

Fatal Error 1451

<1451, Fatal>: "Could not connect to the SMIR"
SMIR interaction error.

Fatal Error 1453

<1453, Fatal>: "Module <module> does not exist in the SMIR"
SMIR interaction error. The module that has requested deletion does not exist in the SMIR.

Fatal Error 1502

<1502, Fatal>: "File <file> not found, or unreadable"
Run-time error. One or more files explicitly mentioned on the command line do not exist or are unreadable.


General Information Messages

These information messages describe compiler operation.

smi2smir: Version <version #> MIB definitions compiled from <file name>
This message appears at the beginning of every file compilation. It means the file may have been explicitly specified on the command line by the user, or it may have been pulled in by the compiler from the registry include directories or the include directories mentioned on the command line.
smi2smir: Syntax check failed on <file name>
The specific error messages that precede this message give the nature of the syntax errors.
smi2smir: Semantic check failed on <file name>
The specific error messages that precede this message give the nature of the semantic errors.
smi2smir: Could not load <file name> into the smir
Syntax or semantic check failed on the module, or SMIR interaction was not complete.
smi2smir: Syntax check successful on <file name>
smi2smir: Semantic check successful on <file name>
smi2smir: Loaded <file name> successfully into the smir
smi2smir: Could not resolve one or more symbols in <module name>
The modules corresponding to one or more of the imported symbols in the specified module was not found or could not be compiled.
smi2smir: Could not connect to the SMIR
Ensure that SMIR.DLL exists, has been registered using the regsvr32 command, and that the Windows Management Instrumentation (WMI) server is up and running.
smi2smir: Modules in the SMIR: <list of modules, 1 on each line>
This is the output of the /l switch.
smi2smir Could not list the modules in the SMIR
This indicates a failure of the /l switch due to no SMIR connection.
smi2smir: Deleted module <module name> successfully
The /d switch succeeded.
smi2smir: Could not delete module <module name>
This indicates a failure of the /d switch due to no SMIR connection.
smi2smir: Deleted all the modules in the SMIR
The /p switch succeeded.
smi2smir: Could not delete all the modules in the SMIR
The /p switch failed because there is no SMIR connection.
smi2smir: Module <module name> does not exist in the SMIR
The /d switch failed because the specified module is not in the SMIR.
smi2smir: Generated MOF successfully
The /g or /gc switch worked successfully.
smi2smir: Could not generate MOF
The /g or /gc switch did not work successfully due to no SMIR connection.
smi2smir: Name of the module: <module name>
This is the successful output of the /n switch.
smi2smir: Could not parse <file name> successfully
This indicates failure of the /n or /ni switch because the specified file is not a valid MIB file.
smi2smir: Processed <number> files successfully
This specifies the number of files that were successfully parsed when the /r or the /auto switch were used.
smi2smir: Repeated files in the input for module <module name>. Only the file <file name> will be compiled
The user has explicitly specified more than one file on the command line, and two or more of these files have the same MIB module.
smi2smir: Added directory <directory name> to the registry
Success of the /pa switch.
smi2smir: Could not add directory <directory name> to the registry
Failure of the /pa switch, which happens only if the registry API fails.
smi2smir: Deleted directory <directory name> from the registry
Success of the /pd switch.
smi2smir: Could not delete <directory name> from the registry
Failure of the /pd switch. The specified directory does not exist in the list of directories in the registry.
smi2smir: <file name> is not a valid mib file
More than one file has been specified on the command line, one of which is not a valid MIB file.

See Also

Running the SNMP Compiler


Return Codes

This section provides a listing of the symbolic constants, their literal values, and descriptions, that are returned by Windows Management Instrumentation (WMI) in HRESULT.

  • WMI Error Constants
  • WMI Non-Error Constants


WMI Error Constants

If an error occurs, WMI returns one of the following error codes as an HRESULT value.

WBEM_E_FAILED
0x80041001
The call failed.
WBEM_E_NOT_FOUND
0x80041002
The object could not be found.
WBEM_E_ACCESS_DENIED
0x80041003
The current user does not have permission to perform the action.
WBEM_E_PROVIDER_FAILURE
0x80041004
The provider has failed at some time other than during initialization.
WBEM_E_TYPE_MISMATCH
0x80041005
A type mismatch occurred.
WBEM_E_OUT_OF_MEMORY
0x80041006
There was not enough memory for the operation.
WBEM_E_INVALID_CONTEXT
0x80041007
The IWbemContext object is not valid.
WBEM_E_INVALID_PARAMETER
0x80041008
One of the parameters to the call is not correct.
WBEM_E_NOT_AVAILABLE
0x80041009
The resource, typically a remote server, is not currently available.
WBEM_E_CRITICAL_ERROR
0x8004100A
An internal, critical, and unexpected error occurred. Report this error to Microsoft Technical Support.
WBEM_E_INVALID_STREAM
0x8004100B
One or more network packets were corrupted during a remote session.
WBEM_E_NOT_SUPPORTED
0x8004100C
The feature or operation is not supported.
WBEM_E_INVALID_SUPERCLASS
0x8004100D
The superclass specified is not valid.
WBEM_E_INVALID_NAMESPACE
0x8004100E
The namespace specified could not be found.
WBEM_E_INVALID_OBJECT
0x8004100F
The specified instance is not valid.
WBEM_E_INVALID_CLASS
0x80041010
The specified class is not valid.
WBEM_E_PROVIDER_NOT_FOUND
0x80041011
A provider referenced in the schema does not have a corresponding registration.
WBEM_E_INVALID_PROVIDER_REGISTRATION
0x80041012
A provider referenced in the schema has an incorrect or incomplete registration. This error may be caused by any of the following
  • A missing namespace pragma in the MOF file used to register the provider, resulting in the provider being registered in the wrong WMI namespace.
  • A corrupt repository which may be fixed by deleting it and recompiling the MOFs.
WBEM_E_PROVIDER_LOAD_FAILURE
0x80041013
COM cannot locate a provider referenced in the schema. This error may be caused by any of the following:
  • The provider is using a WMI .dll that does not match the .lib used when the provider was built
  • The provider's .dll or any of the .dll's on which it depends is corrupt.
  • The provider failed to export DllRegisterServer.
  • An in-process provider was not registered using /regsvr32.
  • An out-of-process provider that was not registered using /regserver.
WBEM_E_INITIALIZATION_FAILURE
0x80041014
A component, such as a provider, failed to initialize for internal reasons.
WBEM_E_TRANSPORT_FAILURE
0x80041015
A networking error that prevents normal operation has occurred.
WBEM_E_INVALID_OPERATION
0x80041016
The requested operation is not valid. This error usually applies to invalid attempts to delete classes or properties.
WBEM_E_INVALID_QUERY
0x80041017
The query was not syntactically valid.
WBEM_E_INVALID_QUERY_TYPE
0x80041018
The requested query language is not supported.
WBEM_E_ALREADY_EXISTS
0x80041019
In a Put operation, the wbemChangeFlagCreateOnly flag was specified, but the instance already exists.
WBEM_E_OVERRIDE_NOT_ALLOWED
0x8004101A
It is not possible to perform the Add operation on this qualifier because the owning object does not permit overrides.
WBEM_E_PROPAGATED_QUALIFIER
0x8004101B
The user attempted to delete a qualifier that was not owned. The qualifier was inherited from a parent class.
WBEM_E_PROPAGATED_PROPERTY
0x8004101C
The user attempted to delete a property that was not owned. The property was inherited from a parent class.
WBEM_E_UNEXPECTED
0x8004101D
The client made an unexpected and illegal sequence of calls, such as calling EndEnumereation before calling BeginEnumeration.
WBEM_E_ILLEGAL_OPERATOR
0x8004101E
The user requested an illegal operation, such as spawning a class from an instance.
WBEM_E_CANNOT_BE_KEY
0x8004101F
There was an illegal attempt to specify a key qualifier on a property that cannot be a key. The keys are specified in the class definition for an object, and cannot be altered on a per-instance basis.
WBEM_E_INCOMPLETE_CLASS
0x80041020
The current object is not a valid class definition. Either it is incomplete, or it has not been registered with WMI using SWbemObject.Put_.
WBEM_E_READ_ONLY
0x80041023
The property that you are attempting to modify is read-only.
WBEM_E_PROVIDER_NOT_CAPABLE
0x80041024
The provider cannot perform the requested operation. This would include a query that is too complex, retrieving an instance, creating or updating a class, deleting a class, or enumerating a class.
WBEM_E_CLASS_HAS_CHILDREN
0x80041025
An attempt was made to make a change that would invalidate a subclass.
WBEM_E_CLASS_HAS_INSTANCES
0x80041026
An attempt has been made to delete or modify a class that has instances.
WBEM_E_ILLEGAL_NULL
0x80041028
A value of Nothing was specified for a property that may not be Nothing, such as one that is marked by a key, indexed, or not_null qualifier.
WBEM_E_INVALID_QUALIFIER_TYPE
0x80041029
The variant value for a qualifier was provided that is not of a legal qualifier type.
WBEM_E_INVALID_PROPERTY_TYPE
0x8004102A
The CIM type specified for a property is not valid.
WBEM_E_VALUE_OUT_OF_RANGE
0x8004102B
The request was made with an out-of-range value, or is incompatible with the type.
WBEM_E_CANNOT_BE_SINGLETON
0x8004102C
An illegal attempt was made to make a class singleton, such as when the class is derived from a non-singleton class.
WBEM_E_INVALID_CIM_TYPE
0x8004102D
The CIM type specified is not valid.
WBEM_E_INVALID_METHOD
0x8004102E
The requested method is not available.
WBEM_E_INVALID_METHOD_PARAMETERS
0x8004102F
The parameters provided for the method are not valid.
WBEM_E_SYSTEM_PROPERTY
0x80041030
There was an attempt to get qualifiers on a system property.
WBEM_E_INVALID_PROPERTY
0x80041031
The property type is not recognized.
WBEM_E_CALL_CANCELLED
0x80041032
An asynchronous process has been canceled internally or by the user. Note that due to the timing and nature of the asynchronous operation the operation may not have been truly canceled.
WBEM_E_SHUTTING_DOWN
0x80041033
The user has requested an operation while WMI is in the process of shutting down.
WBEM_E_PROPAGATED_METHOD
0x80041034
An attempt was made to reuse an existing method name from a superclass, and the signatures did not match.
WBEM_E_UNSUPPORTED_PARAMETER
0x80041035
One or more parameter values, such as a query text, is too complex or unsupported. WMI is therefore requested to retry the operation with simpler parameters.
WBEM_E_MISSING_PARAMETER_ID
0x80041036
A parameter was missing from the method call.
WBEM_E_INVALID_PARAMETER_ID
0x80041037
A method parameter has an invalid id qualifier.
WBEM_E_NONCONSECUTIVE_PARAMETER_IDS
0x80041038
One or more of the method parameters have id qualifiers that are out of sequence.
WBEM_E_PARAMETER_ID_ON_RETVAL
0x80041039
The return value for a method has an id qualifier.
WBEM_E_INVALID_OBJECT_PATH
0x8004103A
The specified object path was invalid.
WBEM_E_OUT_OF_DISK_SPACE
0x8004103B
There is not enough free disk space to continue the operation.
WBEM_E_BUFFER_TOO_SMALL
0x8004103C
The supplied buffer was too small to hold all the objects in the enumerator or to read a string property.
WBEM_E_UNSUPPORTED_PUT_EXTENSION
0x8004103D
The provider does not support the requested put operation.
WBEM_E_UNKNOWN_OBJECT_TYPE
0x8004103E
An object with an incorrect type or version was encountered during marshaling.
WBEM_E_UNKNOWN_PACKET_TYPE
0x8004103F
A packet with an incorrect type or version was encountered during marshaling.
WBEM_E_MARSHAL_VERSION_MISMATCH
0x80041040
The packet has an unsupported version.
WBEM_E_MARSHAL_INVALID_SIGNATURE
0x80041041
The packet appears to be corrupted.
WBEM_E_INVALID_QUALIFIER
0x80041042
An attempt has been made to mismatch qualifiers, such as putting [key] on an object instead of a property.
WBEM_E_INVALID_DUPLICATE_PARAMETER
0x80041043
A duplicate parameter has been declared in a CIM method.
WBEM_E_SERVER_TOO_BUSY
0x80041045
A call to IWbemObjectSink::Indicate has failed. The provider may choose to refire the event.
WBEM_E_INVALID_FLAVOR
0x80041046
The specified flavor was invalid.
WBEM_E_CIRCULAR_REFERENCE
0x80041047
An attempt has been made to create a reference that is circular (for example, deriving a class from itself).
WBEM_E_UNSUPPORTED_CLASS_UPDATE
0x80041048
The specified class is not supported.
WBEM_E_CANNOT_CHANGE_KEY_INHERITANCE
0x80041049
An attempt was made to change a key when instances or subclasses are already using the key.
WBEM_E_CANNOT_CHANGE_INDEX_INHERITANCE
0x80041050
An attempt was made to change an index when instances or subclasses are already using the index.
WBEM_E_TOO_MANY_PROPERTIES
0x80041051
An attempt was made to create more properties than the current version of the class supports.
WBEM_E_UPDATE_TYPE_MISMATCH
0x80041052
A property was redefined with a conflicting type in a derived class.
WBEM_E_UPDATE_OVERRIDE_NOT_ALLOWED
0x80041053
An attempt was made in a derived class to override a non-overrideable qualifier.
WBEM_E_UPDATE_PROPAGATED_METHOD
0x80041054
A method was redeclared with a conflicting signature in a derived class.
WBEM_E_METHOD_NOT_IMPLEMENTED
0x8004105
An attempt was made to execute a method not marked with [implemented] in any relevant class.
WBEM_E_METHOD_DISABLED
0x80041056
An attempt was made to execute a method marked with [disabled].
WBEM_E_REFRESHER_BUSY
0x80041057
The refresher is busy with another operation.
WBEM_E_UNPARSABLE_QUERY
0x80041058
The filtering query is syntactically invalid.
WBEM_E_NOT_EVENT_CLASS
0x80041059
The FROM clause of a filtering query references a class that is not an event class(not derived from __Event.)
WBEM_E_MISSING_GROUP_WITHIN
0x8004105A
A GROUP BY clause was used without the corresponding GROUP WITHIN clause.
WBEM_E_MISSING_AGGREGATION_LIST
0x8004105B
A GROUP BY clause was used. Aggregation on all properties is not supported.
WBEM_E_PROPERTY_NOT_AN_OBJECT
0x8004105C
Dot notation was used on a property that is not an embedded object.
WBEM_E_AGGREGATING_BY_OBJECT
0x8004105D
A GROUP BY clause references a property that is an embedded object without using dot notation.
WBEM_E_UNINTERPRETABLE_PROVIDER_QUERY
0x8004105F
An event provider registration query (__EventProviderRegistration) did not specify the classes for which events were provided.
WBEM_E_BACKUP_RESTORE_MINMGMT_RUNNING
0x80041060
An request was made to back up or restore the repository while WinMgmt was using it.
WBEM_E_QUEUE_OVERFLOW
0x80041061
The asynchronous delivery queue overflowed due to the event consumer being too slow.
WBEM_E_PRIVILEGE_NOT_HELD
0x80041062
The operation failed because the client did not have the necessary security privilege.
WBEM_E_INVALLID_OPERATOR
0x80041063
The operator is not valid for this property type.
WBEM_E_LOCAL_CREDENTIALS
0x80041064
The user specified a username/password on a local connection. The user must use a black username/password and rely on default security.
WBEM_E_CANNOT_BE_ABSTRACT
0x80041065
The class was made abstract when its superclass is not abstract.
WBEM_E_AMENDED_OBJECT
0x80041066
An amended object was PUT without the WBEM_FLAG_USE_AMENDED_QUALIFIERS flag being specified.
WBEM_E_CLIENT_TOO_SLOW
0X80041067
The client was not retrieving objects quickly enough from an enumeration.
WBEMESS_E_REGISTRATION_TOO_BROAD
0x80042001
The provider registration overlaps with the system event domain.
WBEMESS_E_REGISTRATION_TOO_PRECISE
0x80042002
A 'WITHIN' clause was not used in this query.


WMI Non-Error Constants

If an operation does not result in an error, Windows Management Instrumentation (WMI) will return one of the following codes as an HRESULT indicating the status of the operation.

WBEM_NO_ERROR
0x0
The operation was successful.
WBEM_S_NO_ERROR
0x0
The operation was successful.

The objects are the same, subject to comparison flags.

This will be returned when no more objects are available, the number of objects returned is less than the number requested, or at the end of an enumeration. It is also returned when this method is called with a value of zero for the uCount parameter.

WBEM_S_ALREADY_EXISTS
0x40001
An attempt was made to create an object or class that already exists.
WBEM_S_RESET_TO_DEFAULT
0x40002
An overridden property was deleted.
This value is returned to signal that the original non-overridden value has been restored as a result of the deletion.
WBEM_S_DIFFERENT
0x40003
The items (objects, classes, etc.) being compared are not identical.
WBEM_S_TIMEOUT
0x40004
A call timed out.
This is not an error condition. Therefore, some results may have also been returned.
WBEM_S_NO_MORE_DATA
0x40005
No more data is available from the enumeration, and the user should terminate the enumeration.
WBEM_S_OPERATION_CANCELLED
0x40006
The operation was intentionally or unintentionally canceled.
WBEM_S_PENDING
0x40007
A request is still in progress, and the results are not yet available.
WBEM_S_DUPLICATE_OBJECTS
0x40008
More that one copy of the same object was detected in the result set of an enumeration.
WBEM_S_ACCESS_DENIED
0x40009
The user was denied access to some but not all resources.
WBEM_S_PARTIAL_RESULTS
0x40010
The user did not receive all of the objects requested due to inaccessible resources (other than security violations).
WBEM_S_LIMITED_SERVICE
0x43001
The provider is capable of limited service.


WMI Glossary

The Windows Management Instrumentation (WMI) Software Development Kit (SDK) uses its own collection of terms. Many of these terms are familiar to developers, but have new or altered definitions in the WMI SDK environment. Please review the following definitions to understand the WMI implementation of these terms.

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z


A

abstract class
A WMI base class used only as a template for derived classes. The __Event system class, for example, is an abstract class: Real-world events are modeled using classes derived from the __Event class, and instances are created from the __Event subclasses.

aggregate event
A type of event that is generated after a series of events of another type have occurred. An aggregate event is used to represent a series of events to avoid flooding the event consumer. Aggregate events are instances of the __AggregateEvent class.
alias
A symbolic reference in either a class or instance declaration to an object located elsewhere in a MOF file. Alias names follow the same rules as instance and class names. Aliases are typically used as shortcuts to lengthy object paths. To define an alias, add the phrase "as $AliasName" to the instance or class declaration.
association class
A class that describes a relationship between two classes or between instances of two classes. The properties of an association class include pointers, or references, to the two classes or instances. The Association qualifier is attached to every association class for identification.
ASSOCIATORS OF
A WMI Query Language statement that supports the traversal of associations programmatically by retrieving all endpoint instances that are associated with a particular source instance. Also see ASSOCIATORS OF Statement.
asynchronous method
A method that returns to the caller immediately regardless of whether processing has completed. The results of processing are returned through another call on another thread. Asynchronous methods free the caller from having to wait until processing has finished. Also see Making an Asynchronous Call.
B C D E F G H I J K L M N O P Q R S T U V W X Y Z


B

Backus-Naur Form (BNF)
Backus-Naur Form. A metalanguage that specifies the syntax of programming languages.
A C D E F G H I J K L M N O P Q R S T U V W X Y Z


C

CIM repository
A central storage area managed by the CIM Object Manager. Static classes with static instances store the class definitions and the instances in the CIM repository. Static classes with dynamic instances store only the definitions. Dynamic classes store neither the class definitions nor the instances. Dynamic information is always supplied on demand by a provider.
CIM schema
A collection of class definitions used to represent managed objects that occur in every management environment. Also see core model, common model, and extension schema.
CIM class
See class.
class
A template for a type of managed object. WMI classes define the basic units of management. For example, the Win32_LogicalDisk class is a template for all logical disks that occur in the Win32 environment. Also see WMI Classes.
class provider
A COM server that supplies class definitions. Class providers implement methods in the IWbemServices interface to support data retrieval, modification, deletion, enumeration, and query processing. Also see Class and Instance Providers.
Common Information Model (CIM)
The Common Information Model (CIM) describes how to represent real-world managed objects. CIM uses an object-oriented paradigm, where managed objects are modeled using the concepts of classes and instances.

The CIM is divided into the metamodel and the standard schema. The metamodel describes what types of entities make up the schema. It also defines how these entities can be combined into objects that represent real-world devices. Also see Common Information Model (CIM).

CIM Object Manager
A component in the WMI management infrastructure that handles the interaction between management applications and providers. The CIM Object Manager supports services such as event notification, remote access, and query processing. The CIM Object Manager also grants access to the CIM repository.
common model
The second layer of the CIM schema, which includes a series of domain-specific but platform-independent classes. The domains are systems, networks, applications, and other management-related data. The common model is derived from the core model. Also see extension schema.
Component Object Model (COM)
The object-oriented programming model that defines how objects interact within a single process or between processes. In COM, clients have access to an object through interfaces implemented on the object.
consumer-filter binding
An instance of the __FilterToConsumerBinding system class that describes a relationship between a logical consumer and an event filter. A component of the permanent consumer architecture. Also see Linking Event Filters with Logical Consumers.
core model
The first layer of the CIM schema, which includes the top-level classes, their properties, and their associations. The core model is both domain- and platform-independent. Also see common model and extension schema.
A B D E F G H I J K L M N O P Q R S T U V W X Y Z


D

Distributed COM (DCOM)
The protocol used for communication between local and remote WMI components.
dynamic class
A CIM class whose definition is supplied by a provider at runtime as needed. Dynamic classes are used to represent provider-specific managed objects and are not stored in the CIM repository. Dynamic classes support only dynamic instances. Also see WMI Classes and Class and Instance Providers.
dynamic instance
An instance of a CIM class that is supplied by a provider when the need arises. It is not stored in the CIM repository. Dynamic instances can be provided for either static or dynamic classes. Supporting instances of a class dynamically allows a provider to always supply up-to-the-minute property values.
A B C E F G H I J K L M N O P Q R S T U V W X Y Z


E

event
An occurrence of a change to static or dynamic data related to a managed object. Also see Event Notification.
event consumer
A recipient of notifications that report the occurrence of an event. Event consumers are either temporary or permanent. Also see Temporary Event Consumers and Permanent Event Consumers.
event consumer provider
A COM server that maps physical consumers to logical consumers. Event consumer providers support the IWbemEventConsumerProvider interface.

Also see Permanent Consumer Architecture, Implementing an Event Consumer Provider, and Event and Event Consumer Providers.

event filter
An instance of the __EventFilter system class that describes an event type and the conditions under which a notification is delivered. Consumers use event filters to register to receive notification of a particular type of event. Also see Creating an Event Filter.
event provider
A COM server that generates event notifications. Event providers implement the IWbemProviderInit and IWbemEventProvider interfaces. Some event providers also implement IWbemEventProviderQuerySink. Also see Event and Event Consumer Providers and Implementing an Event Provider.
event query
A WMI Query Language statement that is used by event consumers to register to receive notification of particular events and by event providers to register to generate notifications of particular events. Also see Event Queries.
extension schema
The third layer of the CIM schema, which includes platform-specific extensions of the CIM schema such as Microsoft® Windows NT®/Windows® 2000, UNIX, and Microsoft® Exchange Server. Also see common model and core model.
A B C D F G H I J K L M N O P Q R S T U V W X Y Z


F

flavor
A WMI-defined flag that describes the behavior of a qualifier. WMI flavors describe rules that specify whether a qualifier can be propagated to derived classes and instances and whether a derived class or instance can override the qualifier's original value. Also see Qualifier Flavors and Qualifiers.
A B C D E G H I J K L M N O P Q R S T U V W X Y Z


G

GROUP
A clause in the WQL SELECT statement used to request that multiple notifications be combined into single instances of the system class __AggregateEvent. Also see GROUP Clause.
A B C D E F H I J K L M N O P Q R S T U V W X Y Z


H

HAVING
A clause in the WQL SELECT statement used to set a minimum limit on the number of discrete events that produce an aggregate event, reducing overall event traffic. Also see HAVING Clause.
A B C D E F G I J K L M N O P Q R S T U V W X Y Z


I

indication
See event.
inheritance
A classification that allows a child class to contain the properties and methods of a parent class. The parent class is also called the superclass; the child class is also called the subclass. Also see WMI Classes.
instance
A representation of a real-world managed object that belongs to a particular class. Instances contain actual data. Also see Classes and Instances.
instance provider
A COM server that supplies instances of classes and implements methods of the IWbemServices interface to support data retrieval, modification, deletion, enumeration, or query processing. Also see Class and Instance Providers.
ISA
An operator in the WQL WHERE clause, used to retrieve instances from a class hierarchy. Also see ISA Operator for Event Queries and ISA Operator for Data Queries.
A B C D E F G H J K L M N O P Q R S T U V W X Y Z


K

key
A property that provides a unique identifier for an instance of a class. Key properties are marked with the Key qualifier. Also see Key Properties.
Key qualifier
A qualifier that must be attached to every property in a class that serves as part of the key for that class. Also see WMI Standard Qualifiers.
A B C D E F G H I J L M N O P Q R S T U V W X Y Z


L

lazy property
A property that is marked with a lazy qualifier, indicating that the property is expensive to return. A lazy qualifier on a property indicates that the property requires a lot of processer time and memory. WMI improves the performance of queries by not attempting to return the properties marked with the lazy qualifier.

Because WQL queries containing lazy properties can fail, properties marked with the lazy qualifier are not returned by SQLColumns.

local property
A non-system property defined for a class, but not inherited from a superclass.
logical consumer
An instance of a class derived from the __EventConsumer system class. The properties of the class describe the action to be taken upon receipt of a notification. A component of the permanent consumer architecture. Also see Permanent Event Consumers.
A B C D E F G H I J K M N O P Q R S T U V W X Y Z


M

managed object
A hardware or software system component that is represented as an instance of a WMI class. Information about managed objects is supplied by data and event providers, as well as by the CIM Object Manager.
Managed Object Format (MOF)
A language based on Interface Definition Language (IDL) that describes management information. The MOF syntax is a way to describe object definitions in textual form. The MOF Compiler processes a MOF file and adds the required object definitions to the CIM repository.
management application
An application or Microsoft® Windows NT®/Windows® 2000 service that uses information originating from one or more managed objects in a managed environment. Management applications retrieve this information through calls to the CIM Object Manager API from the CIM Object Manager and from providers.
management information base
MIB. MIB is a database of managed objects.
metamodel
A CIM component that describes the entities and relationships representing managed objects. For example, classes, instances, and associations are included in the metamodel.
metaschema
The schema of the metamodel.
method
A function describing the behavior of a class. Including a method in a class does not guarantee an implementation of the method. The Implemented qualifier is attached to the method to indicate that an implementation is available for the class.

A method is also a function included in a WMI Reference interface. Also see Declaring Methods and Calling a Method.

MOF file
A text file that contains definitions of classes and instances using the Managed Object Format (MOF) language.
A B C D E F G H I J K L N O P Q R S T U V W X Y Z


N

namespace
A unit for grouping classes and instances to control their scope and visibility. Namespaces are not physical locations; they are more like logical databases containing specific classes and instances. Namespaces are represented by the __Namespace system class or a class derived from it.
A B C D E F G H I J K L M O P Q R S T U V W X Y Z


O

object path
A formatted string used to access namespaces, classes, and instances. Each object on the system has a unique path that identifies it locally or over the network. Object paths are conceptually similar to Universal Resource Locators (URL). Also see Object Paths.
A B C D E F G H I J K L M N P Q R S T U V W X Y Z


P

permanent consumer
An event consumer whose registration lasts until it is explicitly cancelled. Compare temporary consumer. Also see Permanent Consumers.
physical consumer
COM object implemented by an event consumer provider that includes a sink for receiving event notifications.
polymorphism
The ability to alter methods and properties in a derived class without changing their names or altering interfaces.
property
A name/value pair that describes a unit of data for a class. Property values must have a valid Managed Object Format (MOF) data type. Also see reference property, MOF Data Types, and Classes and Properties.
property provider
A COM server that supports the retrieval and modification of WMI properties. Property providers implement the IWbemProviderInit and IWbemPropertyProvider interfaces. Also see Property Providers.
provider
A COM server that communicates with managed objects to access data and event notifications from a variety of sources, such as the system registry or an SNMP device. Providers forward this information to the CIM Object Manager for integration and interpretation. Also see WMI Providers and Programming Basics for WMI Providers.
A B C D E F G H I J K L M N O Q R S T U V W X Y Z


Q

qualifier
A modifier containing information that describes a class, an instance, a property, a method, or a parameter. Qualifiers are defined by the Common Information Model (CIM), by the CIM Object Manager, and by developers. Also see WMI Standard Qualifiers, Qualifiers, and Using Qualifiers.
qualifier flavor
See flavor.
A B C D E F G H I J K L M N O P R S T U V W X Y Z


R

reference property
A property that uses one of the user-defined classes as its type. A reference property can be thought of as a pointer to an instance in the referenced target class. Reference properties are implemented as strings containing the path of the referenced instance. Also see MOF Ref Data Type.
REFERENCES OF
A WMI Query Language statement that supports the traversal of associations programmatically by retrieving all association instances that refer to a particular source instance. Also see REFERENCES OF Statement.
required property
A property that must have a value.
A B C D E F G H I J K L M N O P Q S T U V W X Y Z


S

schema
A collection of class definitions that describe managed objects in a particular environment.
SELECT
A WMI Query Language statement used to retrieve information. Unlike SQL, which supports queries across multiple tables, WQL supports only single class queries. Also see ASSOCIATORS OF, REFERENCES OF, WITHIN, GROUP , HAVING, ISA, SELECT Statement for Data Queries, SELECT Statement for Event Queries, and SELECT Statement for Schema Queries topics.
singleton class
A WMI class that supports only a single instance. Also see Singleton Classes.
sink
A COM object that acts as the physical delivery destination for the results of an asynchronous operation or an event notification. Sinks implemented by permanent consumers support the IWbemUnboundObjectSink interface. Sinks implemented by temporary consumers and applications making asynchronous calls support the IWbemObjectSink interface.

Also see Making an Asynchronous Call, Implementing IWbemUnboundObjectSink, and Implementing IWbemObjectSink.

standard provider
A provider that is built into the WMI SDK, as distinguished from third-party or custom providers. Also see WMI Providers.
standard qualifier
A qualifier that the CIM Object Manager automatically attaches to a class, instance, property, method, or parameter of a method. Also see WMI Standard Qualifiers and Qualifiers.
standard schema
A common conceptual framework for organizing and relating the various classes representing the current operational state of a system, network, or application. The standard schema is defined by the Distributed Management Task Force (DMTF) in the Common Information Model (CIM).
static class
A CIM class whose definition changes infrequently if at all and is stored in the CIM repository until it is explicitly deleted. The CIM Object Manager can provide definitions of static classes without the help of a provider. Static classes can support either static or dynamic instances.
static instance
An instance of a CIM class that is persistently stored in the CIM repository and remains valid until explicitly deleted, even across system reboots.
subclass
A class that is derived from a superclass. The subclass inherits all of the properties and methods of its superclass. Also see WMI Classes.
subschema
A part of a schema owned by a particular organization. The Win32 schema is an example of a subschema.
superclass
The class from which a subclass inherits. Also see WMI Classes.
system class
A class defined by the CIM Object Manager to support core features such as event notification and security, and localization. System classes are automatically defined in every namespace. All system classes derive from the abstract base class __SystemClass. Also see WMI System Classes and WMI Classes.
system property
A property defined by the CIM Object Manager to provide information applicable to every class such as its name, its derivation, and its namespace. Also see WMI System Properties and Classes and Properties.
A B C D E F G H I J K L M N O P Q R T U V W X Y Z


T

temporary consumer
A consumer that receives event notifications only while the consumer is active. Also see Temporary Event Consumers.
timer event
An event that either occurs once at a particular time of day (absolute timer event) or repeatedly at regular intervals (interval timer event). A timer event differs from other events in that it requires explicit action by the consumer in order for it to occur. Notifications of timer events are sent by the CIM Object Manager. A timer event is represented by an instance of the system class __TimerEvent. Also see Timer Events.
A B C D E F G H I J K L M N O P Q R S U V W X Y Z


V

virtual function table (VTBL)
A table of function pointers, such as an implementation of a class. The pointers in the VTBL point to the members of the interfaces that an object supports.
A B C D E F G H I J K L M N O P Q R S T U W X Y Z


W

WMI Open Database Connectivity (ODBC) Adapter
The WMI Open Database Connectivity (ODBC) interface allows applications to get information from Windows Management using WMI Query Language. This provides a standard API that allows ODBC-based applications to use the data in the Common Information Management (CIM) repository as if it were a database. Also see WMI ODBC Adapter.
WMI Query Language
A dialect of structured query language (SQL) with extensions to support WMI event notification and other WMI-specific features. Also see WMI Query Language.
WHERE
A clause in the WQL SELECT statement that constrains a query such that subsets of class definitions or class instances can be selected. WHERE clauses can also be used to limit the scope of event notifications.
Win32 schema
A Microsoft extension to the CIM schema that contains definitions of classes and instances to represent managed objects that exist in a typical Win32 environment.
WMI for Windows Driver Model (WDM)
An important low-level component that provides access between Windows Management Instrumentation (WMI) and hardware devices.

WITHIN
A clause in the WQL SELECT statement that constrains the granularity of event delivery time and supports polling for events when no event provider is available. Also see WITHIN Clause and Event Queries.
A B C D E F G H I J K L M N O P Q R S T U V X Y Z


WMI Command-Line Syntax

On computers running Microsoft® Windows NT®/Windows® 2000, Windows Management Instrumentation (WMI) runs as a service. On computers running Microsoft® Windows® 95/98, the Windows Management Service runs as an application. You can invoke the Windows Management Service on either operating system by running the executable file WinMgmt.exe.

Note Much of the functionality provided through services in Windows NT/Windows 2000 is provided as individual applications in Windows 95/98.

You can stop and restart WMI manually whenever you want.

For additional information on starting and stopping WMI see:

  • Starting the Windows Management Service
  • Halting the Windows Management Service
  • Setting Registry Entries for Windows 95/98 Systems


Starting the Windows Management Service

Depending on which platform you are running, you will use one of two procedures to start the Windows Management Service. The two procedures are for:

  • Starting on Computers Running Windows NT/Windows 2000
  • Starting on Computers Running Windows 95/98

Note On computers running Microsoft® Windows® 95 or Microsoft® Windows® 98, the Windows Management Service runs as a regular program. You can start the program by running the executable, WinMgmt.exe.


Starting on Computers Running Windows NT/Windows 2000

Windows Management Service starts automatically on computers running Microsoft® Windows NT® and Microsoft® Windows® 2000. Since it is possible to halt the Windows Management Service it may be necessary to restart it at a later time. To start Windows Management Service on computers running Windows NT/Windows 2000, run the net start winmgmt command.

To start Windows Management Service, click the Start button and then click Run. , type the following:

net start winmgmt

Note You must have administrative rights to run net start winmgmt.

See Winmgmt.exe Switches for switches that may be used when launching winmgmt.


Starting on Computers Running Windows 95/98

With the winmgmt command, you can use the switch /exe, /regserver, or /unregserver to start WMI.

On computers running Microsoft® Windows® 95 or Microsoft® Windows® 98, the Windows Management Service runs as a regular program. You can start the program by running the executable, WinMgmt.exe.

Before you start the Windows Management Service on Windows 95/98, you must change certain values in the operating system registry. For more information on this process, see Setting Registry Entries for Windows 95/98 Systems.

To start WMI, click the Start button and then click Run. In the , type the following:

winmgmt

See Winmgmt.exe Switches for switches that may be used when launching winmgmt.


Winmgmt.exe Switches

The following switches are available at the command line with winmgmt. Some of the switches are not supported on all platforms.

winmgmt

[/exe]

[/kill]

[/regserver]

[/unregserver]

[/backup <filename>]

[/restore <filename>]

[/resyncperf <wimmgmt service process id>]

[/clearadap]

/exe
Causes the Windows Management Service to run as an application rather than as a Windows NT/Windows 2000 service. You only rarely use this switch since you almost always want to run WMI as a service. When the /exe switch is used, winmgmt is run in the user's security context. The primary use of the /exe switch in Microsoft® Windows NT version 4.0 is to make it easier to debug providers. This switch is available on Windows 95, Windows 98, Windows NT 4.0, and Windows 2000. Using this switch will place an icon in the task bar.
/kill
Terminates all Winmgmt.exe processes on the local system, including WMI processes started as a service by the Service Control manager or invoked by using the /exe switch. This switch is available on Windows 95, Windows 98, Windows NT 4.0, and Windows 2000. To use this switch with Windows NT you must have administrative rights.
/regserver
Registers the Windows Management Service, adding entries to the operating system registry. The /regserver switch should be implemented by any .exe server. This switch is available on Windows 95, Windows 98, Windows NT 4.0, and Windows 2000
/unregserver
Removes registry entries added through the self-registration process and should rarely be used. This switch is available on Windows 95, Windows 98, Windows NT 4.0, and Windows 2000
/backup <filename>
Causes WMI to back up the repository to the specified file name. The filename parameter should contain the full path to the file location. This process requires a write lock on the repository so that write operations to the repository are suspended until the backup process is completed. This switch is available on Windows 95, Windows 98, Windows NT 4.0, and Windows 2000
/restore <filename>
Manually restores the WMI repository from the specified file. The filename parameter should contain the full path to the file location. When restoring the repository, the process deletes the existing repository, writes the specified backup file to the automatic backup file, and then connects to WMI to perform the restoration. If exclusive access to the repository cannot be achieved, existing clients are disconnected from WMI. This switch is available on Windows 95, Windows 98, Windows NT 4.0, and Windows 2000
/resyncperf <winmgmt service process id>
Invokes the Auto-Detct/Auto-Purge (ADAP) mechanism of WMI. See Maintaining Performance Counter Classes for information on ADAP. This switch is only available on Windows 2000.
/clearadap
The ADAP utility stores state information about the system performance libraries in the registry. The /clearadap switch removes all of the ADAP information from the registry, effectively resetting the state of each performance library. This switch is only available on Windows 2000.


Halting the Windows Management Service

Depending on which platform you are running, you will use one of two procedures to halt the Windows Management Service. The two procedures are for:

  • Halting on Computers Running Windows NT/Windows 2000
  • Halting on Computers Running Windows 95/98


Halting on Computers Running Windows NT/Windows 2000

To stop the Windows Management Service on computers running Microsoft Windows NT/Windows 2000, run the net stop command on the winmgmt service, as described in the following procedure.

To stop the Windows Management Service

  1. Click the Start button.
  2. Select Run.
  3. In the Open box, type net stop winmgmt.
  4. Click OK.


Halting on Computers Running Windows 95/98

To stop the Windows Management Service on computers running Microsoft Windows 95/WIndows 98, run the winmgmt command with the /kill switch, as described in the following procedure.

To stop the Windows Management Service

  1. Click the Start button.
  2. Select Run.
  3. In the Open box, type winmgmt /kill.
  4. Click OK.


Setting Registry Entries for Windows 95/98 Systems

The Windows Management Service starts automatically on computers running Microsoft® Windows NT®/Windows® 2000, but not on computers running Microsoft® Windows® 95/98. To set up the Windows Management Service to start automatically on a Windows 95/98 system, you must make the following changes to the operating system registry.

To set up the Windows Management Service to run automatically on a computer running Windows 95/98

  1. In the registry, navigate to the value named EnableRemoteConnect?.
  2. Under the key HKLM\SOFTWARE\MICROSOFT\OLE\DCOM, set EnableDCOM? to "Y" if it is not set to "Y" already. "Y" is the default setting.
  3. In the registry under the key HKLM\SOFTWARE\MICROSOFT\OLE\DCOM, set EnableRemoteConnect? to "Y". The default setting for the EnableRemoteConnect? value is "N" for Windows 95/98 systems.
  4. Place the following entry in the registry to enable the WMI automatic start feature:

    HKLM\SOFTWARE\Microsoft\wbem\cimom - AutostartWin9X

  5. Set the AutostartWin9x value to either "1" or "2". The following table lists possible values for AutostartWin9x and their meanings.
    Value | Meaning
    "0" Manual (0): Use this setting when you do not need the service running continuously. When a local request comes in, WMI starts to service the request. If you later restart the computer, the computer will start in manual mode (WMI will not start automatically).

    Note that remote startup requests are only supported on Windows NT and Windows 2000. Remote startup requests are not supported by DCOM on Windows 95/98.
    "1" | Automatic if the computer system needs to reload (1): Use this setting if you would normally have active event consumers. If WMI has active event consumers and the system (Windows 95 OSR2, 98, NT4 SP4, and 2000) needs to be restarted, WMI starts automatically after the system starts.
    "2" | Automatic (2): Windows Management Service always starts automatically.

  6. Add the file Winmgmt.exe to the computer's Startup folder. You can find this file in the WBEM folder under the Windows folder.

For information about programmatically connecting to the Windows Management Service, see Connecting to WMI.


Wbemdump

Wbemdump is a Windows Management Instrumentation (WMI) application that can show Common Information Model (CIM) classes and instances, execute the methods of a CIM object, or run queries. The samples directory contains the source code for this application. The source code shows you how to write a WMI Component Object Model (COM) application. The executable Wbemdump.exe serves as a utility that lets you view information in the CIM repository. Some of the switches listed are useful to developers who are writing WMI providers.


Wbemdump Syntax

Syntax: wbemdump [switches] [Namespace [Class|ObjectPath] ]
        wbemdump /Q [switches] Namespace QueryLanguage Query

The following table defines the syntax used with Wbemdump.

Item | Meaning
Namespace | The namespace to dump (defaults to root\default)
Class | The specific class to dump (defaults to none)
ObjectPath | The object path of an instance for example, "SclassA.KeyProp=\"foobar\""
QueryLanguage | Any WMI supported query language (currently only "WQL" is supported).
Query | A valid WMI Query Language (WQL) query, enclosed in quotes.
Switches | One or more of the switches listed in the following table.

The following table lists the switches you can use with Wbemdump and describes how they modify program execution.

Switch | Meaning
/A:<Authority> | Sets authority to use when connecting to WMI .
/AL:<AuthenticationLevel> | Sets the authentication level that Wbemdump will use.
/B:<num> | Produces CreateEnum flags (SemiSync=16; Forward=32).
/C:<file> | Contains command file with multiple WBEMDUMP command lines. The same namespace must be used for each of the command lines.
/CQV:<name>[:value] | Specifies a class qualifier or qualifier value by which you can filter.
/D | Hides properties.
/E | Shows system classes and properties.
/E1 | Shows system classes and properties except __SERVER or __PATH properties.
/E2 | Shows command lines for dumping instances.
/G | Enumerated instances are returned by the GetObject call.
/G2 | Calls GetObject on all reference properties.
/G:<x> | Similar to /G but using x for flags parameter of GetObject.
/H:<name>:<value> | Specifies a context object value.
/I:<ImpLevel> | Sets impersonation level. Values for this parameter can be any of the following: Anonymous=1, Identify=2, Impersonate=3, Delegate=4 The default value is 3 or impersonate.
/L:<LoopCnt> | Specifies the number of times you want this command to run.
/Locale:<localid> | Specifies the locale that will be used.
/M | Gets Class Managed Object Formats (MOF) instead of data values.
/M2 | Gets Instance MOFs instead of data values.
/M3 | Produces instance template.
/O:<file> | Files name for output (creates Unicode file).
/P:<Password> | Password to use when connecting to WMI (default: NULL)
/Q | Executes a query.
/S | Displays information about this instance or class, or all subclasses.
/S2 | Displays information about all namespaces, or all namespaces within namespaces.
/T | Prints execution times for /Q queries.
/T2 | Prints execution times for enumerations using an alternate timer.
/U:<UserID> | Connects UserID with Wbemdump. (default: NULL).
/W | Prompts to continue on warning errors.
/WY | Prints warnings and continue.

Commands can be used in the following manner.

Command | Use
WBEMDUMP /S /E root\default | Dumps everything in the root\default namespace.
WBEMDUMP /S /E /M /M2 root\default | Dumps all class and instance MOFs.
WBEMDUMP root\default foo | Dumps all instances of the foo class.
WBEMDUMP root\default foo.name=\"bar\" | Dumps a specific instance of the foo class.
WBEMDUMP /S2 /M root | Dumps MOFs for all non-system classes in all Name spaces.
WBEMDUMP /Q root\cimv2 WQL "SELECT * FROM Win32_logicaldisk WHERE deviceID='C:' " | Queries the cimv2 namespace for information about the "C" drive on the local system.


Wbemdump /A:<Authority>

This switch causes the command to connect using the authority that you specify with the parameter Authority.


Wbemdump /AL:<AuthenticationLevel>

This switch sets the authentication level that will be used. The following table shows authentication levels and the numeric value you use with WBEMDUMP.

Authentication Level | Value
None | 1
Connect | 2
Call | 3
Packet | 4
Packet Integrity | 5
Packet Privacy | 6

Use the number that corresponds to the authentication level you want to use. For example:

wbemdump /AL:6 root\wmi

For more information on authentication levels see Setting the DCOM Authentication Level for the Scripting API


Wbemdump /B:<num>

This switch affects the way that wbemdump gets classes or instances. The output of the Wbemdump command should be unaffected when you use this switch. If you specify the number 16 as an argument with this switch, Wbemdump will call IWbemServices::CreateClassEnum or IWbemServices::CreateInstanceEnum semisynchronously.

If you specify an argument of 32 these methods will generate a forward-only enumerator. Forward-only enumerators are generally much faster and use less memory than conventional enumerators. You can combine both of these flags, For example:

WBEMDUMP /S /b:48 root/cimv2

Will display all the classes in the root/cimv2 namespace using a semisychronous forward-only enumerator.

See Also

Making a Semisynchronous Call


Wbemdump /C:<file>

This command causes Wbemdump to use a command file containing multiple WBEMDUMP command lines. Internally, Wbemdump will process each line of the command file as a separate GetObject() command without first calling CreateInstanceEnum. You can use this switch when testing a provider to see if it will behave differently if you get instances one at a time using GetObject() instead of getting instances all at once using CreateInstanceEnum(),and then calling GetObject() with all the objects in the enumeration.

The following example creates a command file that is then used with the /C:<file> switch. Windows Management service is stopped before the last command to ensure that no information is cached between calls to Wbemdump.

wbemdump /e2 root/cimv2 Win32_LogicalDisk > cmdfile.cmd
net stop winmgmt
wbemdump root\cimv2 /c:cmdfile.cmd

This set of commands should produce the same output as the command:

wbemdump root\cimv2 Win32_LogicalDisk

Note For this command to succeed, each line of the command file must contain an object path from the same namespace.


Wbemdump /CQV:<name>[:value]

This switch can be used specify a class qualifier or qualifier value by which you can filter. The following examples use this switch.

Command | Use
wbemdump /cqv:provider /d /s root\cimv2 | Lists all the classes that have a provider qualifier
wbemdump /cqv:provider:cimwin32 /d /s root\cimv2 | Lists the Win32 provider classes.
wbemdump /cqv:association /d /s root\cimv2 | Lists all classes with the 'association' qualifier


Wbemdump /D

This switch causes the command to only display classes. For example:

WBEMDUMP /S /D  root\cimv2 cim_ComputerSystem

produces the following output:

<ROOT\CIMV2>

CIM_ComputerSystem

CIM_UnitaryComputerSystem

Win32_ComputerSystem


Wbemdump /E

This switch causes the command to show system properties, in addition to non-system properties. If you do not specify this switch, only non-system properties will be displayed. For example,

WBEMDUMP /S /E root\cimv2 Win32_BIOS

will print all the properties associated with the Win32_BIOS class.

See Also

WMI System Classes


Wbemdump /E1

This switch causes the command to show all system properties except the __SERVER or __PATH properties. This switch might be useful when comparing the output from Wbemdump produced from different computers because these two properties are specific to the computer on which WMI is running. For example:

WBEMDUMP /S /E1 root\cimv2  Win32_NetworkAdapter


Wbemdump /E2

This switch causes the command to output the object path for all instances. You can redirect the output from this command to generate a command file for use with the /C switch. For example:

wbemdump /E2 root/cimv2 win32_LogicalDisk > CMDFILE.CMD

After you run the example above, the file CMDFILE.CMD will contain object paths to all the instances of this class as shown below.

"Win32_LogicalDisk.DeviceID=\"A:\""
"Win32_LogicalDisk.DeviceID=\"C:\""
"Win32_LogicalDisk.DeviceID=\"D:\""
"Win32_LogicalDisk.DeviceID=\"E:\""
"Win32_LogicalDisk.DeviceID=\"F:\""

See Also

Wbemdump /C:<file>


Wbemdump /G

This switch causes the command to get instances in an enumeration by using the getobject method rather than execquery. The results of an enumeration that uses this switch should be identical to a normal Wbemdump query. This switch can be used to test a new provider to ensure that the same instances are produced regardless of how they are requested.


Wbemdump /G2

This switch is similar to the /G switch except that GetObject is called on all reference properties in the enumeration. For example:

WBEMDUMP /G2 root\wmi


Wbemdump /G:<x>

This switch is similar to the /G switch except the flags parameter of the GetObject call is specified by x. The following example specifies the value WBEM_FLAG_USE_AMENDED_QUALIFIERS that requests amended qualifiers be returned in the enumeration:

WBEMDUMP /G:131072  root\cimv2 Win32_Lgicaldisk


Wbemdump /H:<name>:<value>

This switch allows you to provide a context object and a value for that object. Use this switch when using providers that require context objects.


Wbemdump /I:<ImpLevel>

This switch causes the command to connect using the impersonation level that you specify with the parameter ImpLevel. You may need to set the impersonation level if the provider that you are using requires it.

This table lists the impersonation levels that you can specify and the values

Impersonation Level | ImpLevel Value
Anonymous | 1
Identify | 2
Impersonate | 3
Delegate | 4


Wbemdump /L:<LoopCnt>

This switch causes the command to execute the number of times specified by the parameter LoopCnt. You can use this switch to test a provider for memory leaks.

The following example lists an instance of Win32_NetworkAdapter 60 times.

WBEMDUMP /S /L:60 root\cimv2 Win32_NetworkAdapter


Wbemdump /LOCALE

This parameter lets you specify a locale id that will be used to connect to WMI.


Wbemdump /M

This switch causes the command to output the MOF file for a class. For example:

WBEMDUMP /S /M root\cimv2 Win32_NetworkAdapter


Wbemdump /M2

This switch causes the command to output the MOF file that would be used to create an instance or instances of the class specified.

WBEMDUMP /S /M2 root\cimv2 Win32_NetworkAdapter


Wbemdump /M3

This switch causes the command to output a instance MOF that you can use as a template. The output of this command is similar to that produced with the /M2 switch except all the values are set to NULL. You can redirect the output of this command into a file and set the property values to create a MOF file. You can run the MOFCOMP command on this file to generate a new instance of this class.

WBEMDUMP /S /M3 root\cimv2 Win32_NetworkAdapter


Wbemdump /O:<file>

This is the file name for output (creates Unicode file).


Wbemdump /P:<Password>

This switch causes the command to use the password that you specify with the parameter Password. If you do specify this switch the current user ID will be used. This switch can only be used in conjunction with the /U switch.

WBEMDUMP /U:Rburns /P:mypassword root/cimv2


Wbemdump /Q

Executes a query. The following example returns the current locale selected.

WBEMDUMP /Q root\cimv2 WQL "SELECT Locale from Win32_OperatingSytem"


Wbemdump /S

This switch causes the command to display information sequentially about all the subclasses of the class specified.

For example,

WBEMDUMP /S /D  root\cimv2 cim_computersystem

produces the following output:

<ROOT\CIMV2>

CIM_ComputerSystem

CIM_UnitaryComputerSystem

Win32_ComputerSystem


Wbemdump /S2

This switch causes the command to display information sequentially about all namespaces. For example,

WBEMDUMP /S2 /M root

will print the MOF files for all non-system classes in all Name spaces.

See Also

WMI System Classes


WBEMdump /T

This switch causes the command to print execution times for /Q queries. For example

WBEMDUMP /Q /T root\cimv2 WQL "SELECT DeviceId FROM Win32_logicaldisk WHERE deviceID='C:' "


WBEMdump /T2

This switch causes the command to print execution times using an alternate timer for /Q queries. For example

WBEMDUMP /Q /T2 root\cimv2 WQL "SELECT DeviceId FROM Win32_logicaldisk WHERE deviceID='C:' "


Wbemdump /U:<UserID>

This switch causes the command to use the user ID that you specify with the parameter UserID. If you do specify this switch the current user ID will be used.

wbemdump /U:Rburns root/cimv2


WBEMdump /W

This switch causes the command to prompt the user to continue when an error takes place. If this switch is not set the program will abort when an error takes place.


WBEMdump /WY

This switch causes the command to display a warning before continuing when an error takes place. If this switch is not set, the program will abort when an error takes place.

produces the following output:

(WQL) SELECT DeviceId FROM Win32_logicaldisk WHERE deviceID='C:'

ExecQuery 0.1100 seconds.

DeviceID (CIM_STRING/string)* = "C:"

ShowInstances 0.0630 seconds.


WMI Appendix

The Windows Management Instrumentation (WMI) SDK Appendix includes the following sections:

Section | Description
WMI Schema | Information on how to access the complete WMI schema.
Getting Help from Microsoft Technical Support | Instructions on how to get the help you need.


WMI Schema

Due to the dynamic nature and large size of the Windows Management Instrumentation (WMI) schema, it is no longer included in the WMI SDK. However, you can access the material at the following Microsoft Web site http://msdn.microsoft.com/developer/sdk/wmisdk/schema/default.htm.

You can download Microsoft® Internet Explorer version 5 at no cost from the Microsoft Web site at http://www.microsoft.com/ie.


CIM Reserved Words

WMI Query Language (WQL) uses the following keywords:

  • and
  • by
  • false
  • from
  • group
  • having
  • is
  • isa
  • not
  • null
  • or
  • select
  • true
  • where
  • within

In the CIM, these are reserved words; you cannot use them in your class or property names.


Getting Help from Microsoft Technical Support

If you have a simple question and need an answer fast

Quickly find answers yourself online Use Support Online to easily search the Knowledge Base and other technical resources for fast, accurate answers. You can also customize the site to control your search. To begin your search, go to http://support.microsoft.com/support.

If your question is urgent and more complex

Telephone Microsoft Technical Support Work with a support engineer to solve your issue.

Pay-Per-Incident Support Support fees for pay-per-incident support will be billed to your VISA, MasterCard, or American Express card.

In the U.S. and Canada: (800) 936-5800
Cost: $95 U.S. per incident
24 hours a day, seven days a week, including holidays

If your question isn't urgent

Send e-mail to a Microsoft Technical Support Engineer Ideal for questions requiring attached files, submit a question any time and receive a response within one business day. Submit a question with pay-per-incident Web Response at http://support.microsoft.com/support for a fee of $95 U.S.

For additional support needs

If you need text telephone (TTY/TDD) Available Monday through Friday, excluding holidays. In the United States, call (425) 635-4948, 6:00 A.M. to 6:00 P.M. Pacific time. In Canada, call (905) 568-9641, 8:00 A.M. to 8:00 P.M. eastern time.

If you don't have access to the Internet FastTips is a fax-back service providing Knowledge Base articles and answers to common questions. Phone (800) 936-4300.

If you need support services for a business Priority Annual, Priority Plus, and Premier provide a selection of support packages geared for businesses. To learn which account meets your needs, go to http://www.microsoft.com/support. You can also call
(800) 936-3500 for information on accounts for small- to medium-sized businesses and (800) 936-3200 for large, enterprise businesses.

If you need on-site, multivendor, or proprietary product support Microsoft Certified Solution Providers (MCSPs) and Authorized Support Centers (ASCs) specialize in providing support packages for hardware, network, and software products from both Microsoft and other vendors. For more information about MCSPs, call (800) 765-7768 or visit http://www.microsoft.com/mcsp. For more information about ASCs, contact your Microsoft account representative, or visit http://www.microsoft.com/enterprise/asc.htm.

If you need support outside the United States and Canada

The services and prices listed here are available in the United States and Canada only. Support outside the United Sates and Canada may vary. Microsoft support services are subject to Microsoft then-current prices, terms, and conditions, which are subject to change without notice.

Microsoft Technical Support Worldwide If you are outside the United States and have a question about a Microsoft product, first:

  • Check the information in this Help file or product manual.
  • Check the readme files that come with your product disks. These files provide general information that became available shortly before the product was released.
  • Go to Support Online from Microsoft Technical Support at http://support.microsoft.com/support.

If you cannot find a solution, you can receive information on how to obtain technical support by contacting the Microsoft subsidiary office in your area.

Important Phone numbers for Microsoft subsidiaries are subject to change. For the most recent listing, please see the options and phone number section on the Support Online web site at http://support.microsoft.com/support. If there is no Microsoft subsidiary office in your country/region, please contact the establishment from which you obtained your Microsoft product.

  • Argentina
    Microsoft de Argentina S.A.
    Customer Service: (54) (1) 316-4600
    Fax: (54) (1) 316-1922
    Technical Support Phone: (54) (1) 316-4664
  • Armenia
    See Russia
  • Australia
    Microsoft Pty. Ltd.
    Phone: Products and Services 13 20 58
    Fax: (61) (02)9870-2285
    Sales Information Centre: (61) (02) 9870-2100
    Internet:http://www.microsoft.com.au/Australia
    Technical Support:
    Phone: (61) (02) 9870-2131
    Fax: (61) (02) 9805 0519
  • Austria
    Microsoft Ges.m.b.H.
    Phone: (+43) 1 610 64 -0
    Fax: (+43) 1 610 64 -200
    Information: 0660-6520
    Prices, updates, etc.: 0660-6520
    Standard Support:
    Installation and Handling: 01 50222-2255
    General information about Support Network in Central Europe:
    FAX: 01805-251191
  • Azerbaijan
    See Russia
  • Belgium
    Microsoft NV
    Phone: +32-2-730 39 11
    Fax: +32-2-726 96 09
    Microsoft Support Network Info. Center: 0800 18307
    TechNet Subscription: +353 1 703 8738
    MSDN™ Subscription: +353 1 708 8690
    Microsoft Information Center: +32-2-481 52 52
    Bulletin Board: +32-2-726 85 45 (14400/1200/2400/9600 bd, 8N1, ANSI)
    Technical Support:
    +32-2-513 32 74 (Dutch speaking)
    +32-2-502 34 32 (English speaking)
    +32-2-513 22 68 (French speaking)
    Internet: www.microsoft.com/benelux/support
  • Belorussia
    See Russia
  • Bolivia
    See Uruguay
  • Brazil
    Microsoft Informatica Ltda.
    Phone: (55) (11) 5514 –7100
    Fax: (55) (11) 5514 - 7106/5514-7107
    Technical Support:
    Phone: (55) (11) 5506-8087
    Fax: (55) (11) 5506-7621
    Automatic Fax: (55) (11) 5506-8506
    Technical Support Bulletin Board Service: (55) (11) 5506-1234
    Customer Support: (55) (11) 822-5764
    Customer Services Fax: (55) (11) 822-6227
  • Canada
    Microsoft Canada Co.
    Head Office Phone: 1 (905) 568-0434
    Customer Information Centre: 1 (800) 563-9048
    Technical Support:
    Desktop Systems including Microsoft® Windows® 95: (905) 568-4494
    Microsoft Office and Office Components: (905) 568-2294
    Other Standard Technical Support: (905) 568-3503
    Priority Support Information: (800) 668-7975
    Text Telephone (TTY/TDD) (905) 568-9641
    Technical Support Bulletin Board Service: (905) 507-3022
  • Caribbean
    Microsoft Caribbean, Inc.
    Phone: (809) 273-3600
    Fax: (809) 273-3636
    Technical Support: (408) 953 8086
    Support E-Mail: mscarsup@microsoft.com
    Customer Service: (800) 297 5982 for area codes 787 & 809 only
    Customer Service E-mail: msccatus@microsoft.com
  • Central America
    Technical Support:     (506) 298 2020
    Support E-Mail: mscasup@microsoft.com
    Customer Service: (506) 298 2000
    Customer Service E-mail: msccatus@microsoft.com
  • Chile
    Microsoft Chile S.A.
    Phone: 56-2-330-6000
    Fax: 56-2-330-6190
    Customer Service: 56-2-800-330600
    Personal Operating System and Applications:
    Phone: 56-2-330-6222
    Fax: 56-2-341-1439
  • People's Republic of China
    Microsoft (China) Co. Ltd
    19th Floor, Metro Tower
    No. 30 Tian Yao Qiao Road,
    Shanghai, 200030, P.R.C.
    Phone: 011-86-21-64691166; 011-86-21-64691188
    Fax: 011-86-21 64691188 Ext. 6988
  • Colombia
    Microsoft Colombia
    Phone: (571) 618 2245
    Fax: (571) 618 2269
    Technical Support:
    Línea de Respuesta Microsoft
    Phone: (571) 5230022
    Fax: (571) 5231220
    Voice Mail: (571) 5034216
  • Croatia
    Microsoft Hrvatska d.o.o.
    Phone: (+385) (1) 304 555
    Fax: (+385) (1) 335 051
    Technical Support: Please, contact the subsidiary.
  • Czech Republic
    Microsoft s.r.o.
    Phone (+42) (2) 611 97 111
    Fax: (+42) (2) 611 97 100
    Technical Support: (+420) (2) 2150 3222
  • Denmark
    Microsoft Denmark
    Phone: (45) 44 89 01 00
    Fax: (45) 44 68 55 10
    Technical Support:
    Phone: (45) 44 89 01 11
    Microsoft Sales Support: (45) 44 89 01 90
    Microsoft FastTips: (45) 44 89 01 44
    (Document 303030 in FastTips contains detailed instructions)
    Microsoft MSDL (BBS): (45) 44 66 90 46
  • Dominican Republic
    See Central America
  • Dubai
    Microsoft Middle East
    Phone: (971) 4 513 888
    Fax: (971) 4 527 444
    Technical Support:
    Personal Operating Systems and Desktop Applications ONLY:
    Phone: (971) (4) 524 488
    Fax: (971) (4) 524 495
    email: mts@emirates.net.ae
    Priority Support Information: (971) (4) 555 752
    Customer Service Center:
    (Version upgrade / TechNet and MSDN subscription)
    Phone: (971) (4) 655 082
    Fax: (971) (4) 655 097
  • Ecuador
    Corporation Microsoft del Ecuador S.A.
    Phone: (593) 2 460-447, (593) (2) 460-451
    Customer Service: (593) (2) 460-453, (593) (2) 460-458
    Technical Support: (593) (2) 463-094
  • Egypt
    Microsoft Egypt
    Phone: +202-594 2445
    Fax: +202-594 2194
    Technical Support:
    Personal Operating Systems and Desktop Applications ONLY:
    Phone: (202) 261 3991 / 6
    Fax: (202) 403 2718
  • England
    See United Kingdom
  • Estonia
    See Germany
    Technical Support: (+372) 650 49 99
  • Finland
    Microsoft OY
    Phone: +358-(0)9-525 501
    Fax: +358-(0)9-878 8770
    Technical Support:
    Phone: +358-(0)9-525 502 5026
    Standard +358 (0) 9-525-502-500
    Priority: +358 (0) 9-525-502-20
    Premier: +358 (0) 9-525-502-03
    Microsoft MSDL: +358-(0)9-878 77 99
    (Information in Swedish and English): +358 (0) 9-455-03-66
    Microsoft FastTips: +358-(0)9-525 502 550
    (Information in Swedish and English)
  • France
    Microsoft France
    Phone: (33) 01 69-86-46-46
    Fax: (33) 01 64-46-06-60
    Telex: MSPARIS 604322
    Technical Support:
    Phone: (33) 01-69-86-10-20
    Fax: (33) (01) 69-28-00-28
  • French Polynesia
    See France
  • Georgia
    See Russia
  • Germany
    Microsoft GmbH
    Phone: 089/3176-0
    Fax: 089/3176-1000
    Telex: (17) 89/83 28 MS GMBH D
    Information: 089/3176 1199
    Prices, updates, etc.: 08105-25-1199
    Internet: www.microsoft.com/germany
    Standard Support:
    Installation and Handling: 01805/67 22 55
    General information about Microsoft support in Central Europe:
    Fax: 1805-25-1191
  • Greece
    Microsoft Hellas, S.A.
    Phone: (30)(1) 6806-775 through (30)(1) 6806-779
    Fax: (30)(1) 6806-780
    Technical Support:
    Phone: (30) (1) 9247-030
    Fax: (30) (1) 9215-363
  • Hong Kong SAR, PRC
    Microsoft Hong Kong SAR, PRC Limited
    Fax: (852)2560-2217
    Product support Faxback Service: (852)2535-9293
    Microsoft Club Hotline: (852)28044277
    Technical Support: (852) 2804-4222
  • Hungary
    Microsoft Hungary
    Microsoft Magyarország Kft.
    Phone: +36 (1) 327-2800
    Fax: +36 (1) 327-2899
    Technical Support: +36 (1) 267-4636 (2MSINFO)
  • Iceland
    See Denmark
  • Ireland
    See United Kingdom
  • India
    Microsoft India
    Phone: (011) (91) (80) 559 5733, (011) (91) (11) 646 0767, 646 0694
    Fax: (011) (91) (80) 559-7133, (011) (91) (11) 647- 4714
  • Indonesia (SP)
    Microsoft Indonesia - Jakarta
    Technical Support:
    Phone: 62 21 570 42 54
    Fax: 62 21 520 81 22
  • Israel
    Microsoft Israel Ltd.
    Phone: 972-3-613-0833
    Fax: 972-3-613-0834
  • Italy
    Microsoft SpA
    Phone: (39) (2) 7039-21
    Fax: (39) (2) 7039-2020
    Microsoft Rome Office: (39) (6) 5095-01 - Fax: (39) (6) 5095-0600
    Microsoft by Fax (Fax-on-demand service): (39) (2) 70-398-888
    Customer Service (New product info, product literature): (39) (2) 70-398-398
    Dealer Support (Customer Service for resellers only): (39) (2) 70-398-388
    Technical Support: (39) (2) 70-398-398
    Microsoft Consulting Service: (39) (2) 7039-21
  • Japan
    Microsoft Company Ltd.
    Technical Support (Standard Support): (81) (424) 41-8700
    (Technical Support options/ Support Contract)
    Phone: 0120-37-0196 (toll free domestic only)
    Channel Marketing Information Center:
    (Presales Product Support)
    Tokyo Phone: (81) (3) 5454-2300
    Osaka Phone: (81) (6) 245-6995
    Customer Service Phone:
    (Version upgrade/Registration)
    Phone: (81) (48) 226-5500
    Fax: (81) (48) 226-5511
  • Kazakhstan
    See Russia
  • Kirgizia
    See Russia
  • Korea
    Microsoft CH
    Phone: (82) (2) 531-4500
    Fax: (82) (2) 531-1724
    Customer Service: 080-022-7337 (toll free domestic only)
    Technical Support:
    Office Technical Support: (82) (2) 508-0040
    Windows Technical Support: (82) (2) 563-0054
    Developer Technical Support: (82) (2) 566-0071
    Microsoft FastTips: (82) (2) 3453-7555
    Support Sales: (82) (2) 531-4544
  • Latin America
    Microsoft
    Latin American Headquarters (U.S.A.)
    Phone: (305) 489-4800
    Fax: (305) 491-1616
    Customer Service: (425) 936-8661
    Technical Support: (214) 714-9100
    http://www.microsoft.com/latam/soporte
  • Liechtenstein
    See Switzerland (German speaking)
  • Luxembourg
    Microsoft NV
    Phone: +32-2-730 39 11
    Microsoft Support Network Info. Center +31-800-9977-57
    TechNet Subscription: +353-1-703 8738
    MSDN Subscription: +353-1-708-8690
    Microsoft Information Center: +32-2-481 52 52
    Bulletin Board: +32-2-726 85 45
    (1200/2400/9600/14400 bd, 8N1, ANSI)
    Technical Support:
    +32-2-513 32 74 (Dutch speaking)
    +32-2-502 34 32 (English speaking)
    +32-2-513 22 68 (French speaking)
    Web: www.microsoft.com/benelux/support
  • Malaysia (SP)
    Microsoft (Malaysia) Sdn Bhd:
    Phone: (60-3) 793-9595
    Fax: (60-3) 791-6080
  • México
    Microsoft México, S.A. de C.V.
    267-2110 Atencion a Distribuidores
    265-3380 Atencion a Clientes
    265-3399 Soporte Sistemas Operativos y Applicaciones de Escritorio
    267-2190 Soporte de Servidores y Herramientas de Desarrollo
    Fast Tips: (52)(5) 2612199
    Microsoft BBS 628-6200/02 MSMEXICO sin password
  • Morocco
    Microsoft Afrique Du Nord
    Phone: (212) 2 47 10 72
    Fax: (212) 2 47 10 86
  • Netherlands
    Microsoft BV
    Phone: 023-5689189
    Customer Service: 023-5677700
    Microsoft Support Network Info Centre: 0800 099 7757
    TechNet Subscription: 0800 022 6801
    MSDN Subscription: 0800 022 7261
    Bulletin Board: 023-5634221
    (1200/2400/9600/14400bd, 8N1, ANSI)
    Technical Support:
    023-5677877 (Dutch speaking)
    023-5677853 (English speaking)
    Web: www.microsoft.com/benelux/support
  • New Zealand
    Microsoft New Zealand Ltd
    Phone: 64 (9) 357-5800
    Fax: 64 (9) 358-3726
    Technical Support:
    Phone: 64 (9) 357-5575
    Fax: 64 (9) 307-0516 and 357-5577
  • Northern Ireland
    See United Kingdom
  • Norway
    Microsoft Norway AS
    Phone: +(47) 22 02 25 00
    Fax: +(47) 22 95 06 64
    Technical Support:
    Standard: +(47) 22 02 25 50
    Priority: + (47) 22 02 25 45
    Premier: + (47) 22 02 25 46
    Microsoft Sales Support: +(47) 22 02 25 80
    Microsoft MSDL: +(47) 22 18 22 09
    Microsoft FastTips: +(47) 22 02 25 70
    (Document 404040 in FastTips contains detailed instructions)
  • Panama
    Technical Support:     (506) 298 2020
    Support E-mail: mscasup@microsoft.com
    Customer Service: (506) 298 2000
    Customer Service E-mail: msccatus@microsoft.com
  • Papua New Guinea
    See Australia
  • Paraguay
    See Uruguay
  • Peru
    Centro de Servicio al Cliente
    Central de Soporte: (51) (1) 422- 4116
    Fax: (51) (1) 221 9052
    Central de Informacion (51) (1) 242-5980
    Fax: (51) (1) 447 8591
  • Philippines (SP)
    Microsoft Philippines
    Phone: 632 811 0062
    Technical Support:
    Phone: 632 892 2295/2495 and 632 813-2494
    Fax: 632 813 2493
  • Poland
    Microsoft Sp. z o.o.
    Phone: +(48-22) 661-54-00
    Fax: +(48-22) 661-54-34
    Information Service: +(48-22) 865-99-33
    Technical Support: +(48-22) 865-99-66
  • Portugal
    Microsoft Portugal MSFT, Lda.
    Phone: (351) 1 4409200
    Fax: (351) 1 4412101
    Technical Support:
    Standard Support: (351) 1 4409280/1/2/3
    Fax: (351) 1 4411655
  • Puerto Rico
    Technical Support: (408) 953 8086
    Support E-Mail: mscarsup@microsoft.com
    Customer Service: (800)297 5982 for area codes 787 & 809 only
    Customer Service E-mail: msccatus@microsoft.com
  • Republic of Ireland
    See United Kingdom
  • Romania
    Microsoft s.r.l.
    Phone: (+40) (1) 222 90 16
    Fax: (+40) (1) 222 90 12
    Technical Support: (+40) (1) 312 09 48
  • Russia
    Microsoft Z.A.O.
    Microsoft Information Center: (095) 916 7171
    Russia: 125252
    Moscow: Postbox 70
    Technical Support:
    Moscow (095) 745-54-45
    St.-Petersburg: (812) 118-36-36
    Novosibirsk (3832) 119-019
    Web: www.microsoft.com/rus/
  • Scotland
    See United Kingdom
  • Saudi Arabia
    Microsoft Saudi Arabia
    Phone: +966-1-488-1165
    Fax: +966-1-488-1576
    Technical Support:
    (Personal Operating System and Desktop Applications only):
    Phone: 800 124 0500
    (toll free within Saudi Arabia)
    Fax: 966-1-4740576
  • Singapore
    Microsoft Singapore Pte Ltd
    Phone: (65) 337-6088
    Fax: (65) 337-6788
    Customer Services:
    Phone: (65) 324-5255
    Fax: (65) 324-6181
    Product Support Services:
    Phone: (65) 378-3600
    Fax: (65) 378-3662
  • Slovenia/Slovenija
    Microsoft d.o.o.
    Phone: (+386) (61) 1800 8-00
    Fax: (+386) (61) 1800 822
    Technical Support: (+386) (61) 185 3449
  • Slovak Republic
    Microsoft Slovakia s.r.o.
    Phone (+421) (7) 37 63 02
    Fax: (+421) (7) 37 66 71
    Technical Support: (+421) (7) 531 20 83
  • South Africa
    Microsoft South Africa
    Phone: (27) 11 445 0000
    Fax: (27) 11 445 0046
    Technical Support:
    (Toll Free): 0 802 11 11 04
    (Toll): (27) 11 445 0000
    Fax: (+27) 11 445-0343
  • South East Africa and Indian Ocean Islands
    See South Africa
  • Spain
    Microsoft Iberica SRL
    Phone: (34) 1-807-9999
    Fax: (34) 1-803-8310
    Technical Support: (34) 1 -3754004
    Customer Service: (34) 1-3754004
    From Spain Only: 902-187 198
    Fax Back telephone: (34) 1-3754004
  • Sweden
    Microsoft AB
    Phone: +46-(0)8-752 56 00
    Fax: +46-(0)8-750 51 58
    Technical Support:
    Standard: +46-(0) 8- 752 09 29
    Priority: +46 (0) 8 751 09 80
    Premier: +46 (0) 8 632 57 01
    Sales Support: +46-(0)8- 752 56 30
    Microsoft MSDL: +46-(0)8-750 47 42
    Microsoft FastTips: +46-(0)8-752 29 00
    (Document 202020 in FastTips contains detailed instructions)

  • Standard Technical Support:
    (French speaking): 022-738 96 88
    General information about Microsoft Support in Central Europe:
    Tel. 0848-80-2330
    Internet: www.microsoft.com/switzerland
  • Tadzhikistan
    See Russia
  • Taiwan
    Microsoft Taiwan Corp.
    Phone: (886) (2) 504-3122
    Fax: (886) (2) 504-3121
    Technical Support: (886) (2) 508-9501
  • Thailand
    Microsoft (Thailand) Limited
    Phone: (662) 266-3300
    Fax: (662) 266-3310
    Product Support:
    Phone: (662) 613-7208 through 11
    Fax: (662) 613-7198
  • Turkey
    Microsoft Turkey
    Phone: 90 (212) 258 59 98
    Fax: 90 (212) 258 59 54
    Support Hotline:
    Phone: 90 (212) 258 96 66
    Fax: 90 (212) 258 95 99
    Bulletin Board Service: 90 (212) 227 93 90
  • United Kingdom
    Microsoft Limited
    Fax: (0870) 60 20 100
    Phone: (0870) 60 10 100
    Microsoft KeyData:
    (Bulletin Board Service)
    (0870) 50 30 200 (up to 28.8Kbaud, n, 8, 1)
    Microsoft KeyFax:
    (Faxback Information Service)
    (0870) 50 30 100
    Technical Support:
    Desktop Applications, Home Products, Desktop Systems and hardware:
    0870 50 10 100
    Developer Products: 0870 50 10 200
    Business Systems: 0870 50 10 300
    Customers phoning from Ireland should dial 706 5353 for technical support.
    Minicom Line 0870 50 30 400
    Pre-Sales Information: Microsoft Connection (0345) 00 2000
  • Uruguay
    Technical Support:
    Phone: (598) (2) 774934
    Fax: (598) (2) 774935
  • Uzbekistan
    See Russia
  • Venezuela
    Corporation MS 90 de Venezuela S.A.
    Other information: (582) 265-9922
    Fax: (582) 265-0863
    Technical Support: (582) 993-6755
  • Wales
    See United Kingdom


Schema Validation Wizard Error Messages

Built on Friday, October 08, 1999


Valid Class Name

[This is preliminary documentation and subject to change.]

Error type: Error

The class name must be fully qualified (that is, the class name prefixed by the schema name, schema_class). Class names must begin with an alpha character. The class portion of the class name may contain underscores.


Valid Description

[This is preliminary documentation and subject to change.]

Error type: Warning

Every class, property, reference, and method must contain a description that provides meaningful reference material. For example, the description must provide more information than simply reiterating the property name. All property descriptions must contain the name of the property within the first six words of the description.

The description validation process removes the following noise words and characters from the description:

a, abstract, all, and, as, association, be, class, component, define, for, integer, is, manage, may, number, object, or, property, reference, represent, string, such, the, this, which, ",", ".", "(", ")", "/", "\", "<", ">".

In addition, all references to the class name are removed. For example, if the class name is Win32_LogicalDiskDrive, the words logical, disk, and drive are removed from the description.

The description is considered valid if the remaining description contains more than 50 characters.


Valid Class Type

[This is preliminary documentation and subject to change.]

Error type: Error

Classes must contain an Abstract, Static, or Dynamic qualifier. Dynamic classes must also contain the Provider qualifier.


Valid UUID

[This is preliminary documentation and subject to change.]

Error type: Error

Classes must contain an UUID qualifier and its value must be correctly formatted.


Valid Locale

[This is preliminary documentation and subject to change.]

Error type: Error

Classes must contain a Locale qualifier and its value must be of the form, MS_xxxx. For example, American English would appear as "MS_409".


Valid Mapping Strings

[This is preliminary documentation and subject to change.]

Error type: Error

The MappingStrings qualifier must be of type array, {}, and contain a valid domain or recast mapping string. For details on the use of the MappingStrings qualifier, see the CIM Specification v2.0 at http://www.dmtf.org/.


Valid Reference Target Class

[This is preliminary documentation and subject to change.]

Error type: Error

Referenced classes contained in associations must exist.


Valid Read Qualifier

[This is preliminary documentation and subject to change.]

Error type: Error

All properties must include the Read qualifier.


Valid MaxLen Qualifier

[This is preliminary documentation and subject to change.]

Error type: Error

You must specify the MaxLen qualifier for all key properties of type String.


Valid Number of References

[This is preliminary documentation and subject to change.]

Error type: Error

Associations must include two or more reference properties.


Reference Included in Non-Association Class

[This is preliminary documentation and subject to change.]

Error type: Error

Non-association classes must not include reference properties.


Valid Reference Overrides

[This is preliminary documentation and subject to change.]

Error type: Error

The overriding reference must be in the hierarchy of the same base class as the overridden reference.


Valid Association Inheritance

[This is preliminary documentation and subject to change.]

Error type: Error

An association can be derived from a non-association class or an association class. However, you cannot derive a non-association class from an association class. You can explicitly define an association class using the Association qualifier or implicitly using Association with the ToSubClass flavor.


Valid Property Override

[This is preliminary documentation and subject to change.]

Error type: Error

You must maintain the property type when you override the property.


Valid Value Qualifier

[This is preliminary documentation and subject to change.]

Error type: Error

The Value qualifier must be of type array, {}.


Valid ValueMap Qualifier

[This is preliminary documentation and subject to change.]

Error type: Error

The ValueMap qualifier must be of type array, {}. The type of the array elements must match the property's type. Do not include a ValueMap qualifier if the permissible values start at 0 and increment by 1.


Valid Number of Value\ValueMap Entries

[This is preliminary documentation and subject to change.]

Error type: Error

If both the Value and ValueMap qualifiers are present, they must contain the same number of elements.


Valid BitMap Qualifier

[This is preliminary documentation and subject to change.]

Error type: Error

The BitMap qualifier must be of type array, {}. The type of the array elements must match the property's type. The BitMap must not contain duplicate entries. Do not include a BitMap qualifier if the permissible values start at 0 and increment by 1.


Valid Number of BitValue\BitMap Entries

[This is preliminary documentation and subject to change.]

Error type: Error

If both the BitValue and BitMap qualifiers are present, they must contain the same number of elements.


Valid Method Override

[This is preliminary documentation and subject to change.]

Error type: Error

The overriding method must maintain the signature of the existing method.


Valid Qualifier Scope

[This is preliminary documentation and subject to change.]

Error type: Error

The context that the qualifier or flavor is used must be correct. For example, the Abstract qualifier must only appear on a class.


Non-CIM/WMI Qualifier Found

[This is preliminary documentation and subject to change.]

Error type: Warning

A non-CIM/WMI qualifier was found.


Redundant Association

[This is preliminary documentation and subject to change.]

Error type: Warning

Associations with different names contain the same reference classes.


Valid Derivation

[This is preliminary documentation and subject to change.]

Error type: Error

You may only derive classes from the following CIM classes. In all other cases you must derive from the Win32 classes.

  • CIM_Configuration
  • CIM_ElementSetting
  • CIM_FRU
  • CIM_FRUIncludesProduct
  • CIM_FRUPhysicalElements
  • CIM_PhysicalElement
  • CIM_Product
  • CIM_ProductFRU
  • CIM_ProductParentChild
  • CIM_ProductPhysicalElements
  • CIM_ProductSoftwareFeatures
  • CIM_ProductSupport
  • CIM_Realizes
  • CIM_Setting
  • CIM_SupportAccess


Valid CIM_PhysicalElement Derivation

[This is preliminary documentation and subject to change.]

Error type: Error

Classes derived from CIM_PhysicalElement must derive from the leaf-most subclass of the CIM_PhysicalElement tree. However, if Microsoft provides a Win32 class for your particular physical element, you must derive from that Win32 class.


Valid CIM_Setting Usage

[This is preliminary documentation and subject to change.]

Error type: Error

An instance of CIM_ElementSetting must exist for classes derived from CIM_Setting. This establishes a relationship between CIM_Setting and CIM_ManagedSystemElement.


Valid CIM_StatisticalInformation Usage

[This is preliminary documentation and subject to change.]

Error type: Error

An instance of CIM_Statistics must exist for classes derived from CIM_StatisticalInformation. This establishes a relationship between CIM_StatisticalInformation and CIM_ManagedSystemElement.


Valid CIM_LogicalDevice Derivation

[This is preliminary documentation and subject to change.]

Error type: Error

Classes derived from CIM_LogicalDevice must derive from the leaf-most subclass of the CIM_LogicalDevice tree.


Valid CIM_ElementSetting Usage

[This is preliminary documentation and subject to change.]

Error type: Error

An instance of CIM_ElementSetting must exist for classes derived from CIM_Setting that expose a device's configuration information. This establishes a relationship between CIM_Setting and CIM_LogicalDevice.


Valid Win32_ComputerSystem Derivation

[This is preliminary documentation and subject to change.]

Error type: Error

You must derive from Win32_ComputerSystem, instead of CIM_UnitaryComputerSystem.


Complete Localization Schema

[This is preliminary documentation and subject to change.]

Error type: Error

Each class contained in the base schema must exist in the localized schema. Also, the base schema's inheritance structure must be preserved.


Valid Localized Class

[This is preliminary documentation and subject to change.]

Error type: Error

The list of properties in the localized class definition must match or be a subset of the list of properties of the base schema.


Valid Amendment Qualifier

[This is preliminary documentation and subject to change.]

Error type: Error

Each localized class must contain the amendment qualifier. The format of this qualifier is [AMENDMENT, LOCALE(0xXXX)] where 0xXXX is the locale identifier for the localized class. For example, the amendment qualifier for American English is [AMENDMENT, LOCALE(0x409)].

See WMI Localization for more information.


Valid Abstract Qualifier

[This is preliminary documentation and subject to change.]

Error type: Error

Each localized class must contain the Abstract qualifier.


Valid Localized Property

[This is preliminary documentation and subject to change.]

Error type: Error

Each property defined in the localized class must match the property definition found in the base schema.


Valid Localized Method

[This is preliminary documentation and subject to change.]

Error type: Error

Each method definition in the localized class must match the method definition found in the base schema. Note the method qualifiers are different in the classes.


Valid Locale Qualifier

[This is preliminary documentation and subject to change.]

Error type: Error

The value for the Locale qualifier must match the localized namespace in which the class exists.


Valid Locale Namespace

[This is preliminary documentation and subject to change.]

Error type: Error

The name of the localized namespace must be in the proper format and must specify a valid locale. The localized namespace is named MS_xxx where xxx is the hexadecimal value of the Win32 LCID. For example, the hierarchy of the namespaces containing the English and German amended class definitions for CIMV2 are:

  • root\cimv2
  • root\cimv2\ms_409
  • root\cimv2\ms_407


WMI contents Page

Web Sites
of Interest:
DMTF

Schema

WMI SDK

Microsoft
Management

COM

Internet
Explorer

WMI SDK customer,

Welcome to the Windows Management Instrumentation (WMI) SDK. The Microsoft team is proud to deliver technology that will enable a whole new generation of management applications and solutions. As you review our documents, tools, and samples, you will find that the WMI SDK offers resources for a variety of information technology professionals. For information on how to use this SDK, see Using the WMI SDK and Roadmap to WMI Documentation.

Let us know if there is anything else that you would like to see in this kit in the future. Send e-mail to wmi@microsoft.com.

Thank you,

Microsoft WMI Team


Topic Not Found

No matching topic was found. Some possible reasons and remedies are as follows:

  • The file (.chm) that contains the destination topic is not in the expected location.

    Remedy: Rerun the MSDN Library Setup.

  • The file (.chm) that contains the current topic or destination topic is out-of-date and the link is no longer valid.

    Remedy: Install the latest version of the MSDN Library.

  • The MSDN Library CD is not in the CD-ROM drive.

    Remedy: Insert the MSDN Library CD into the CD-ROM drive.


Requirements

Many topics that introduce the syntax of an API element contain information about the build and run-time requirements for using the element. The format is as follows:

Windows NT/2000: Requires Windows NT 3.1 or later.
Windows 95/98: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

The first line indicates the versions of Windows NT on which an element is supported. This information may include required service packs, option packs, or components such as Internet Explorer. If an element is not supported, the line reads "Windows NT/2000: Unsupported."

The second line indicates whether an element is supported on Windows 95 or Windows 98. This information may include required OEM service releases, redistributables, or components such as Internet Explorer. If an element is not supported, the line reads "Windows 95/98: Unsupported."

The third line indicates the versions of Windows CE on which an element is supported. If an element is not supported, the line reads "Windows CE: Unsupported."

The fourth line indicates the file that defines an element. This value can be an .h file, .idl file, or .odl file. If the header file is supplied by the user, the line reads "Header: User-defined."

The fifth line indicates the file used to resolve calls to a function or member. This value can be a .lib file, .dll file, or .tlb file. If the import library is supplied by the user, the line reads "Import Library: User-defined." For element types that do not require an import library, this line is omitted.

The sixth line indicates whether an element exists as both a Unicode (W) version and an ANSI (A) version. If Unicode support is not available, this line is omitted.


Windows Management Instrumentation

This page uses frames, but your browser doesn't support them.