Legal Information

Windows Management Instrumentation

This is a preliminary document and may be changed substantially prior to final commercial release. This document is provided for informational purposes only and Microsoft makes no warranties, either express or implied, in this document. Information in this document is subject to change without notice. The entire risk of the use or the results of the use of this document remains with the user. 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.

Unpublished work. ©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.

Other product and company names mentioned herein may be the trademarks of their respective owners.

Built on Thursday, April 29, 1999


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 architectural information and information about using the WMI SDK.

  • WMI for Network Administrators and System Managers

    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 for Application Developers

    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.

  • WMI for Provider Developers

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

  • WMI Development Environment

    Includes information on ActiveX Controls, WMI applications, Managed Object Format (MOF) Language, and the WMI Query Language, and an application called WBEMTest.

  • 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

    SQL for WMI

    MOF Compiler

    BNF Syntax for MOF

    SNMP Compiler Error Messages

    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 originally released WBEM SDK version 1.01:


What's New in Version 1.1

  • Scripting API and Samples
  • WMI ActiveX Control Tutorial
  • Security Impersonation Technology Conceptual Overview and API
  • Microsoft Windows Installer Provider Conceptual Overview and Samples
  • Security Provider Conceptual Overview and Samples
  • Service Name Change
  • Commercial Quality Versions of the Object Browser and ActiveX Controls


Scripting API and Samples

As scripting has proven to be a simple, fast and powerful approach for Windows Management, this Windows Management Instrumentation (WMI) SDK version now includes a Scripting API set and some associated samples.

  • Scripting API
  • Scripting Examples
  • Scripting Sample Programs


WMI ActiveX Control Tutorial

This release of the Windows Management Instrumentation (WMI) SDK includes a new tutorial, Creating a WMI Browser in MFC, which introduces you to the WMI ActiveX® Control suite. In this tutorial, you create a simple browser using the navigator, login, and object viewer controls.

Note The WMI tutorials are supported on Microsoft® Windows NT® version 4.0 with Service Pack 4 and Windows® 2000. Additionally, these samples are only supported with Microsoft Visual C++ version 5.0 or higher.


Security Impersonation Technology Conceptual Overview and API

New security enhancements are now incorporated into the Windows Management Instrumentation (WMI) SDK including client impersonation technology. This SDK includes a conceptual overview section on security impersonation along with how to add applicable interfaces to the WMI COM and Scripting API set.

Client Impersonation by Providers

IUnsecuredApartment COM API


Windows Installer Provider Conceptual Overview and Samples

This release of the Windows Management Instrumentation (WMI) SDK includes the Microsoft Windows Installer Provider, which is used to install, maintain, and inventory software using WMI.


Security Provider Conceptual Overview and Samples

This release of the Windows Management Instrumentation (WMI) SDK includes the Security Provider, which is used to read and modify Windows® NT/Windows® 2000 security descriptors for NTFS files, directories, and shares.

Security Provider

The Security Provider contains the following classes.

Class | Description
Win32_AccountSID | Represents a security account's security identifier (SID).
Win32_SecuritySettingOfLogicalFile | Represents an association between a CIM_LogicalFile instance and a Win32_LogicalFileSecuritySetting instance.
Win32_LogicalFileSecuritySetting | Represents security settings for a logical file.
Win32_SID | Represents an arbitrary security identifier (SID).
Win32_LogicalFileAccess | Represents an association between a Win32_LogicalFileSecuritySetting and a Win32_SID. The Win32_LogicalFileAccess class represents the access control entry ( ACE ) contained within the file's DACL.
Win32_LogicalFileGroup | Represents an association between a Win32_LogicalFileSecuritySetting and a Win32_SID. The Win32_LogicalFileGroup class represents the primary group of the logical file.
Win32_LogicalFileOwner | Represents an association between a Win32_LogicalFileSecuritySetting and a Win32_SID. The Win32_LogicalFileOwner class represents the owner of the logical file.


WMI and WBEM

To distinguish between the Microsoft® Windows®-based implementation of WBEM and the standards-based Desktop Management Task Force (DMTF) initiative, Microsoft refers to its implementation of WBEM as Windows Management Instrumentation (WMI).

Note WMI includes the new driver instrumentation called WMI for Windows Driver Model (WDM).


Service Name Change

To clarify the goals of Windows Management Instrumentation (WMI) technology, Microsoft has renamed the WMI Windows NT/Windows 2000 Service from CIMOM (Common Information Management Object Model) to WMI. As a result, references made formerly to CIMOM in the documentation will now be made to WMI.

Microsoft's implementation of WMI is geared toward the Windows® family of operating systems and the management thereof. However, Microsoft is still dedicated to overall WBEM objectives and continues to work in full cooperation with the DMTF (Desktop Management Task Force).


Commercial Quality Versions of the Object Browser and ActiveX Controls

The Object Browser and ActiveX® controls that previously shipped with the WBEM SDK version 1.01 are now fully tested and ready for commercial use. These tools can be found at the following locations:

WBEM Object Browser

ActiveX Controls


What's New in Windows 2000 Beta 3

  • View Provider Conceptual Overview and Samples
  • Directory Service Provider Conceptual Overview and Samples
  • WMI ADSI Extension
  • WBEM Test Development Tool


View Provider Conceptual Overview and Samples

This release of the SDK includes the View Provider. The view provider lets you combine different source classes, from different namespaces or on different computers, and combine them as a single view class. View classes simplify things when no single class contains all the information you need. The view provider also makes it easier to gather information when you have many identical class instances located on different computers.


Directory Service Provider Conceptual Overview and Samples

This release of the SDK includes the Directory Services (DS) Provider. The DS provider is one of the built-in providers that comes with the WMI SDK. It makes the classes and objects in the Active Directory available to WMI management applications.


WMI ADSI Extension

This release of the SDK includes coverage of the WMI Active Directory Service Interface (ADSI) Extension. The extension maps Directory Service Computer class objects to WMI Win32_ComputerSystem class objects.

But what does this do for me you say? Suppose you use the ADSI to query the Active Directory, looking for a particular computer. The query returns a computer object that interests you. To use WMI to manage that particular computer object, you must convert the DS Computer object name into a form usable by WMI (a WMI path name). Using the DS Computer object name, you must manually construct the corresponding WMI ComputerSystem object. This can be quite complicated. The WMI ADSI Extension does this work for you automatically.


WBEM Test Development Tool

WBEMTest is a general purpose utility that lets you to create, enumerate, and delete classes and instances; execute the methods of instances; run queries; and display the Managed Object Format (MOF) code for classes and instances. WBEMTest is useful to check queries, classes and instances when you are developing WMI providers and WMI client applications.


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 Desktop 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:

  • System Requirements
  • Architectural Overview, a high-level description of the WMI initiative and the components that are part of the WMI technology.
  • Terms and Concepts, a description of the main terms and concepts that are central to WMI.
  • Using the WMI SDK, topics on getting started using the WMI SDK.


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 4 or later, including Microsoft® Windows® 2000
  • Microsoft® Internet Explorer 4.01 or later
  • Microsoft Internet Explorer 4.01 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 version 4.0 with Service Pack 4 or later, including Windows 2000, and on Microsoft® Windows® 95 OSR2 and Microsoft® Windows® 98.


Compiler Requirements

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

The .idl and .h files included with the WMI SDK are intended for use with Microsoft Visual C++ Version 5.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 Windows Management Instrumentation (WMI) SDK development purposes, it is recommended that a Win32® developer have a computer that consists of at least:

  • Pentium 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


Alpha Processors

The sample project files (*.dsp), are not usable on Alpha platforms.

If you are using an Alpha processor, your computer should consist of at least:

  • 32 MB RAM
  • 35 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 Desktop 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 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/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:

  • Microsoft 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 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/Windows® 2000 services
  • Local or remote standard executables (.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 follows:

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 DMTF as part of the 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. See WMI SDK Applications for more information.

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 Microsoft 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. WinMgmt.exe runs as a standard executable file that is started 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 are actively seeking its services. On computers running Windows 2000, 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 when all the clients depart. As a manual service, WinMgmt.exe 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 and the Scripting API. Both of these scripts are 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 interact 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:

  • 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.

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.

For more information about WQL, see WMI Query Language.


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 name spaces. WMI does not support protection of individual classes, instances, and name spaces.

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 Microsoft® 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 Permission Editor application (Wbemperm.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 Desktop 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 allowed:

  • 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.

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.

Providers 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. Providers can define new classes using either the WMI application programming interface (API) or the Managed Object Format (MOF) language.

The names of classes defined by applications or providers are case-insensitive strings that can never include leading or trailing underscores. Applications and providers 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 can include underscore characters to delimit parts of a compound name. For example, Logical_Disk 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 classes can participate in a relationship known as an association. An association relates two classes or instances of classes by referring to them in the properties of another class. This third class is referred to as an association class.

WMI classes can be 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 has its definition supplied by a provider at run time, as needed. Dynamic classes are not stored permanently. Whenever an instance of a dynamic class is requested, WMI makes a call to the appropriate 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.

Properties of superclasses are always inherited by their subclasses. However, the values of inherited properties can sometimes be overridden. Whether a subclass can specify its own value for an inherited property depends on the existence of a particular qualifier. 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 can not 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

WMI classes can include zero or more methods. WMI methods are implemented by method providers. The method provider must be properly registered for each class it uses. To indicate that a implementation is available for a specific method, you must attach an Implemented qualifier to the method in its definition. A client invokes a method synchronously by calling the IWbemServices::ExecMethod method or asynchronously by calling the IWbemServices::ExecMethodAsync method.

A derived class inherits a method implementation by default, but it can override that implementation. When WMI attempts to invoke a method for a particular instance of a class, it starts at the class invoked by the client and works toward the base class in the hierarchy searching for the Implemented qualifier. If the API does not find an Implemented qualifier, the API does not execute the method. Providers of derived classes implement a method only to override the implementation provided by the base class.

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.

The Static qualifier indicates that WMI must execute the method using either a class or instance path.

When developing a method provider, you must tag every method parameter with the Id qualifier. The Id qualifier is used to identify and sequence the parameters in a method. WMI sets this qualifier to 1 for the first parameter in the method and increments it for each additional parameter.

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. Developers of method providers should also refer to the following topics for more information:

  • 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 and thus do not permit the creation of instances. The __Event system class, for example, is an abstract class. Instances are created from the __Event 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 parent 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 definition 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 provider for the class 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 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. Each of these references always takes the form of an object path, a string that uniquely identifies the location of the referenced class or instance. By storing paths rather than real objects in the association class, relationships can be added or removed without affecting the objects. All association classes are identified by the Association qualifier, one of the standard qualifiers defined by WMI for use with classes.

All WMI classes can be included in zero or more association classes. 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 an instance of the CIM_System class and 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


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 flag ToInstance. When defining the class using MOF, you should specify the constant WBEM_FLAVOR_FLAG_PROPAGATE_TO_INSTANCES.

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, a class instance, a property, a method, or a 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 describe the behavior of 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.

WMI flavors 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
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.


System Classes

WMI system classes are a collection of predefined classes included with the WMI SDK. 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's 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 Desktop 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, time is always GMT, and therefore this value must always be 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.

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


Interval Format

Date-time intervals are specified with a format that is similar to the date and time syntax specified by the Desktop 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 WBEM CIM Studio, see Using the Interval Editor.


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.


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\Security
  • 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 Security namespace contains the classes and instances that are used for the WMI security subsystem. 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 (URL). 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. 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"


Using the WMI SDK

The Windows Management Instrumentation (WMI) SDK provides a set of application interfaces, tools, and samples to help you understand and develop for the WMI system. Three applications are also included in this SDK that you can use to view and change the Common Information Model (CIM) repository.

Interface definition language (IDL) files are included for developers who want to build their own client and server stubs for accessing the CIM repository. Documentation of the entire WMI application programming interface (API) is available online.

The WMI SDK includes:

  • Applications for viewing and changing data in the CIM repository.
  • The Wbemuuid.lib library and associated header files that provide access to the WMI API using the C++ programming language.
  • Component Object Model (COM) sample programs.
  • Scripting sample programs.
  • Guide and reference documentation for the WMI API.


WMI SDK Applications

The WMI SDK includes several applications that you can use to view and change data in the CIM repository, configure event consumers, and view events. For more information, see the Applications Guide.

CIM Studio is the most extensive of the these applications. In addition to editing properties and qualifiers, CIM Studio can also edit classes and instances, generate and compile Managed Object Format (MOF) files, and generate provider code.

To use these applications, you must use a browser that supports Microsoft® ActiveX® controls, such as Microsoft® Internet Explorer.


MOF Language and Compiler

The Managed Object Format (MOF) language is a compiled language for defining classes and instances. The MOF compiler offers a textual means of adding data to the Common Information Model (CIM) repository. Although classes and instances can also be added through the WMI API using C/C++, MOF eliminates the need to write complex code. MOF provides developers and administrators with a simple and fast technique for modifying the CIM repository.

For information about how to call the MOF compiler, see MOF Compiler. For a guide to writing correct MOF syntax, see Managed Object Format (MOF) Language.


Component Object Model (COM) Sample Programs

WMI SDK

Component Object Model (COM) Programs

Component Object Model (COM) 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 a Readme.txt file in the subdirectory for each of these samples.

Sample | Description
Client | Client is a sample application that demonstrates some important WMI capabilities such as connecting to a namespace and listing logical disks.
CmdLineConsumer | CmdLineConsumer is a generic event consumer that spawns another application according to the logical consumer instance. To register this consumer, at the command prompt type: mofcomp cmdline.mof
CustomViews | CustomViews provides alternative views of objects contained in the WMI database. 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 | EventConsumer is a tutorial demonstrating a permanent event consumer. This application demonstrates how to create a COM object that exposes a class identifier (CLSID) and an implementation of the IWBEMUnboundObjectSink interface, and that includes a class factory.
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).
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.
ObjectPathParser | ObjectPathParser 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 Windows Management 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.
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 /?


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 following.

Directory name | 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 name | 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 name | 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 name | 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 name | 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 name | 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 name | 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.


WMI for Network Administrators and System Managers

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

The WMI SDK provides tools to build small applications and scripts you can use to extract useful information from the WMI repository or to control managed objects.

Network administrators and system managers will find the following WMI SDK topics especially useful:

  • You can use the WMI ODBC Adapter to develop database management applications. These applications gain access to data in database management systems (DBMS) using SQL for WMI.
  • Network Management with SNMP explains how to seamlessly integrate the modeling and manipulation of SNMP information into WMI.
  • Using the Scripting API, you can develop scripts and Visual Basic applications to view information about managed objects or to control managed objects.
  • Using The WMI ADSI Extension, you can perform queries to find objects contained in the Active Directory.


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. The DBMS vendors provide their adapters to link the ODBC interface to their specific API functions.

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 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 it were a database. By providing information to ODBC, the ODBC adapter functions as a driver to the ODBC driver architecture.

You cannot use the WMI ODBC adapter to create tables, add records, or edit records.

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

  • ODBC Adapter General Information
  • Microsoft Access
  • Microsoft Query
  • Crystal Reports
  • 16-Bit Client Applications


About the ODBC Adapter

You can set up applications such as Microsoft® Excel and Microsoft® Access to use the information provided by Windows Management Instrumentation (WMI) through the 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 that show the health of your network.

The ODBC adapter is supported only on Microsoft® Windows NT® version 4.0 with Service Pack 4. The information you get using the ODBC adapter is read only, which means you cannot edit any information in the CIM repository. The ODBC adapter supports only SQL SELECT.

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.


Microsoft Access

This 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 Microsoft Access.

When linking tables, Microsoft Access always assumes the same table qualifier for all its invocations. Microsoft 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 ODBC adapter maps the table qualifier to the WMI namespace, all table links are limited to the same WMI namespace. Microsoft Access makes non-qualified SQLExecDirect calls to the ODBC adapter. This is also true for passthrough queries.


Microsoft Query

This client application still enforces the ODBC version 1.0 limitation of 65 characters for the maximum length of a table qualifier string. The table qualifier in the ODBC adapter is the fully qualified namespace path in which the table resides. If you specify a namespace path in the Connections dialog box that exceeds 65 characters, you are not allowed to go between namespaces in the Microsoft® Query Add Tables dialog box.


Crystal Reports

This client application does not support the SQL_LONGVARCHAR data type. It stops a query if the query requests this type.

The functionality of the Browse button gives the user a "distinct sample" of a property within a class. This is true for classes with more than a hundred instances. For example, the Browse button is known to exhibit and return a different number of instances for the same column. This is expected as Crystal Reports uses an internal timer, measured in a fixed number of milliseconds, to show instances.


16-Bit Client Applications

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


ODBC Adapter General Information

The ODBC adapter has the following characteristics.

Properties named Index

The following classes contain properties named Index. Index is a reserved word in SQL:

Win32_SCSIController

Win32_NetworkAdapter

Win32_DiskDrive

Win32_DiskPartition

Win32_POTSModem

The SQL passthrough queries from Microsoft Access, Microsoft Query, and Microsoft® Visual Basic will all fail if Index is explicitly named in a SELECT clause or is referenced in a Where clause. Additionally, Microsoft Query expands "SELECT *" into an explicit list of all columns, including Index, which will cause an ODBC failure on these classes.

Work-arounds

In Access or Visual Basic, you must refer to the property in double-quotes, as in the following:

Select "Index" from win32_DiskDrive where "Index" = 0

Crystal reports automatically encapsulates property names in double-quotes. No work-around is needed.

There is no work-around for Microsoft Query.


Installing the ODBC Adapter

Windows Management Instrumentation (WMI) software development kit (SDK) installs the Open Database Connectivity (ODBC) version 3.0 components (driver manager and administrator), if required. The ODBC 3.0 driver manager is backward-compatible with 2.x ODBC 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 ODBC utility in the Windows control panel.

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

To add a user data source

  1. Click Add on the User DSN tab of the ODBC utility. You will then see the Create New Data Source dialog box.
  2. From the dialog box, select WBEM ODBC Driver.

  3. Click Finish. You will then see the Setup WBEM ODBC Datasource dialog box, and 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 the adapters.


API Conformance

The Windows Management Instrumentation (WMI) Open Database Connectivity (ODBC) adapter conforms to ODBC API Level 1, which includes the following functionality:

  • Allocates and frees the environment, connection, and statement handles.
  • Assigns storage for parameters in a Structured Query Language (SQL) statement and result columns.
  • Connects to data sources with adapter-specific dialog boxes.
  • Prepares and executes SQL statements.
  • Sets and inquires about statement and connection options.
  • Sends all or part of a parameter value.
  • Retrieves all or part of a result column.
  • Retrieves data from and information about a result set.
  • Retrieves catalog information (columns, special columns, statistics, and tables).
  • Retrieves adapter and data source information, such as supported data types, scalar functions, and ODBC functions.
  • Retrieves error information.


Using ODBC and WMI

The following sections show how to gather information from the Microsoft® Win32® provider about the status of the drives attached to your computer. You can use the same techniques to get information from any WMI provider for applications that can access data using ODBC.

For more information, see the following sections:

Microsoft Excel 97

Microsoft Access 97


Microsoft Excel 97

If you have Microsoft Query installed on your computer, you can populate the cells of an Excel 97 spreadsheet with information from WMI providers.

The following steps describe how to use Excel with the ODBC Adapter

To get data from WMI using Microsoft Excel and ODBC

  1. From your Excel spreadsheet, click Data, and then click Get External Data.
  2. Select Create New Query. The Choose Data Source dialog box appears.

    There are two tabs on this dialog box. The first tab is Databases. It contains any ODBC data sources that you have set up. If you have previously set up an ODBC data source for WMI, you can select the data source now or you can select the New Data Source option to add a new ODBC data source. The new data source will be available the next time you use Excel.

  3. Select New Data Source to open the Create New Data Source dialog box.

    The dialog box has an input box labeled What name do you want to give your data source? Choose a name that describes what this data source is used for because you may want to access it from other applications. For example, you could call it "WBEM ODBC for Excel". Another item in the dialog box is a drop-down list labeled Select a driver for the database that you want to access. Click the down arrow to show the choices for the drop down list, and select WBEM ODBC Driver.

  4. Click Connect. The Configure Connection dialog box appears.

    You can use this dialog box to specify 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 Excel spreadsheet gets data from your computer, you may be able to leave these boxes blank.

  5. Click Connect. The bottom window of this dialog box will show a namespace selection tree.
  6. To expand the tree, click the plus sign next to the root node.

  7. Select the check box next to the CIMV2 Namespace, and click OK. You will return to the Create new data source dialog box.
  8. From the Select a default table for your data source drop-down box, select the default table you want. You can also specify a class such as Win32LogicalDisk from the drop-down list. Otherwise, you will have a chance to specify this information later when you construct a query for this data source.

  9. To return to the Choose data source dialog box, click OK on the create new data source dialog box. The data source you just created will appear on the list of available data sources.
  10. Select your new data source, and click OK. The Query Wizard - Choose Columns dialog box appears.

    If you did not select a default table for the data source in the Create new data source dialog box, you will be placed at the first available class as shown above. The classes expand to show all available properties. Scroll down the list in the Available tables and columns window until you find Win32LogicalDisk. If you specified a default table in the Create new data source dialog box, you will be placed at that class with the properties expanded underneath as shown next.

  11. Select DeviceID.
  12. Click the button labeled > and this field will be added to the right-hand window labeled Columns in your query. Add the following properties of "Win32LogicalDisk" in the same way: FileSystem, FreeSpace, and Size as shown below.

  13. Click Next. The Query Wizard - Filter Data dialog box will appear. You can use this dialog box to limit the results of this query to only show data that meets certain criteria. For example, if you want to see only instances of Win32LogicalDisk that have more than 120 KB freespace you could set the fields of the Query Wizard - Filter Data as shown next. Select Freespace in the Column to filter list box. In the dropdown list and under the label Only include rows where, set the criteria to Is greater than. The drop-down list to the right has no label; set its value to 120000.

  14. Press Next, and the Query Wizard Sort Order dialog box will appear.

  15. In the drop-down list labeled Sort by, select DeviceID.
  16. Click Next and the Query Wizard Finish dialog box will appear.

  17. To save this query, click Save Query. In the future, you can access this query by selecting the Choose data source dialog box on the Queries tab. Saving this query can save you a lot of time if you use the same information on a regular basis, such as in reports.
  18. Make sure you select Return Data to Microsoft Excel, and click Finish. You will then return to Excel, and the Returning External Data to Microsoft Excel dialog box will appear.

  19. Click Properties, and the External Data Range Properties dialog box will appear.

    If you select the Refresh data on file open check box, the data will be updated each time you open your spreadsheet. Leave this box unchecked if you want the data on this sheet to remain static.

  20. Click OK to return to the Returning External Data to Microsoft Excel dialog box.
  21. From the drop-down menu on this dialog box, select the cell where you want the data to begin, and click OK. Excel will connect to the data source. and you will see the drive data appear on the spreadsheet.


Microsoft Access 97

You can display information from WMI providers through ODBC on forms in Access 97.

The following steps describe how to use Access with the ODBC Adapter.

To get data from WMI using Microsoft Access and ODBC

  1. From your Access database, click File, and then click Get External Data.
  2. Select Link Tables. The Link dialog box will appear.

  3. From the Files of type drop-down list, select ODBC Databases(). The Select Data Source dialog box opens. There are two tabs on this dialog box.

  4. 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 machine data source that you have set up previously, or the default machine data source called WBEM Source. For more information on WBEM Source, see Installing the ODBC Adapter.

  5. Click OK. The Configure Connection dialog box will appear.

    You can use this dialog box to 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.

  6. Click Connect. The bottom window of this dialog box will show a namespace selection tree.
  7. To expand the tree, click the plus sign next to the root node. Select the check box next to the CIMV2 Namespace, and click OK.

  8. Click OK , and the Link Tables dialog box will appear. Common Information Management (CIM) objects are represented as tables in this dialog box.

  9. Select an object about which you want to retrieve information, such as Win32LogicalDisk, and click OK. The Select Unique Record Identifier dialog box will appear.

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

  10. Select the DeviceID field, and click OK. The new table will be added to your database.

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


WMI to ODBC Mapping

Windows Management Instrumentation (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:

  • The WMI property name of the instance becomes the ODBC column name.
  • The WMI property value of the instance becomes the ODBC column value.
  • The WMI property qualifiers of the instance become ODBC 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, information in qualifiers that vary over instances is inaccessible. See SQLColumns for more information.

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. For more information, see SQLTables. The adapter exposes qualifiers on a per-class basis only. Therefore, the adapter does not access qualifier information that varies across instances.

WMI data types map to ODBC SQL data types. WMI uses variants to return property values. The 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 could not 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 could not 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 given a table with 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 (2 WMI instances).

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

The ODBC Adapter will return the following instances back to the client application (5 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:

  • "DSN=dataSourceName,"

    Includes the attribute-keywords, as described next, or

  • "DRIVER=driverName"

    Includes the attribute-keywords, as described next.

In addition to the standard data source name, user name, and password, the adapter recognizes the attribute-keywords NAMESPACES, DBQ, HOME, SERVER, SYSPROPS, AUTHORITY, LOCALE, UIDPWDDEFINED and IMPERSONATE, PASSTHROUGHONLY

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. Each namespace has an associated bitmap image representing its state. The bitmap image looks like a check box with a folder.

Clicking the folder alternately selects and cancels the selection of the namespace. If the check box or folder is not expanded (denoted by a PLUS SIGN next to the control), then all items in the folder are selected or canceled, depending on the current state of the folder. If the folder is already expanded or has no child items, then only the folder is affected.

The state of each folder is represented as follows:

State | Definition
Clear Unchecked Checkbox | Item is not selected and no child items (if any) are selected.
Gray Unchecked Checkbox | At least one child item is selected.
Clear Checked Checkbox | Item is selected, but no child items (if any) are selected.
Gray Checked Checkbox | Item is selected and at least one child item is selected.

The dialog box also allows namespace selection from a remote WMI repository. This functionality is available through the Browse button and text box.

If you choose to manually enter a remote server name in the text box (maximum length 128 characters), the current tree control is cleared and replaced by the tree control for the new remote server. If the text box is empty, the local server is used.

Click the Browse button to display a new Server Selection dialog box. This presents information similar to the Network Neighborhood. The dialog box initially displays the network resources on the local area network (LAN). There is an item in the list of servers named Entire Network that you can use to view the entire network (represented by a globe). If you double-click on an image that does not represent a server, the current display is cleared, and the contents of the chosen network resource are displayed.

The dialog box also has three bitmap buttons:

  • The Folder button enables you to traverse back to the previous network resource selection.
  • The Link view button displays all the network resources in list view format.
  • The Report view button displays all the network resources in report view format.


The NAMESPACES Attribute-Keyword

NAMESPACES 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:

NAMESPACES={namespace name, style}

Where style can be either:

shallow (include only the specified namespace), or

deep (include the specified namespace and all its children)

Examples

NAMESPACES={Root\Default, shallow}
Specifies just the Root\Default namespace.
NAMESPACES={Root\Default, deep}
Specifies the Root\Default namespace and all its children.
NAMESPACES={Root\Wellfleet, shallow},{Root\Cisco, deep}
Specifies the Root\Wellfleet namespace plus the Root\Cisco namespace plus all the children of the Root\Cisco namespace.
NAMESPACES=Root\Default
Equivalent to NAMESPACES={Root\Default,shallow}.


The DBQ Attribute-Keyword

DBQ is the database qualifier. This is the fully qualified, default, working namespace.


The HOME Attribute-Keyword

HOME 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.

Example: HOME=Root\Redmond;NAMESPACES=Fred

The fully qualified namespace is Root\Redmond\Fred.


The SERVER Attribute-Keyword

SERVER is the name of the target computer that will act 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.

Example: SERVER=\\REDMOND


The SYSPROPS Attribute-Keyword

SYSPROPS indicates whether the adapter exposes WMI system properties. Set this 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 Connection dialog box.


The AUTHORITY Attribute-Keyword

AUTHORITY indicates the Domain name to which the user account belongs. It can be NTLMDOMAIN.DomainName to specify an override domain.


The LOCALE Attribute-Keyword

LOCALE 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 ID (LCID).

For example, American English would appear as "MS\0x409"


The UIDPWDDEFINED Attribute-Keyword

UIDPWDDEFINED indicates that the user name and password have been defined (even if 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 they will remove these keyword/value pairs out 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 fail. Using the UIDPWDDEFINED keyword will force 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.


The IMPERSONATE Attribute-Keyword

IMPERSONATE indicates that the ODBC Adapter will attempt 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 permissions that are different than the current user.

Impersonation will fail 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 ODBC adapter is installed. From the tools menu go into User Manager for Domains to 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).

You will need to restart your computer for these settings/tokens to be activated.

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

Impersonation is not supported on Microsoft® 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.


The PASSTHROUGHONLY Attribute-Keyword

PASSTHROUGHONLY indicates that the ODBC adapter will only attempt to fetch the query data through a single direct WQL query statement.

Usually, if this attempt fails the adapter will attempt to fetch the query data through an alternative route. However, if PASSTHROUGHONLY is enabled, the adapter will fail at this point. This option was added because some non-passthrough alternatives to fetching query data are very slow. Therefore, to ensure that the user will either get a result or a failure quickly, the user can enable PASSTHROUGHONLY. You can also activate passthrough only mode through the check box control in the connection dialog box.

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


Multi-threading Issues in the Adapter and Client Applications

Since the ODBC Adapter Manager is thread-safe, the adapter is inherently thread-safe.

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

An action on one of these objects causes the Adapter Manager to enter a critical section for that object. In the case of SQLCancel, the Adapter Manager enters a "cancel-in-progress" critical section. This prevents SQLCancel from being reentered before the first one 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 a SQLFreeStmt or SQL_CLOSE operation. The adapter returns SQL_SUCCESS_WITH_INFO with a SQLSTATE of 01S05. This causes the Adapter 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 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 it has been entered (non-zero owning thread). This is the test for determining if a 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 it needs to cancel the operation, however it deems appropriate.

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-per-statement handle.
  • Have multiple connection handles, with a single statement handle-per-connection handle and a single thread-per-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, 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.


ODBC Adapter Synchronous and Asynchronous Operation

By default, the 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 ODBC 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 with SQL_SUCCESS or SQL_SUCCESS_WITH_INFO. Otherwise, the function returns with SQL_STILL_EXECUTING.

Note The ODBC adapter is a Windows Management Instrumentation (WMI) 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.


The SQL Grammar

The 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 SQL Reference

The following SQL reference topics apply to the WMI implementation of the ODBC Adapter:

ODBC Minimum SQL Grammar

Level 1 Provider SQL Grammar

Quick Reference Table

SQLColAttributes (Core)

SQLColumns (Extended Level 1)

SQLDriverConnect (Extension Level 1)

SQLError (Core)

SQLGetConnectOption (Extension Level 1)

SQLGetFunctions (Extension Level 1)

SQLGetInfo (Extension Level 1)

SQLGetStatementOption (Extension Level 1)

SQLGetTypeInfo (Extension Level 1)

SQLTables (Extension Level 1)


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 datatype.
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

WMI SDK

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

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 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:

  • Microsoft® Visual Basic®
  • Visual Basic for Applications
  • Microsoft® 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 website at: http://msdn.microsoft.com/scripting/. This site contains detailed information on Microsoft Visual Basic Scripting Edition and Microsoft 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 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:

objWbemObjectSet = objWbemServices.Something(
  strParam,
  [iFlags=0],
  [objWbemNamedValueSet=null]
);

Describes a Something method of an SWbemServices object. 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®, Microsoft® 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 Microsoft Visual Basic, Microsoft Visual Basic Scripting Edition, Microsoft 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.

  • Security Issues When Writing Scripts For WMI

    Shows you how to read and set security settings when developing applications with the scripting API.

  • Making an Asynchronous Call Using the Scripting API

    Shows you how to use asynchronous methods in your applications.

  • 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 Microsoft Visual Basic or Microsoft VBScript, object creation is supported using the CreateObject call. For example

Set locator = CreateObject("WbemScripting.SWbemLocator")

JScript Support for Object Creation

In Microsoft 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. These are:

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);
}


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)

Security Settings Component

The following pseudo-BNF describes the security settings component.

wmiMoniker    : "winmgmts:" [securitySetting] "!" <objectPath>
        | "winmgmts:" [securitySetting]
        | "winmgmts:" <objectPath>

objectPath       : a valid WMI Object Path - see section below for more details

securitySetting    : "{" <ows> authAndImpersonLevel
       [<ows> "," <ows> privilegeOverrides]<ows> "}"

authAndImpersonLevel : authenticationLevel
        | impersonationLevel
        | authenticationLevel <ows> "," <ows> impersonationLevel
        | impersonationLevel <ows> "," <ows> authenticationLevel
        | 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"

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.

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 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 Microsoft® 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.
  3. If Microsoft WBEM Scripting V1.0 Library does not appear 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 API V1.0 Library appears on the references list. Make sure you check the box next to this item in the list.


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.

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. Logon 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 Microsoft Visual Basic, Visual Basic, Scripting Edition, Jscript, and within HTML, see Scripting Examples.


Security Issues When Writing Scripts For WMI

There are several security issues that need to be considered when developing scripts for WMI.

  • Setting the DCOM Impersonation Level for the Scripting API
  • Setting the DCOM Authentication Level for the Scripting API
  • Setting Privileges for 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 you do not set this property, WMI may not use the default DCOM impersonation level defined for your computer. If the impersonation level is not sufficient, the provider may refuse the request or provide incomplete information.

DCOM supports four levels of impersonation.

Name/Value | Moniker Name | Meaning
wbemImpersonationLevelAnonymous 1 | Anonymous | This impersonation level hides the credentials of the caller. Calls to WMI may fail with this impersonation level.
WbemImpersonationLevelIdentify 2 | Identify | This impersonation level allows objects to query the credentials of the caller. Calls to WMI may fail with this impersonation level.
WbemImpersonationLevelImpersonate 3 | Impersonate | This impersonation level allows objects to use the credentials of the caller. This is the recommended impersonation level for WMI scripting API calls.
WbemImpersonationLevelDelegate 4 | Delegate | This impersonation allows objects to permit other objects to use the credentials of the caller. This impersonation will work with WMI scripting API calls, but may constitute an unnecessary security risk and is supported only under Windows 2000.

Calls to the Scripting API for WMI may fail with an error code of wbemErrAccessDenied (hexadecimal 0x80041003) if the impersonation is not set to wbemImpersonationLevelImpersonate or wbemImpersonationLevelDelegate. There are two ways to specify the impersonation level of an API call. 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 Microsoft 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 Win32 process that has a process ID 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.

The other way you can set the impersonation level is from the security object called Security_ that is a property of objects of type 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.

This security object is of type SWbemSecurity and has three properties, which are Privileges, AuthenticationLevel, and ImpersonationLevel. When you set the properties of this object, these security settings will be 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 and calls using this object or objects created from it such as objects of type SWbemObject will succeed. For 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 impersonation level of wbemImpersonationLevelImpersonate 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 for 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 scripting API, you can set the DCOM authentication level that WMI will use.

Name/Value | Moniker Name | Meaning
wbemAuthenticationLevelDefault 0 | Default | WMI will use the default Windows Authentication setting.
wbemAuthenticationLevelNone 1 | None | Use 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 levels and encrypts the argument value of each remote procedure call.

There are two ways to specify the authentication level of an API call. If you are using monikers you can simply specify this parameter as part of the moniker. When setting 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.

For example:

Set Service = GetObject("winmgmts:{impersonationLevel=impersonate,authenticationLevel=pktPrivacy}!root/cimv2")

Set Service = GetObject("winmgmts:{authenticationLevel=pktPrivacy}!root\cimv2")

or

set service = GetObject("winmgmts:")
Service.Security_.authenticationLevel = wbemAuthenticationLevelPktPrivacy

You can see more examples of monikers at Object Creation and Monikers.


Setting Privileges for the Scripting API

You may need to set Microsoft® Windows NT®/Windows® 2000 privileges when using the scripting API to performing certain tasks such as examining the Windows NT/Windows 2000 security log or requesting that the operating system shutdown. You can set these privileges from the Privileges property of a SWbemSecurity object or with a moniker. 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.

Note 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.

To set Windows NT/Windows 2000 privileges in Microsoft 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 have set this privilege using a Windows NT/Windows 2000 privilege string and the SWbemPrivilegeSet.AddAsString method.

objwbemLocator.Security_.Privileges.AddAsString ("SeDebugPrivilege")

Set Windows NT/Windows 2000 privileges Using Monikers as follows:

Set Service = GetObject("winmgmts:{impersonationLevel=impersonate, (Debug)}")

You may want to revoke a specific privilege and set another. The following example sets the SeDebugPrivilege privilege and revokes the SeRemoteShutdownPrivilege privilege:

Set Service = GetObject("winmgmts:{impersonate,(Debug,!RemoteShutdown)}")

Here are some things to consider when working with privileges:

  • 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 version 4 platforms, you must set the privileges either
    • On the SWbemLocator 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 app.
  • You can set privileges on Microsoft® Windows® 95 platforms, but these settings will have no effect.
  • On Windows NT version 4 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 IE or 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.

For a complete list of privileges see WbemPrivilegeEnum.


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 name space when running a script from an ASP page. This is because Internet Information Services (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 Permission Editor (Wbemperm.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 via 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 Microsoft® Windows NT® version 4. Instead, the credentials used to run IIS (Internet Information Services) 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 Local System 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.


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 version 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 version 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 Internet Information Services (IIS), the client, which is Microsoft Internet Explorer, requests impersonation with IIS. For Windows NT version 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. 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.

Note This registry key is sometimes reset to 0 when you upgrade WMI. You should check this registry key after upgrading WMI.


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.


Scripting Examples

The following list of examples shows you how you can use the scripting API with Microsoft Visual Basic and Microsoft Visual Basic Scripting Edition.

Name | Description
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 Microsoft Visual Basic, Visual Basic Scripting Edition 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 Microsoft Visual Basic and from an HTML page, using VBScript.


SWbemServices.SubclassesOf Examples

Microsoft Visual Basic Example

Private Sub subclassesof_Click()
' This example fills a list box with the
' Subclasses of Cim_ComputerSystem

Dim objWbemServices As SWbemServices
Dim objWbemLocator As New SWbemLocator
Dim objWbemObjectSet As SWbemObjectSet

    Set objWbemServices = objWbemLocator.ConnectServer 'log on
    Set objWbemObjectSet = _
    objWbemServices.subclassesof("Cim_ComputerSystem")
    For Each instance In objWbemObjectSet
        objMyList.AddItem (instance.Path_.RelPath)
    Next instance
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)

    Set objwbemNamedValueSet = objWbemAsyncContext.Item("sinkname")
    If objwbemNamedValueSet.Value = "SubclassesOfAsync" Then
        MsgBox (objWbemObject.Path_.RelPath)
    End If
    Set objWbemObject = Nothing
End Sub

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">
    alert("Completed");
</script>
<script FOR="thesink"
EVENT="OnObjectReady(objObject, objAsyncContext)" LANGUAGE="JScript">
    document.all.info.innerText = objObject.Name;

</script>
<script

FOR="document" EVENT="onclick()" LANGUAGE="JScript">
        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: <span ID="info">unknown </span>.
<object ID="locator" CLASSID="CLSID:76A64158-CB41-11D1-8B02-00600806D9B6">
</object>
<object ID="thesink" CLASSID="CLSID:75718C9A-F029-11d1-A1AC-00C04FB6C223">
</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 Microsoft 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_.

Private Sub ex_method_Click()
Dim process As SWbemObject
Dim method As SWbemMethod

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

End Sub

Visual Basic Scripting Edition Example

This is similar to the example above except 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

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.innerText = "executed successfully."
    else
        document.all.info.innerText = "Failed!."
    end if

end sub
</script>
</head>

<body>

<p>The Method <span ID="info">unknown </span>.
<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. If you close the "waiting for events" dialog box, the program will stop waiting for events.

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

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
    end if
loop

WScript.Echo "finished"


SWbemServices.ExecNotificationQueryAsync Examples

Microsoft Visual Basic Example

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 "instancesof async now running asynchronously "

End Sub

Private Sub sink_OnObjectReady(ByVal objWbemObject As WbemScripting.ISWbemObject, ByVal objWbemAsyncContext As WbemScripting.ISWbemNamedValueSet)

Set cntxt_item = objWbemAsyncContext.Item("sinkname")

    If cntxt_item.Value = "ExecNoteAsync" Then
        MsgBox " got event: " & objWbemObject.TargetInstance.Message
    End If

    Set objWbemObject = Nothing

End Sub

Dim service
Dim sink

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>

Visual Basic Scripting Edition ASP Example

This sample illustrates the use of the WMI Scripting API within an ASP, using Visual Basic Scripting Edition. 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®, Microsoft® Visual Basic for Applications, Microsoft® 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 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 Common Information Model (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.


The WMI ADSI Extension

[This is preliminary documentation and subject to change.]

The Windows Management Instrumentation (WMI) Active Directory Service Interface Extension is an implementation of a third-party extension to Microsoft® Active Directory™ Service Interfaces (ADSI). The extension adds properties and methods to ADSI objects.

These properties and methods connect ADSI and WMI. Specifically, you can use the extension to look up an Active Directory object and then convert the object name into one that can be used in WMI. Then you can use WMI to manage the object.

For detailed information on ADSI Extensions, see the SDK documentation on the MSDN Web site on http://www.microsoft.com.

This section contains the following subsections:

  • About the WMI ADSI Extension
  • Using the WMI ADSI Extension
  • Code Samples
  • Reference


About the WMI ADSI Extension

[This is preliminary documentation and subject to change.]

You can use the Microsoft® Active Directory™ Service Interfaces (ADSI) to perform queries to find objects contained in the Active Directory. You can use Windows Management Instrumentation (WMI) to manage objects in WMI. However, the result of using WMI and ADSI separately can produce incompatible results.

For example, if you want to use WMI to manage objects associated with a particular computer object returned by an ADSI query, you must convert the Directory Service (DS) computer object name into a form usable by WMI (a WMI path name). Using the DS computer object name, you must manually construct the corresponding WMI ComputerSystem object. This process is complicated and time consuming. The WMI ADSI Extension performs this process automatically.

For more information on how a DS object and a WMI object work together, see DS and WMI Object Architecture.

This section contains information on the following topics:

  • DS and WMI Object Architecture


DS and WMI Object Architecture

[This is preliminary documentation and subject to change.]

Although the WMI ADSI Extension can be used to map many different kinds DS objects to their WMI counterparts, the current implementation maps computer objects only. Specifically, the WMI ADSI Extension maps DS Computer class objects to WMI Win32_ComputerSystem class objects, as shown in the following figure.

For detailed information on ADSI Extensions, see the SDK documentation on the MSDN Web site on http://www.microsoft.com.

ADSI is extended by adding a new interface—IWMIExtension. The WMI ADSI Extension supports a dual interface. It can be used in the Microsoft® Visual Basic®, Microsoft® Visual Basic® Scripting Edition (VBScript), and the C++ programming environments. The WMI interfaces returned by the methods in this interface are the WMI scripting interfaces, ISWbem (and not IWbem). These are the interfaces typically used when writing VB code or script to WMI. However, they are dual and can be equally used in C++ code. This interface contains two new methods, and one new property.

  • Getting an Object with the ADSI Extension
  • Getting a Service with the ADSI Extension
  • Getting a Path with the ADSI Extension


Getting an Object with the ADSI Extension

[This is preliminary documentation and subject to change.]

The GetWMIObject method returns a pointer to an ISWbemClassObject interface. This interface is supported by SWbemClassObject COM objects, which represent all WMI managed objects. An instance of the Win32_ComputerSystem class is represented in WMI by a COM object of class SWbemClassObject, which supports the ISWbemClassObject interface to SWbemClassObject.

The pointer returned by GetWMIObject can be used to call methods or read/write properties of the SWbemClassObject COM object. By doing so, you actually manipulate the WMI object it represents (in this case, the instance of Win32_ComputerSystem).

Here is a Visual Basic example showing how the GetWMIObject extension method is used.

Dim WMIObject As SWbemObject
Dim ADSObject As IADs

'   Assume ADSObject points to an ADSI Computer object.
Set WMIObject = ADSObject.GetWMIObject ()
Debug.Print    WMIObject.Manufacturer


Getting a Service with the ADSI Extension

[This is preliminary documentation and subject to change.]

The GetWMIServices method returns a pointer to the WMI namespace in which the appropriate WMI ComputerSystem object resides. This pointer is an ISWbemServices interface pointer.

This pointer can be used to call properties and methods in this interface. Examples of properties and methods include operations that get objects from that namespace or invoke WQL queries.

Here is a Visual Basic example showing how the GetWMIServices extension method is used.

Dim WMIServices As SWbemServices
Dim WMIObject   As SWbemObject

'   Assume ADSObject points to an ADSI Computer object.
Set WMIServices = ADSObject.GetWMIServices
Set WMIObject   = WMIServices.Get("Win32_LogicalDisk.DeviceID=""C:""")

Debug.Print "WMI Object from Services : "+WMIObject.Path_.RelPath


Getting a Path with the ADSI Extension

[This is preliminary documentation and subject to change.]

The WMIObjectPath property contains the WMI path of the corresponding WMI Win32_ComputerSystem class object. For example, the WMIObjectPath property of the WMI ADSI Extension would return:

"WINMGMT://MYCOMPUTER/root/cimv2:Win32_ComputerSystem.Name='MYCOMPUTER'".

for the MYCOMPUTER computer object. The MYCOMPUTER object represents the moniker to the WMI matching object.

The path returned by the WMIObjectPath property is the moniker to the object. For Visual Basic and VBScript, the moniker is usable without modification. For C++, use the SWbemObjectPath object in the WMI scripting API to parse the moniker into an object path that can be used in the C++ programming environment.


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 locating objects in the Microsoft® Active Directory™, and using the results to manage objects in WMI. The most typical case is managing a group of computers using WMI; for example, when you want to apply changes across all computers in an Organizational Unit (OU).

Note The WMI ADSI Extension is self-registering. It registers itself according to ADSI Extension rules to extend the appropriate classes in the LDAP ADSI namespace.

To emphasize the usefulness of the WMI ADSI Extension, the following two examples are provided:

  • Creating WMI Paths Without the ADSI Extension

    Demonstrates how to create WMI paths using the Active Directory property Computer.Name without the aid of the WMI ADSI Extension.

  • Creating WMI Paths Using the ADSI Extension

    Demonstrates how to create WMI paths using the WMI ADSI Extension.


Creating WMI Paths Without the ADSI Extension

[This is preliminary documentation and subject to change.]

The following script example shows how to create WMI paths using the Active Directory property, Computer.Name, without the aid of an extension. You must identify all computers in a group in the Active Directory, then use WMI to release their respective IP addresses.

'  Get the ADSI object for the "Accounting" OU container
Set Accounting = WScript.GetObject("LDAP://OU=Accounting, CN=NTDEV, DC=Microsoft, DC=com")

'  Enumerate the computers in this container in the DS
For Each Computer in Accounting

     'Get the WMI Win32_ComputerSystem object for this DS computer
     Machine = "WINMGMTS://" + Computer.Name  + "/root/cimv2:Win32_ComputerSystem=" + Computer.Name
     Set ManagedComputer = WScript.GetObject(Machine)

     'Get all network adapter configurations on this Win32 computer (WMI association traversal)
     Set Adapters = ManagedComputer.Associators_("Win32_NetworkAdapterConfiguration","Win32_SystemSetting")

     For Each Adapter in Adapters
          'If network adapter is configured for DHCP, release it's address (WMI method invocation)
          If Adapter.DHCPEnabled
               Adapter.DHCPRelease()
     Next

Next


Creating WMI Paths Using the ADSI Extension

[This is preliminary documentation and subject to change.]

The following example shows how to create WMI paths using the WMI ADSI Extension.

//Get the ADSI object for the "Accounting" OU container
Set Accounting = WScript.GetObject("LDAP://OU=Accounting, CN=NTDEV, DC=Microsoft, DC=com")

//Enumerate the computers in this container in the DS
For Each Computer in Accounting

     //Get the WMI Win32_ComputerSystem object for this DS computer using the WMI ADSI Extension
     Set ManagedComputer = Computer.GetWMIObject()

     //Get all network adapter configurations on this Win32 computer (WMI association traversal)
     Set Adapters = ManagedComputer.Associators_("Win32_NetworkAdapterConfiguration","Win32_SystemSetting")

     For Each Adapter in Adapters
          //If network adapter is configured for DHCP, release it's address (WMI method invocation)
          If Adapter.DHCPEnabled
               Adapter.DHCPRelease()
     Next

Next


Code Samples

[This is preliminary documentation and subject to change.]

The following code samples have been provided to help you understand how to use the ADSI Extension.

  • Using the WMI ADSI Extension with Visual Basic
  • Using the WMI ADSI Extension with VBScript (and the Windows Scripting Host)
  • Using the WMI ADSI Extension with C++


Using the WMI ADSI Extension with Visual Basic

[This is preliminary documentation and subject to change.]

Private Sub TestWMIADSIExtension()
    Dim ext   As WMIExtension
    Dim comp  As IADs
    Dim wobj  As SWbemObject
    Dim wserv As SWbemServices
    Dim myStr As String

'   Get the ADSI computer object from ADSI LDAP provider
    Set comp = GetObject("LDAP://CN=MYCOMPUTER,CN=Computers,DC=ntdev,DC=microsoft,DC=com")
    Debug.Print comp.Name

'   This causes the QueryInterface on the extension object interface
    Set ext = comp

'   Use the WMIObjectPath property to retrieve the path of the respective WMI object
    myStr = ext.WMIObjectPath
    Debug.Print myStr
'   Use the path to get the WMI object.
    Set wobj = GetObject(myStr)
    Debug.Print "From WMIObjectPath - " + wobj.Path_.Path
    Set wobj = Nothing

'   Use the GetWMIObject method to get the WMI object directly
    Set wobj = ext.GetWMIObject
    Debug.Print "From GetWMIObject - " + wobj.Path_.Path
    Set wobj = Nothing

'   Use the GetWMIServices method to get the services pointer associated with the WMI object
    Set wserv = ext.GetWMIServices
'   This services pointer can now be used to perform other WMI operations
    Set wobj = wserv.Get("Win32_LogicalDisk.DeviceID=""C:""")
    Debug.Print "From GetWMIServices - " + wobj.Path_.Path
    Set wobj  = Nothing
    Set wserv = Nothing

    Set ext   = Nothing
    Set comp  = Nothing
End Sub


Using the WMI ADSI Extension with VBScript (and the Windows Scripting Host)

[This is preliminary documentation and subject to change.]

Dim ADSObject
Dim WMIObject
Dim WMIServices
'   Get the AD computer object through the ADSI LDAP provider.
Set ADSObject = GetObject("LDAP://CN=MYCOMPUTER,CN=Computers,DC=ntdev,DC=microsoft,DC=com")
WScript.Echo "Got ADSI Object : "+ADSObject.Name

'   Get the path to the matching WMI object (uses property WMIObjectPath).
WScript.Echo "WMI Object Name is : "+ADSObject.WMIObjectPath

'   Get the matching WMI object itself (uses method GetWMIObject).
Set WMIObject = ADSObject.GetWMIObject
WScript.Echo "Got WMI Object : "+WMIObject.Path_.RelPath

'   Get the WMI services pointer associated with the WMI object.
Set WMIServices = ADSObject.GetWMIServices

'   The services pointer can be used for other WMI operations.
Set WMIObject = WBEMServices.Get("Win32_LogicalDisk.DeviceID=""C:""")
WScript.Echo "WMI Object from Services : "+WMIObject.Path_.RelPath


Using the WMI ADSI Extension with C++

[This is preliminary documentation and subject to change.]

// ADSiTesting.cpp : Defines the entry point for the console application.

#include "stdafx.h"
#include <iostream.h>
#include <objbase.h>
#include <activeds.h>
#include <adshlp.h>
#include <wbemcli.h>
#include <wbemads.h>
#include <stdio.h>

int main(int argc, char* argv[])
{
    IADs            *pComp    = NULL;
    IADs            *pComp2;
    IWMIExtension   *pWMI     = NULL;
    ISWbemObject    *pObj     = NULL;
    ISWbemServices  *pSvc     = NULL;

    wchar_t Obj[80] = L"LDAP://CN=MYCOMPUTER, CN=Computers, DC=ntdev, DC=Microsoft, DC=com";

    CoInitialize (NULL);

    //Get the particular ADSI Computer object.
    HRESULT hRes = ADsGetObject( Obj, IID_IADs, (void**)&pComp );

    if ( FAILED (hRes) )
    {
        cout << "Error: Failed to get object\n";
        exit(1);
    }

    //Get the WMI ADSI Extension interface on this object.
    hRes = pComp->QueryInterface ( IID_IWMIExtension, (void**)&pWMI );

    if ( FAILED (hRes) )
    {
        cout << "Error: Failed to get IWMIExtension interface\n";
        exit(1);
    }

    //Get the WMI Object using the extension.
    hRes = pWMI->GetWMIObject(&pObj);
    if ( FAILED (hRes) )
    {
        cout << "FAILED: Failed to get ISWbemObject interface\n";
        exit(1);
    }

    //Get the WMI object path (moniker) using the extension
    BSTR strObjPath = NULL;
    hRes = pWMI->get_WMIObjectPath ( &strObjPath );

    if ( FAILED (hRes) )
    {
        cout << "FAILED: Failed to get the object path\n";
        exit(1);
    }

    //Get the WMI Services pointer using the extension
    hRes = pWMI->GetWMIServices ( &pSvc );
    if ( FAILED (hRes) )
    {
        cout << "FAILED: Failure on valid parameter to GetWMIServices\n";
        exit(1);
    }

    //Cleanup.
    pObj->Release();
    pSvc->Release();
    SysFreeString(&strObjPath);
    pWMI->Release ();
    pComp->Release();

    return 0;
}


Reference

[This is preliminary documentation and subject to change.]

This section contains information on the following topics:

  • Definition of the Interface


Definition of the Interface

[This is preliminary documentation and subject to change.]

The following code defines this interface:

Interface IWMIExtension : IDispatch
{
    HRESULT WMIObjectPath   ([out, retval] BSTR *strWMIObjectPath);
    HRESULT GetWMIObject    ([out, retval] ISWbemObject **objWMIObject);
    HRESULT GetWMIServices  ([out, retval] ISWbemServices **objWMIServices);
}


WMI for Application Developers

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.

Application developers will find the following WMI SDK topics especially useful:

  • Programming Basics for WMI Applications
  • Event Notification
  • Creating a WMI Application in MFC


Programming Basics for WMI Applications

Windows Management Instrumentation (WMI) applications are standard executable files (.exe files) and Microsoft® Windows NT®/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 Local System 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 Microsoft® 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®/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.

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.


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);
  SysFreeString(KeyProp);

  // Attach Key qualifier to mark the "Index" property as the key.
  // ============================
  IWbemQualifierSet *pQual = 0;
  pNewClass->GetPropertyQualifierSet(KeyProp, &pQual);

  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 (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

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.


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. System context values resemble system classes and system properties because they also begin with a double-leading underscore.

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.


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. 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®/Windows® 2000 Event Log service. On Microsoft® 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.

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. Because intrinsic events map to system classes, they cannot be modified or extended.

The following table briefly describes the set of system classes relating to intrinsic events.

Event system class | 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.

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.

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®/Windows® 2000, DCOM runs automatically. On the Microsoft® 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 following in Implementing IWbemEventConsumerProvider.
  • Supplying one or more implementations of the IWbemUnboundObjectSink interface, as described following 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 FindConsumer(
        /* [in] */ IWbemClassObject __RPC_FAR *pLogicalConsumer,
        /* [out] */ IWbemUnboundObjectSink __RPC_FAR *__RPC_FAR
            *ppConsumer
        );

    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
        );

};

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.

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 (e.g. 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.

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.


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 Samples\vc\SimpleClient folder of the WMI SDK.

Note The sample code in this tutorial was built with Microsoft® Visual C++ 5.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 the 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 executables.
  3. Choose a location for your program and give it the name, WbemClient.

  4. Create a dialog-based application without 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.

    Add the following code to the function.

    // CWbemClientDlg connection

void CWbemClientDlg::OnConnect()
{
    // Indicate success.
    m_outputList.ResetContent();
    m_outputList.AddString(_T("Connected to namespace"));
}
  10. 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. ClickConnect. When you see Connected in the trace window, Enum Disks should be enabled. Click it; you should see a list of logical devicesin 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 the 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 the 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 the Search for Classes toolbar button 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 toolbar button. To delete a class or instance programmatically, use IWbemServices::DeleteClass or IWbemServices::DeleteInstance, respectively.


WMI for Provider Developers

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 topics especially useful:

  • Programming Basics for WMI Providers
  • WMI Providers
  • SNMP Providers
  • Provider Framework
  • Security and Authentication


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®/Windows® 2000 services
  • Local or remote standard executables (.exe files)

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: 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: SOFTWARE\Microsoft\WBEM\Windows Management. This key contains a REG_MULTI_SZ value named "Autorecover MOFs (recovered)" 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.


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®/Windows® 2000 platforms running Windows Management Instrumentation (WMI) Nova / M1 release or later. It does not apply to the original WBEM v1.0 SDK release, nor does it apply to the Microsoft® 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 users SID to the corresponding providers. If the provider is written appropriately, it will attempt to access information with the users 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 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;
    datetime UnloadTimeout;
    boolean InitializeAsAdminFirst;
    [Values{"None"}: ToSubClass] sint32 ImpersonationLevel = 0;
    [Values{"CLSID", "Namespace", "COM Object"}: ToSubClass] sint32 InitializationReentrancy = 0;
    boolean PerUserInitialization = 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 WBEMTEST, 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 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 below.


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. To make this determination, WMI uses a property in system-wide instance of a class in the \Root namespace. The amount of time specified in this property is the minimum amount of time that a provider can remain idle before WMI begins the unloading process.

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.


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 runtime 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 WMI 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 do 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, tan 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. Class 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. There are six parameters to the method:

  • The object path for the class 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 system 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 pInParams 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 executables 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
{
Name  = "FaxEventProvider";
CLSID = "{AA7828C5-95F9-11d2-BB0D-00C042424242}";

DefaultMachineName = NULL;
ClientLoadableCLSID = NULL;
ImpersonationLevel = 0;

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" };
};


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
Event Log Provider | Provides access to data and notifications of events from the Microsoft® Windows NT®/Windows® 2000 Event Log.
Microsoft Windows Installer Provider | Provides access to information about applications that are installed using Microsoft® Windows® installer.
Performance Monitor Provider | Provides access to data from the Windows NT/Windows 2000 Performance Monitor.
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.
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®/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.


Registering the Event Log Provider

The Event Log Provider is registered automatically when the WMI SDK is installed; 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 Microsoft® 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 Microsoft® 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 nonsystem 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. This class includes methods you can use to set a log file's overwrite policy and maximum file size and perform operations to clear and back up the event log. The overwrite policy indicates when log files can be overwritten; 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;
    string            SourceName;
    string            Type;
    uint16            Category;
    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.
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.
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 the 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 the Win32_NTLogEvent and Win32_UserAccount, a class defined in the Microsoft 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 the 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 the wealth of 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.


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 is compatible with 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 has an associated entry 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 Microsoft® 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 Microsoft® 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 www.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 Microsoft 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 WBEM 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.

After doing this, you perform instance enumeration.


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.

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 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.

Classes | 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.
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.
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% 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.

Classes | Description
Product | A concrete 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 component 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 Desktop 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 Checks classes.

Classes | Description
Condition | Instances of this class represent checks that can be used to modify the selection-state of any entry in the Feature class, based on a conditional expression. If Condition evaluates to True, the corresponding Level value in the Feature class will be set to the value specified in the Condition class's Level property. Using this mechanism, any feature can be permanently disabled (by setting the Level to 0), set to be always installed (by setting the Level to 1), or set to a different install priority (by setting Level to an intermediate value). The Level may be set based upon any conditional statement, such as a test for platform, an operating system, a particular property setting, etc. - see the Windows installer documentation for more information.
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 is should be either on or off 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 (DSN's) that need 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, you 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 Actions classes.

Classes | Description
BindImageAction | Instances of this class represent the binding of executables to their imported DLL's. The virtual address of each function that is imported from all DLL's is computed and saved in the importing image's Import Address Table (IAT).
ClassInfoAction | Instances of this class represent COM class information that needs to be registered with the system.
CreateFolderAction | Instances of this class represent folders for software elements about 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 needs to be registered with the system.
MoveFileAction | Instances of this class represent files that already exist on the your computer, and need 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 must 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 are derived from the DMTF CIM_Setting class. Frequently, components of a computer system need to be reconfigured or changed during active use. For example, a mobile computer's configuration changes when you connect it to a larger system or network. Plugging in interchangeable hardware cards, like PCMCIA cards, can drastically change the capability of a system. Many of these components have capabilities that can be configured to different levels, or can be turned on or off, depending on the desired use.

When designing an information model for a management domain, you must capture detailed information about all of the various capabilities of a particular system element and identify which of these capabilities are being exploited in a particular system. Use configurations and settings to capture a set of properties that are meaningful within the context of a particular set of associations.

Here is a listing of Settings classes.

Classes | 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.
Upgrade | Instances of this class contain information on how to perform an upgrade of a product and how to handle installations when related versions of the product are already installed.


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.

Classes | 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.

Classes | Description
InstalledSoftwareElement | Instances of this association class allow you to identify the computer a particular software element is installed on.
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 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®/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.


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®/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.


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

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 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 Microsoft® Windows 95® and Windows 98 platforms. This clause is unnecessary on Microsoft® 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 the Windows Driver Model (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 hardware components that conform to the WMI for WDM standard.

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 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 creates instances on demand in response to application requests. 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 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).


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}" ;
};

instance of __ClassProviderRegistration
{
  Provider = $WMIData;
  InteractionType = 1;
  ResultSetQueries = {"select * from meta_class"};
  ReferencedSetQueries ={"select * from meta_class"};
  UnsupportedQueries = NULL;
  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 WMI for WDM class provider defines the WMIBinaryMofResource class in the Root\WMI namespace to support 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, volatile]     uint32 LowDateTime ;
  [read, volatile]     uint32 HighDateTime ;
};

The Name property specifies the name of the WMI-for-WDM – enabled driver that is represented by a class in the CIM repository. The LowDateTime and HighDateTime properties record when the class was last updated.


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 SDK installation:

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 Microsoft Win32 classes are read-only. Applications using the Win32 Provider cannot change them. However, there are several properties that can be modified by calling IWbemServices::PutInstance or IWbemServices::PutInstanceAsync. The following classes contain properties that can be set by client applications:

Win32_BaseService

Win32_ComputerSystem

Win32_Environment

Win32_LogicalDisk

Win32_OperatingSystem

Win32_OSRecoveryConfiguration

Win32_PageFile

Win32_Registry


Setting Properties in the Win32_BaseService Class

The Win32_BaseService class represents executable objects that are installed in a registry database maintained by the Microsoft® Windows NT®/Windows® 2000 Service Control Manager. The Win32_BaseService class has a single modifiable property: State. State is a character string that specifies the current state of a service.

The Microsoft Win32 Provider makes calls to the Service Control Manager to retrieve and update the State property. For example, the Win32 Provider first calls OpenService to gain access to a service, QueryServiceStatus to retrieve information about a service, and ControlService to change a service's state.

When a client application calls IWbemServices::GetObject or GetObjectAsync to retrieve the value of the State property, one of the following values can be returned:

Continue Pending | Pause Pending
Paused | Running
Start Pending | Stop Pending
Stopped | Unknown

However, State can only be set to one of three values: Running, Paused, or Stopped. When a client application calls PutInstance or PutInstanceAsync to change the state of a service, the return value indicates whether or not the Service Control Manager has successfully accepted the request. The return value does not indicate whether the change of state was successful. For example, the Win32 Provider returns WBEM_E_FAILED if the service does not allow a client to terminate it by setting its State property to Stopped.


Setting Properties in the Win32_ComputerSystem Class

The Win32_ComputerSystem class represents computer systems operating in the Microsoft 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:

  • SystemVariable
  • UserName
  • Name
  • VariableValue

The SystemVariable property is a Boolean value that indicates whether or not the environment variable identified by the Name property is a system variable environment. SystemVariable is set to TRUE if the variable is a system environment variable; otherwise, it is FALSE. When SystemVariable is set to TRUE, the UserName property must be set to <SYSTEM>.

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 Microsoft 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 Microsoft 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 Microsoft 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_PageFile Class

The Win32_PageFile class represents data files that describe the paging characteristics of a Windows NT/Windows 2000 system. Each instance of the Win32_PageFile class represents a different page file. The Win32_PageFile 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's 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 Microsoft® 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.


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®/Windows® 2000 file system (NTFS) files, directories, and shares.

This section contains the following topics:

  • About the Security Provider

    This topic presents an overview of the security provider, describes the security descriptors, and lists the classes supported by the security provider.

  • Using the Security Provider

    This topic shows you how to register the security provider and it gives examples that show how to get and set security descriptors.


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.

  • Mailslots and named pipes
  • Local or remote printers
  • Local or remote Microsoft® Win32® services
  • Registry keys
  • Semaphores, events, mutexes, and waitable timers
  • Processes, threads, 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 method 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. The security descriptor contains information about the owner of the object's primary group, and the contents of the security descriptor itself. The security descriptor also contains two lists, which are called access control lists (ACL): a discretionary ACL (DACL) and a system ACL (SACL).

The DACL specifies the rights that specific users and groups have to a securable object. The SACL specifies what type of access should be audited by the system for the users and groups the list contains.

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 an AceType property, an AceFlags property and an AccessMask property. The AceType property indicates to which of the two types of ACE (ACCESS_ALLOWED_ACE, or ACCES_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, etc.) 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 it a SACL is not present at all, there will not be an audit of access to the object.


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 an Windows NT/Windows 2000 system, you must specify an impersonation level of Delegate to retrieve or set some properties. On 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. Furthermore, even if the client has administrator privileges, no SACL information will be returned if the client, or group the client is a member of) AccessMask does not indicate that he can access the SACL. If this were not true, the security provider would compromise Windows NT/Windows 2000 security.


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 contains the following classes.

Class | Description
Win32_AccountSID | Represents an account's security identifier (SID).
Win32_SecuritySettingOfLogicalFile | An association between a CIM_LogicalFile instance and a Win32_LogicalFileSecuritySetting instance.
Win32_LogicalFileSecuritySetting | Represents security settings for a logical file.
Win32_SID | Represents an arbitrary SID.
Win32_LogicalFileAccess | Represents an association between a Win32_LogicalFileSecuritySetting and a Win32_SID. Instances of the Win32_LogicalFileAccess class represent the ACEs contained within the file's DACL.
Win32_LogicalFileAuditing | Represents an association between a Win32_LogicalFileSecuritySetting and a Win32_SID. Instances of the Win32_LogicalFileAuditing class represent ACEs contained within the file's SACL.
Win32_LogicalFileGroup | Represents an association between a Win32_LogicalFileSecuritySetting and a Win32_SID. The Win32_LogicalFileGroup class represents the primary group of the logical file.
Win32_LogicalFileOwner | Represents an association between a Win32_LogicalFileSecuritySetting and a Win32_SID. The Win32_LogicalFileOwner class represents the owner of the logical file.

A subset of these classes are listed below in two groups. The first group shows classes that represent a security descriptor or parts of the security descriptor. The second group shows classes that can be used to retrieve the security descriptors associated with securable objects such as NTFS files, directories, and shares.

Security Descriptor Components

Win32_SecurityDescriptor

Win32_Trustee

Win32_ACE

Classes used to manage security descriptors

Win32_LogicalFileSecuritySetting

Win32_LogicalShareSecuritySetting


Win32_SecurityDescriptor

[This is preliminary documentation and subject to change.]

This class represents the security descriptor for a securable object. The parts of this class are:

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 | An 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 | An 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 | A 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.

See Security Descriptor Objects for an example of a security decriptor for a file.


Win32_Trustee

[This is preliminary documentation and subject to change.]

The Win32_Trustee class represents a trustee.

Property | Type | Description
Name | String | Specifies a trustee. This can be a user account, group account, or logon session.
Sid | Array of Unit8 | This is an array of integers that uniquely identifies a user or group.
SidLength | Variant | This is a variant containing the number of bytes in the SID. This property is not populated by the security provider.


Win32_ACE

[This is preliminary documentation and subject to change.]

The Win32_ACE class represents a access control entry.

Property | Type | Description
Trustee | Win32_Trustee | Specifies a user account, group account, or logon session to which an ACE applies.
AceType | Unit32 | Specifies what 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 | Specifies access permissions granted or denied for this object.
GuidObjectType | String | Specifies what type of object to which the ACE applies (Windows 2000 only).
GuidInheritedObjectType | String | Specifies what type of child objects can inherit the ACE (Windows 2000 only).


Win32_LogicalFileSecuritySetting

[This is preliminary documentation and subject to change.]

This class is associated with the CIM_Datafile and CIM_Directory classes using their path properties. This class supports two methods.

Method | Description
GetSecurityDescriptor (Descriptor) | This gets the properties and embedded objects of a descriptor object that you provide as a input parameter to this method. 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 sets the properties and embedded properties for a file based on the descriptor object that you provide as a output parameter.


Win32_LogicalShareSecuritySetting

[This is preliminary documentation and subject to change.]

This class is associated with CIM_LogicalShare class with the path property. This class supports two methods.

Method | Description
GetSecurityDescriptor (Descriptor) | This 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 sets the properties and embedded properties for an object based on the descriptor object that you provide as a output parameter.


Security Descriptor Objects

[This is preliminary documentation and subject to change.]

Security descriptor objects are represented by instances of the class Win32SecurityDescriptor and contain embedded objects from the Win32_Trustee and Win32_ACE classes. The following example shows the security descriptor for a file and how the classes are associated.


The 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 the 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 the 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 that you want to grant. The actual value of AccessMask depends on the type of object the mask refers to.


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 SDK installation:

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 Visual Basic script example retrieves the security descriptor for a file and stores it in the object objDescriptor.

Set objdescriptor = GetObject("winmgmts:{impersonationLevel=impersonate}!root/cimv2:Win32_LogicalFileSecuritySetting='D:\\test\\test.txt'")
retval = instance.GetSecurityDescriptor(objDescriptor)


Setting Security Descriptors

[This is preliminary documentation and subject to change.]

To change the security descriptor for a file, directory, or network share, you will 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. Once you have the descriptor object you can modify its properties 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 loose 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 controlflags. Then the AccessMask for the trustee "Everyone" is set to full access.

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 = "\\a-rburns2\root/cimv2:"
Const objectpath = _
       "Win32_LogicalFileSecuritySetting=""D:\\test\\test.txt"""
    strMoniker = "winmgmts:" & ImpLevel & namespace & objectpath

    Set instance = GetObject(strMoniker)
  ' 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 ("The trustee ""Everyone"" was not found")
    End If
End Sub


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).

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


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. See SNMP Information Module Compiler for more information.

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 up the SNMP providers 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 WBEM 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 | Create an instance of
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. See RFC MIB Files in the WMI SDK for more information.

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\rfcs 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 currently provides access to the Microsoft® Windows® 2000 Active Directory only. The DS Provider will eventually provide access to all ADSI compliant directories (for example, Microsoft® Windows NT® version 4.0, Microsoft® Exchange, Netscape and Netware Directory Service) on a computer network. 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


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
  • 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.


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).

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[];
    uint32 numberOfValues;
};

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
};


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}";
    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++

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 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 WBEM 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.

    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.

  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.

In the following example, the class DS_user was clicked.


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 WBEM 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 three system classes and four classes specific to the DS Provider.

You will normally have no need for the information contained in the three system classes. The classes specific to the DS Provider (DS_LDAP_Class_Containment, DS_LDAP_Instnace_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);

                /************************************************************
                * CLASS ASSOCIATIONS - USING THE DS CLASS ASSOCIATIONS PROVIDER.
                ************************************************************/

                /************************************************************
                * INSTANCE ASSOCIATIONS - USING THE DS INSTANCE ASSOCIATIONS PROVIDER.
                ************************************************************/

                t_pNamespace->Release();
            }
            SysFreeString(strNamespace);
            t_pLocator->Release();
        }
    }
}


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

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 program. This file must be registered with Microsoft® Windows® 98 or Microsoft® Windows®2000 before you can use the DS Provider. If you are running either Windows 98 or 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 or Windows 98

  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 either Windows 2000 or Windows 98

  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:

  • How the Active Directory is Mapped to WMI
  • DS Provider Classes


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,
    provider("Microsoft|DSLDAPClassAssociationProvider|V1.0")
]

class DS_LDAP_Class_Containment
{
    [KEY] object ref ChildClass; // The child DS Class
    [KEY] 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 instnace are specified: A query of the form:
    "select * form DS_LDAP_Instance_Containment where ChildInstance=<InstancePath> and ParentInstance=<InstancePath>"


Example VB Scripts

[This is preliminary documentation and subject to change.]

This section contains information on:

  • Generating a User Path Listing with VBScript
  • Generate 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 sections:

  • About the View Provider

    This section gives an overview of the View Provider and a discussion about views.

  • Using the View Provider

    This section 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.]

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 two types of view classes are:

  • Join view classes

    Instances of different classes connected by a common property value.

  • Union view classes

    Union of source class instances.


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. 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.


Union View Classes

[This is preliminary documentation and subject to change.]

Union view classes are created from the logical union of source class instances. They include all the instances of the source classes. 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. The properties of union class Instances have a value of NULL if the source class instance does not have the same property. For example, suppose you are joining 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.


View Class Definition

[This is preliminary documentation and subject to change.]

View class definitions begin with either the JoinOn string qualifier or the Union Boolean qualifier to indicate which type of view class is being defined. The Union qualifier and the JoinOn qualifier are mutually exclusive. If you specify the Union qualifier with a value of TRUE you cannot assign a string value for the JoinOn qualifier. Conversely, if you specify a value for the JoinOn qualifier, you cannot assign the value TRUE to the Union 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 instance properties you want to use and where the 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 PropertySource qualifier to indicate the source class 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 seven qualifiers you can use to define View Provider classes.

Qualifier Name | 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.
ViewSpaces qualifier | Defines the namespaces where the source instances are located.
PropertySource 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.


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 up to 255 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.


PropertySource Qualifier

[This is preliminary documentation and subject to change.]

Every property in a view class must have a string array qualifier called PropertySource. The PropertySource 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 union class called based on instances of Win32_LogicalDisk.

PostJoinFilter("SELECT * FROM UnionDrive WHERE FreeSpace > 1000000 and Description = \"3 1/2 Inch Floppy Drive\"")


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 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.


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 all the computers involved are running Windows® 2000.

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. 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;
. . .


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 SDK that 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 SDK installation:

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, Win32Perf_RawProcess and Win32Perf_RawThread. The following MOF code creates a join class with some of the properties of both classes joined by the ProcessID property:

#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"};
};

[JoinOn("Win32Perf_RawProcess.IDProcess = Win32Perf_RawThread.IDProcess"),
ViewSources{"Select Name, IDProcess, PriorityBase  From Win32Perf_RawProcess" , "Select Name,IDProcess, ThreadState, PriorityCurrent From Win32Perf_RawThread"},
ViewSpaces{"\\\\.\\root\\Default", "\\\\.\\root\\Default"},
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;
};


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;
};


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 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.


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.


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.

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 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:

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.

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.

The description field is optional and can be used to specify information about the class. There is no default value for the description field.

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 checkbox 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.

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.

Like the class description, the provider description is optional and can be left blank.

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.

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's 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 free-threaded 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 must implement 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, the .h and the .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 define USE_POLARITY:
    #define USE_POLARITY
  • You must link with msvcrt.lib. 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 framdyd.lib in a relase build or framedyn.lib in a debug build.

Failure to predefine USE_POLARITY and link with msvcrt.lib and framedyn.lib or 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. Predefine the symbol USE_POLARITY and 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 need the debug version of Framedyn.dll to debug a framework provider. 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. Linking with the debug version of Framedyd.lib is also necessary for debugging a framework provider.


Provider Framework Reference

To implement a framework provider, you can use the provider framework classes.


Security and Authentication

Windows Management Instrumentation (WMI) supports a limited form of security for the Microsoft® Windows® 95/98 and Microsoft® Windows NT®/Windows® 2000 platforms. 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 the current release, WMI does not provide security for system resources such as individual classes, instances, and namespaces. However, administrators can use WMI to control global permissions on schema operations, such as limiting the access of some users to read-only operations.

All security-related information is represented by instances of WMI system classes located in the Root\Security namespace. These classes and instances can only appear in the Root\Security namespace and must remain there permanently. By default, the namespace Root\Security is accessible to administrators only.

You can use the WBEM Permissions Editor application (Wbemperm.exe) to set permissions for WMI users. It is similar to the Local Users and Groups snap-in supplied with Windows 2000.

WMI performs security checks only when a user logs on to the service. Therefore, during the time the user is connected to the Windows Management Service, changes made to a user's access rights through the WBEM Permissions Editor do not take effect until after the user has disconnected and reconnected. This includes situations where a user's access is revoked. For the duration of the session during which the access change occurs, the user continues to have his or her original access permissions.

In WMI, all security accounts are referred to as subjects. There are two types of subjects: user and group. Users are represented by instances of the __NTLMUser system class, which describes individual users. Groups are represented by instances of the __NTLMGroup system class, which describes multiple users. The __NTLMUser class derives from the __User class, a subclass of the __Subject system class. The __NTLMGroup classes derives directly from __Subject.

Members of the local Users group have read-only access to all namespaces except Root\Security by default.

On Microsoft® Windows® 95/98 platforms, all local access is unauthenticated and unsecured. This is because the operating system is not secured. Remote access control depends on how the system is set up. Windows 95/98 systems have two types of network access control:

  • User level
  • Share level

User-level security requires that a domain be specified; once it is, it can be used to identify users. When you set up a Windows 95/98 system to use user-level security, remote access for the system is very similar to remote access for Windows NT/Windows 2000 systems. The Windows Management Service can be configured to differentiate between valid and invalid users, and to assign valid users specific permissions.

Share-level security does not require a domain and is typical in simple workgroup settings. With share-level security, the Windows Management Service can provide access to remote clients but the access is unauthenticated and unsecured. By default, remote access to the Windows Management Service on Windows 95/98 systems is not enabled. The following registry value can be set to "1" to enable it:

HKLM\SOFTWARE\Microsoft\WMI\WinMgmt\
 EnableAnonConnections

To check or change a Windows 95/98 system's network access control, double-click the Network icon in Control Panel, click the Access Control tab, and check or change settings on the tab.

For more information about starting the Windows Management Service on Windows NT/Windows 2000 and Windows 95/98 systems, see WMI Command-Line Syntax.

Applications can specify security settings at the process level and at the interface level. For more information, see Setting Process Level Security and Setting Interface Level Security.


Security Classes

Windows Management Instrumentation (WMI) defines the following system classes for describing data that is related to security:

  • The abstract base class __SecurityRelatedClass
  • The abstract base class __Subject
  • The __User class
  • The __NTLMUser class
  • The __Group class
  • The __NTLMGroup class

All of these classes belong to the Root\Security namespace. The __SecurityRelatedClass abstract class serves as the base class for all security classes. The __Subject class is the base class for all users, represented by the __NTLMUser class, and all groups, represented by the __NTLMGroup class.

You must create an instance of a subclass of the __NTLMUser or __NTLMGroup class for every user or group to be validated by WMI. The __User class is an intermediate abstract base class. It is only used as a derivation point.

In practice, an instance of the __NTLMUser class is created to permit a user to access WMI. The __NTLMUser class specifies the user's Microsoft® Windows NT®/Windows® 2000 LAN Manager domain name. Because __NTLMUser derives from the __Subject class, all of the __Subject properties must also be set correctly before the user can be granted access to WMI. Instances of this class have no effect when a local user logs on to a Microsoft® Windows® 95/98 system. On Windows 95/98 systems, WMI uses instances of this class only to authenticate remote connections. On Windows NT/Windows 2000 systems, WMI uses instances of this class to validate both local and remote users.

To permit a group to access WMI, you create an instance of the __NTLMGroup class. Any user belonging to a group inherits the permissions assigned to the group. The group's properties include the type of group (that is, local or global) and, for a global group, the name of the domain. The __NTLMGroup class is used on Windows NT/Windows 2000 platforms only. Instances of this class do not affect the logon process for Windows 95/98 systems.

The Permissions property of the __Subject class and its subclasses, __NTLMGroup and __NTLMUser, control the level of access that is given to an authenticated user. If this property is set to 0, then read-only access is permitted. If it is set to 1, the user may read, create, update, and delete instances of classes, but the user cannot perform operations on the classes themselves. Finally, if the value is set to 2, then full read/write access is granted.


NTLM Group Support on Windows NT/Windows 2000

Windows Management Instrumentation (WMI) supports several features that enable native Microsoft® Windows NT®/Windows® 2000 security to be transparently integrated with WMI security. A Windows NT/Windows 2000 NTLM user inherits all of the permissions assigned to all of the groups of which he or she is a member.

You need not associate an instance of the __NTLMUser class with a user. He or she only has to be a member of one of the groups already in the security access database of Windows NT/Windows 2000. By using this mechanism, the Windows 2000 Local Users and Groups snap-in can become the tool for controlling group membership, thereby simplifying WMI administration.

In most cases, you create instances of the __NTLMGroup class using the WBEM Permissions Editor.

On some Windows NT Workstation and Windows 2000 Professional computers, the operating system automatically adds the Administrators group domain to the local Administrators group when the computer joins the domain. Windows Management Service does not control this process. Instead, the administrator specifies this through the Windows 2000 Local Users and Groups snap-in.

You can control most access to WMI from the Windows 2000 Local Users and Groups snap-in immediately after service installation. At this time, the following permissions are in effect:

  • All local administrators have full access to WMI, including full access to all namespaces at all times.
  • Domain administrators have full access to WMI unless the user has removed them from his or her local Administrators group.

The following groups have read-only access to all namespaces except Root\Security :

  • The local Users group on Windows 2000 systems.
  • The users group on Windows NT 4.0 systems.

File and registry permissions pertain only to Windows NT/Windows 2000 systems and NTFS volumes, not to Windows 95/98 systems. Windows NT/Windows 2000 sets registry permissions automatically when WMI is installed. The WMI registry tree assigns read/write permissions for the registry to members of the Administrators group and read-only permissions for the registry to everyone else.


Authentication

Authentication is the process of ensuring that only valid users are allowed access to managed objects through Windows Management Instrumentation (WMI). Valid users include individual users as well as group users.

There are two parts to authentication:

  • User identification
  • Permission assignment

User identification involves verifying the user name and password. Verification is the responsibility of marshalers such as Distributed Component Object Model (DCOM), Component Object Model (COM), or anonymous pipe marshalers. Marshalers 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 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 by marshalers. 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. Permissions on Windows 95/98 systems govern whether certain users should do particular operations. However, on Windows 95/98 systems no mechanism exists to prevent a determined user from forcing an operation to occur.


Default Access and Permissions

On Microsoft® Windows NT®/Windows® 2000 platforms, there is no distinction between local and remote access. The current user is assumed 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 and password in the call to the IWbemLocator::ConnectServer method because the Distributed Component Object Model (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.

On Microsoft® Windows® 95/98 platforms, local users are considered administrators and given full rights. The operating system performs no authentication. However, the system always validates remote users using instances of the __NTLMUser class in the Root\Security namespace. Because there is no default remote access on Windows 95/98 platforms, you must create one or more __NTLMUser instances to enable remote access.

Note that group-based authentication using the __NTLMGroup class is not available on Windows 95/98 platforms, but only on Windows NT/Windows 2000.

File and registry permissions pertain only to Windows NT/Windows 2000 systems and NTFS volumes, not to Windows 95/98 systems. Windows NT/Windows 2000 sets registry permissions automatically when WMI is installed. The WMI registry tree assigns read/write permissions for the registry to members of the Administrators group and read-only permissions for the registry to everyone else.


Logon Scenarios

On Microsoft® Windows NT®/Windows® 2000 platforms, all user names and passwords are checked for group membership or a corresponding __NTLMUser class membership. If the user specifies no user name and password, the operating system checks logon credentials. The system denies access if all of the following conditions are true:

  • The user is not a member of the Administrators group.
  • The user is not a member of the local Users group.
  • The user is not a member of any group that is an instance of the __NTLMGroup class.
  • The user is not represented by an __NTLMUser instance.

Any remote connection to a Microsoft® Windows® 95/98 platform succeeds if the domain controller authenticates the user's credentials and a corresponding __NTLMUser instance exists.

Any local connection to a Windows 95/98 platform succeeds whether or not a user name and password are specified.

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, the Distributed Component Object Model (DCOM) starts the Windows Management Service on the remote system and the user can log on, if all other logon credentials are accepted.


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:

  • Applications Guide
  • ActiveX Controls
  • Managed Object Format (MOF) Language
  • WMI Query Language
  • WBEMTest

For specific background information on WMI, see WMI for Application Developers, WMI for Provider Developers and WMI for Network Administrators and System Managers. For all WMI reference material, see WMI Reference.


Applications Guide

The Windows Management Instrumentation (WMI) SDK includes the following Web-Based Enterprise Management (WBEM) applications:

  • WBEM Object Browser

    The WBEM 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.

  • WBEM CIM Studio

    The WBEM 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.

  • WBEM Event Registration Tool

    The WBEM 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.

  • WBEM Event Viewer

    The WBEM Event Viewer displays events for all instances of registered consumers. You can also start the WBEM Event Registration Tool from the WBEM Event Viewer.

This document provides a brief description of these applications and how to use them.


System Requirements for the WBEM Applications

To use WBEM applications, your system must include the following hardware and software:

  • Microsoft® Windows NT® version 4.0, SP4 or later.
  • Internet Explorer version 4.01 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.


WBEM Logon Dialog Box

When you start any WBEM 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 type the path name or click Browse for Namespace.

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 WBEM applications (when you connect to a namespace on a remote computer, for example). This dialog box is the same for all WBEM applications, except that the name of the application that you are logging on to is displayed as the title of the dialog box. When you logon to the default namespace, the dialog box looks like this.

Note that Login as current user is selected, and Username and Password are disabled. This is because there is no need to enter another username and password when you log on to the default namespace. When you log on to a remote namespace, the WBEM CIM Studio logon dialog box looks like this.

Username and Password are enabled. 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.

By default, all members of the local Users group on Microsoft® Windows NT®/Microsoft® Windows® 2000 systems have read-only access to all namespaces except Root\Security. To change the default access permissions, use the WMI Permission Editor (Wbemperm.exe).

To change either the impersonation level or the authentication level, click Options and expand the logon dialog box. You can select new impersonation and authentication levels from the associated drop-down selection lists.

To complete a WBEM logon dialog box

If you are logging in as the current user on the local computer, click OK. If you are logging in on a remote computer, click to clear Current User and enter your information in Username and Password. The user name can be in the form domain\user. Click OK.


WBEM Object Browser

The WBEM 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 the WBEM Object Browser

WBEM Object Browser User Interface

WBEM Object Browser Functions


Starting the WBEM Object Browser

To start the WBEM Object Browser

  1. Click Start, point to Programs, and then click WMI SDK.
  2. Click WBEM Object Browser. The Connect to Namespace dialog box appears:

    The default namespace is Root\CIMV2. You can choose another namespace by typing its name, clicking the down arrow to select a namespace from the history list, or clicking Browse for Namespace.

  3. Click OK. The WBEM Login dialog box appears.

    See WBEM Logon Dialog Box for instructions.

    After logging in, if you have previously accessed the selected namespace in the WBEM 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. The Select Initial Tree Root dialog box automatically appears after you have logged in.

    Initially, this dialog box lists the classes in the current namespace that can have instances.

  4. Select Show all classes to see all classes in the current namespace. Classes that cannot have instances (abstract classes) appear in bold type.
  5. Select Associations to display association classes.

    Use this dialog box to browse classes and their instances and then choose an instance as the root of the object tree. For each class you want to browse, select the class name in the Available Classes list and then click Add. Each class selected appears in Browse for objects in. (For quicker selection, you can start typing the class name in the field under Available Classes 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, then clicking Remove.

  6. When you are done selecting classes, click OK.

    The dialog box then shows all instances of the selected classes. For example:

  7. Click the instance you want to be the root and then click OK.

    The object tree appears in the WBEM Object Browser with the selected instance as the root. Note that the WBEM 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.


WBEM Object Browser User Interface

The WBEM 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 WBEM Object Browser screen is shown below.


Object Explorer

The left frame in the WBEM 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 by re-rooting the tree or permanently (through schema) so that the selected root persists among WBEM 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.

Clicking the plus (+) and minus (-) boxes expands and contracts the tree display. The tree shows regular objects and grouping nodes. Grouping nodes are not objects themselves but are a way to organize objects. The icons next to the names indicate the type of object or node.

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 icons 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.

Browse for Namespace allows you to browse and select namespaces on the local computer or a remote computer. See Browsing for a Namespace for information.
Browse for Instance allows you to browse classes for a specific instance and reroot the Object Explorer tree from that instance. See Using Browse for Instance to Reroot the Object Tree for information.


Object Viewer

The right frame in the WBEM 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 WBEM 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 icon to identify association objects ( [image]) on the Associations page.

The Object Viewer includes the following buttons.

Back/Forward displays previously-viewed pages.
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.


WBEM Object Browser Functions

Using the WBEM 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, the WBEM 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 the WBEM 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 the WBEM 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


Selecting the Namespace from the History List

The Objects in box keeps a list of previously selected namespaces. Click the down arrow to select a namespace from this history list.


Browsing for a Namespace

To browse for a namespace

  1. Click Browse for Namespace.

    The Browse for Namespace dialog box appears.

  2. By default, Machine Nameshows the local computer. To select a namespace on another computer, type 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 WBEM Login dialog box appears. See WBEM Logon Dialog Box for instructions. 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 Browse for Namespace dialog box, click the plus sign (+) next to the root namespace to display the namespaces on the selected computer.
  4. Click the namespace you want to use and then click OK.

    This returns you to the WBEM 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. Then, select Go to Namespace. The object tree for the namespace appears rooted at the selected object.


Rerooting an Object Tree

In the WBEM 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 WBEM 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 WBEM 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

Use this procedure to change the default object tree root for a namespace.

To change the initial tree root

Right-click the object you want to be the initial root. Select 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 you want to be the new root. Then, select Make Root from the menu that appears.

Because only regular objects can be made the root of the tree, the Make Root option 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 you want to be the new root of the object tree.

To browse for an instance

  1. In the Object Explorer, click Browse for Instance. The Browse for Instance dialog box appears.

    The Browse for Instance dialog box shows a list of classes in the current namespace. By default, this dialog box shows the list of classes that can have instances.

  2. Select Show all classes to see all classes in the current namespace.

    Classes that cannot have instances (abstract classes) appear in bold type.

  3. Select Associations to display association classes.
  4. For each class you want to browse, select the class name in the Available Classes list and then click Add.

    Each class selected appears in Browse for objects in. (For quicker selection, you can start typing the class name in the field under Available Classes 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. The Browse for Instance results dialog box appears. This dialog box shows all objects in the selected classes.

  6. Click the object you want to be the root of the object tree and then click OK to return to the WBEM 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

First, select the object in the Object Explorer. Then, click the Properties tab in the Object Viewer.

The Properties page displays the properties for a selected regular object. Icons in the Properties page provide the following information about the object's class.

Icon | 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. For more information, see the WMI System Properties. Non-system properties are either defined by the user or inherited from parent classes.
 | 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. Select the object you want to view and click the Properties tab.
  2. Click Views and then select Property Filters.
  3. Select or clear the filters for the view you want:
    • Show system properties
    • Show inherited properties

    Clearing these filters hides the properties in the Properties page display.

  4. Click OK.


Displaying Custom Views of Object Data

The example screen shown in the topic Displaying Properties of Regular Objects 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 enabled.

To display a custom view

Click the Views button and then select Views from the menu that appears. The Views window appears with a list of available views. Finally, select the view you want from the list and then click OK.

To return to the generic view, click Views, choose the Views menu option, 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 page for the object you want to change.

    For instructions, see Displaying Properties of Regular Objects or Displaying Properties of Association Objects.

  2. Click the property value you want to change.
  3. If a down arrow appears when you select the value, click the arrow and then choose a value from the list that appears.

    If no down arrow appears, type the new value in the field. When you start typing, the text turns blue. The Save button becomes active; 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 page.

    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 page. Click OK to return to the Object Viewer.

    • Right-click Object button and select Set to <empty>.
    • Right-click the <empty> value and select Create Value.

      This opens the Embedded Object dialog box. Enter the name of the class to which the object belongs. The Properties page for that class appears. You can edit properties and qualifiers the same way as on the Object Viewer Properties page. 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 select Go to Object or double-click the row corresponding to the instance you want to view. This displays the object Properties page. 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 the object in the Object Explorer and then click the Methods tab in the Object Viewer.

The Methods page shows all methods that can be applied to the selected object. You can display and execute object methods in the WBEM Object Browser, but you can only edit methods information in WBEM CIM Studio.

To view the parameters defined for a method, right-click on the method row and select Execute Methods. To view qualifiers for the method, right-click and select Method Qualifiers.

The following example screen shows the Methods page for the Win32_OperatingSystem object.


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 option is disabled.

To execute a method

  1. Display the Methods tab for the object you want to work with.

    For more information, see Displaying Object Methods.

  2. Right-click the method and select Execute Method from the context menu.

    The Method Parameters window, which shows the parameters used when executing the selected method, becomes visible.

    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 icon in the first column.
    Icon 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 the object in the Object Explorer and then click the Associations tab in the Object Viewer.
  2. The Associations page 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 page:

  • The left-most object icon always represents the current object, EDKDOCS1, as it appears in the preceding screen shot.
  • Each branch from the current object represents an association of that object to another object.
  • The icon in the middle ( [image]) represents the association object.
  • The right-most object icons represent the objects associated with the current object.

On the Associations page, you can also do the following:

  • Hover over the association object icon to display the association type.
  • Hover over the connecting lines on each side of the association object icon to display the roles of the related objects.
  • Jump to another regular object by double-clicking its icon.

    For example, double-clicking the icon next to Win32Service.Name="Messenger" in the preceding screen sample changes the display.

    Selecting another object on the Associations page updates all displays in the Object Viewer. In this example, the Properties and Methods pages now display information about the Messenger object.

  • Jump to an association object by double-clicking its icon.

    In the preceding screen shot, the association object next to Win32Service.Name="LanmanWorkstation" is of the type Win32ServiceToService. Selecting this icon changes the display.

    This also updates the Properties and Methods pages to show information for the newly-selected association object.

  • Jump to the Properties page of an object by right-clicking the object's icon or name. Select Properties from the menu that appears.
  • Reroot the Associations graph by right-clicking an object icon and selecting Make Root from the menu that appears.
  • 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 page, double-click the icon for the association object you want 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 from the menu that appears. 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. Select the object in the Object Explorer and click the Properties tab in the Object Viewer.
  2. Right-click the Properties page of the Object Viewer.
  3. Select Object qualifiers from the menu that appears.

    The Qualifiers window appears.


Displaying Property Qualifiers

Property qualifiers can only be displayed for non-system properties.

To display property qualifiers

  1. Select the 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 from the menu that appears.

    In either case, the Qualifiers window appears. If the object has no property qualifiers, the window is blank.

  3. To close the Qualifiers window, click OK or Cancel.

The following screen shows the qualifiers for the BootDevice property of the Win32_OperatingSystem object.


Editing Object and Property Qualifiers

To edit object and property qualifiers

  1. Select the object in the Object Explorer.
  2. Display the Qualifiers (object or property) window you want to edit.
  3. Click the field you want to change.
  4. If a down arrow appears when you select the field, click the arrow and choose a value from the list that appears.

    If no down arrow appears, type 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 active to indicate that the value has not been committed yet.

  6. When you finish editing, click OK.

    This closes the Qualifiers window.

  7. In the Object Viewer, click Save. When a confirmation message appears, click Yes to save the changes.


WBEM CIM Studio

The WBEM 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 informatio.
  • Run selected operations.

WBEM CIM Studio also provides wizards for generating and compiling .mof files and for generating framework provider code. For more information about the WBEM CIM Studio, see the following topics:

Starting WBEM CIM Studio

WBEM CIM Studio User Interface

WBEM CIM Studio Functions


Starting WBEM CIM Studio

To start WBEM CIM Studio

  1. Click Start.
  2. Point to Programs and then click WMI SDK.
  3. Click WBEM CIM Studio.

    The Connect to namespace dialog box appears:

    The default namespace is Root\CIMV2. You can choose another namespace by typing its name, clicking the down arrow to select a namespace from the history list, or clicking Browse for Namespace.

  4. After selecting the namespace, click OK.

    The WMI Login dialog box appears. See WBEM Logon Dialog Box for instructions about how to use the dialog box.


WBEM CIM Studio User Interface

The WBEM 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 WBEM CIM Studio wizards generate and compile MOF files and generate framework provider C++ code.

The following screen shot shows what the WBEM CIM Studio interface looks like.


Class Explorer

The left frame in the WBEM CIM Studio is the Class Explorer. The Class Explorer shows the selected namespace (Root\CIMV2 in the sample screen in the preceding topic) and the schema defined for that namespace as a class inheritance tree. Clicking the plus (+) and minus (-) boxes expands and contracts the tree, respectively. The shaded icons next to the class names indicate the type of objects defined by the class.

Class that defines regular objects
Class that defines association objects

Use the check boxes to select or cancel the selection of classes for the wizard operations performed in the WBEM CIM Studio. You can also select or clear all check boxes by right-clicking anywhere in the Class Explorer and then choosing Select all or Unselect all from the menu that appears.

For non-wizard operations, select classes by clicking the class name in the Class Explorer.

The Class Explorer includes the following buttons.

Browse for Namespace allows you to browse and select namespaces on the local computer or a remote computer. See Browsing for a Namespacefor more details.
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 for more details.
Delete class button deletes a selected class from the current repository. See Deleting Class Definitions for more details.


Class Viewer

The right frame in the WBEM 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.

Create instance creates a new instance of a selected class. See Adding Instances of a Class for more details.
Delete instance button 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 button displays filtered or custom views of class instance data. See Filtering Views of Class Properties and Creating and Using Custom Views of Instances.
Help for Class displays help information on the selected class or the class of the selected instance.
Help opens the WMI online documentation.


Wizards

The three icons above the Class Viewer invoke the following wizards:

Provider Code Generator Wizard generates framework provider C++ code for a selected class. See Provider Code Generator Wizard.
MOF Generator Wizard inserts selected class definitions and/or instances from the repository into a text file in the MOF syntax. See MOF Generator Wizard.
MOF Compiler Wizard imports class definitions or instances described in a MOF file into the current repository. See MOF Compiler Wizard.

When selected, each wizard opens a series of screens that guide you through the operation.


WBEM CIM Studio Functions

Using the WBEM 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.
  • Run the Provider Code Generator Wizard, MOF file generator, and MOF file compiler on selected classes and/or instances.

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, the WBEM 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 down 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

In the Class Explorer, click Search for Class. The Search for Class dialog box appears. Then, enter the name of the class you want to find and click OK. If found, the class is selected in the Class Explorer and its details appear in the Class Viewer.


Displaying the Definition of an Existing Class

Within WBEM 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.

Icons in the Properties page provide the following information about the class.

Icon | 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. See the WMI System Properties. Non-system properties are either defined by the user or inherited from parent classes.
 | Indicates a local property.
 | Indicates an inherited property.
 | The pen symbol on an icon 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 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 you want to view and click the Properties tab.
  2. Click Views and select Property Filters.
  3. Select or clear the filters for the view you want:
    • Show system properties
    • Show inherited properties

    Clearing these filters hides the properties in the Properties page 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 page shows all methods that can be applied to the selected class. For more information, see Executing Methods.


Displaying Class Qualifiers

To display class qualifiers

  1. Select the class in the Class Explorer and click the Properties tab in the Class Viewer.
  2. Right-click the Properties page in the Class Viewer.
  3. Select Object qualifiers from the menu that appears.

    The Qualifiers window appears.


Displaying Property Qualifiers in the Class Explorer

Property qualifiers can only be displayed for non-system properties.

To display property qualifiers

  1. Select the 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 from the menu that appears.

    In either case, the Qualifiers window appears. If the class has no property qualifiers, the window is blank.

  3. To close the Qualifiers window, click OK or Cancel.

The following screen shows the property qualifiers for the UntilTime property of the Win32_Printer class.


Displaying Method Qualifiers

To display method qualifiers

  1. Select the 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.

    The Qualifiers window appears.

  3. To close the Qualifiers window, click OK or Cancel.


Displaying Class Associations

To display class associations

  1. Select the class in the Class Explorer and then click the Associations tab in the Class Viewer.

The Class Associations page, 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 who's instances could be associated to instances of the Win32_MotherboardDevice class.

On the Class Associations page:

  • The left-most object icon 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 icon in the middle ( [image]) represents the association object class.
  • The right-most icons represent the classes associated with the current class.

On the Class Associations page, you can also do the following:

  • Hover over the association object icon to display the association type.
  • Hover over the connecting lines on each side of the association object icon to display the roles of the related classes.
  • Jump to another class by double-clicking its icon.

    For example, double-clicking the icon next to CIM_System in the preceding screen sample changes the display.

    Selecting another class on the Class Associations page updates all displays in the Class Viewer. In this example, the Properties and Methods pages now display information about the CIM_System class.

  • Jump to an association object by double-clicking its icon.

    In the preceding screen sample, the association object next to CIM_Setting is of the type CIM_ElementSetting. Selecting this icon changes the display and updates the Properties and Methods pages to show information for the newly-selected association object.

  • Jump to the Properties page of an object by right-clicking the object's icon.
  2. Select Properties from the menu that appears.


Displaying Instances of an Existing Class

Within WBEM 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.
  2. Click the Instances button in the Class Viewer. The instance table for the selected class appears. If there are no instances of the class, the table displays the message, "No Instances Available."

    From the instance table, you can also display the details for any individual instance.

  3. Right-click the instance, and then select Go to Object.

    This displays the object's Properties page. Clicking the Instance button toggles the display between the instance table and the Properties page 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 an 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 from the menu that appears.
  4. Choose the view you want from the list that appears and then 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 in the Class Viewer.

    The instance table for the selected class appears. If there are no instances of the class, the table displays the message, "No Instances Available." From the instance table, you can also display the details for any individual instance.

  3. Right-click the instance and then select Go to Object.

    This displays the object's Properties page. Clicking the Instance button toggles the display between the instance table and the Properties page for the selected object.

  4. Click the Associations tab in the Class Viewer.

    The Associations page 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 page:

  • The left-most object icon 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 icon in the middle ( [image]) represents the association object.
  • The right-most object icons represent the objects associated with the current object.

On the Associations page, you can also:

  • Hover over the association object icon to display the association type.
  • Hover over the connecting lines on each side of the association object icon to display the roles of the related objects.
  • Jump to another regular object by double-clicking its icon.

    For example, double-clicking the icon next to Win32Service.Name="Messenger" in the preceding screen sample changes the display.

    Selecting another object on the Associations page updates all displays in the Class Viewer. In this example, the Properties and Methods pages now display information about the Messenger object.

  • Jump to an association object by double-clicking its icon.

    In the preceding screen sample, the association object next to Win32Service.Name="LanmanWorkstation" is of the type Win32ServiceToService. Selecting this icon changes the display and updates the Properties and Methods pages to show information for the newly-selected association object.

  • Jump to the Properties page of an object by right-clicking the object's icon or name.

    Select Properties from the menu that appears.

  • Reroot the associations graph by right-clicking an object icon and selecting Make Root from the menu that appears.
  • 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 you want to derive a new class.
  2. Click the Add Class button.

    The Add Class dialog box appears.

  3. Type 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 page, 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 the Add Class button.

    The Add Class dialog box appears.

  2. Erase any Parent value in the Add Class dialog box (this box should be blank).
  3. Type 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.


Assigning Custom Icons to Classes

You can use the icon qualifier to assign a custom icon to a class. If you do not assign a custom icon and the class name corresponds to an icon resource in Wbemutils.dll, that icon is used. Otherwise, a default icon is assigned to the class.

To assign a custom icon to a class

  1. Use the procedure in Adding Class, Property, or Method Qualifiers to add the icon qualifier to your class.
  2. In the Value field of the icon qualifier, enter one of the following:
    <path>\<filename.ico>
    Where filename.ico is the name of an icon file that exists in the specified path; the standard search path is not supported in this form.
    —or—
    <path>\<res.dll>:<resname>
    Where res.dll is a .DLL that contains the resname icon resource. The standard search path is supported, making path optional if res.dll exists in the search path. The resname is the resource STRING, not the UINT defined in Resource.h or other resource header files. For example, if Resource.h contains the following statement, resname is the string "456", not "IDI_MYICON".
    #define IDI_MYICON   456

    If path\res.dll is omitted and resname is a WMI predefined icon, that icon is used. WMI predefined icon names correspond to the Win32_* class names defined in Cimwin32.mof, excluding the associations.


Deleting Class Definitions

To delete a class

In the Class Explorer, select the class you want to delete. Click the Delete Class button. When the Delete Class Query box appears, 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 WBEM 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 you want to change in the Class Explorer. Click the Properties tab in the Class Viewer.

    The class's properties appear in the Properties page.

  2. Click the blank Name field at the bottom of the properties table and type the new property name.
  3. Click the Type field. Click the down arrow and 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. If you want 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 box may appear from which you can choose the appropriate value.

  5. If the property type is an array, click the Array button in the Value field to open a dialog box in which you can enter each value in the array. When you are done entering values, click OK to return to the Properties page.
  6. To create an embedded object, do the following steps in order:
    • Select object as the property type.

      The Object Type dialog box appears.

    • Optionally, enter the name of the class to which the embedded object belongs and then click OK.
    • By default, the Value field is set to <empty> (which represents NULL). To change this value, right-click the field,and select Create Value from the menu.

      The Embedded Object dialog box appears. If you previously entered the name of the class to which the embedded object belongs, this dialog box opens the Properties page for that class. Otherwise, the display is blank.

    • Enter the name of the class to which the embedded object belongs in the Class field and press Enter to display the Properties page for that class.
    • Edit the properties and/or qualifiers for the embedded object, if necessary and then click OK to return to the Class Viewer.
  7. Click Save to save your changes.


Renaming Classes in WBEM CIM Studio

To rename a class

Select the class in the Class Explorer tree; then, select 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 the 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 you want to delete.

    This step selects the entire property entry.

  3. Press the Delete key.

    A confirmation message appears.

  4. Click OK to delete the property.

    This activates the Save button in the Class Viewer.

  5. Click the Save button to save your changes.


Editing Class Properties

To edit a property field

  1. Select the class in the Class Explorer and click the Properties tab in the Class Viewer.
  2. Click the field you want to change.
  3. If a down arrow appears when you select the field, click the arrow and choose a value from the list that appears.

    —or—

    If no down arrow appears, type 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 you want to change and then click OK to return to the Properties page.

    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 the Object button to open the Embedded Object dialog box.

      You can edit properties and qualifiers from this box in the same way as in the Class Viewer Properties page. Click OK to return to the Class Viewer.

    • Right-click the Object button 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 page for that class appears. You can edit properties and qualifiers the same way as in the Class Viewer Properties page. Click OK to return to the Class Viewer.

  5. When you have finished editing, click the Save button. 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 the class that you want to edit.

    The properties of that class appear.

  2. Add a property with a type of datetime.

  3. With the mouse on the property, right-click and select property qualifiers from the context menu.

    The property qualifiers dialog box appears.

  4. Enter a qualifier named "subtype" and set its value to "interval".
  5. Select OK.

    When you attempt to enter a value for the property, the interval editor will appear.

    The top field 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 page for the class you want to work with. See Displaying Class Methods.
  2. Type the method name in the Name field.
  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 select Edit Method Parameters.

    The Method Parameters window appears.

  5. 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 page.

    —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 page for the class you want to work with.

    See Displaying Class Methods.

  2. Click the gray box to the left of the method you want to delete.

    This selects the entire method entry.

  3. Press the Delete key.

    A confirmation message appears.

  4. Click OK to delete the method and then 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 page for the class or instance you want to edit.

    See Displaying Class Methods.

  2. Right-click the method you want to edit and select Edit Method Parameters.

    The Method Parameters window appears.

  3. Select and edit the fields you want to change.

    In some cases, selecting an item produces a drop-down list, from which you can select new values.

  4. Click OK to save the changes and return to the Methods page.

    —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 drop-down 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 box.

    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 field, if selected, specifies that this qualifier will be propagated automatically to all instances of this class. The Class field, if selected, specifies that this qualifier will be propagated automatically to all classes derived from this class. 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).

  6. Click the Value field and enter the desired value.

    When you select this field and begin typing, a list box 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 the Save button 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 you want to delete. This selects the entire qualifier entry.
  3. Press the Delete key. A confirmation message appears. Click OK to delete the qualifier.
  4. Click OK to close the Qualifiers window. This activates the Save button in the Class Viewer.
  5. In the Class Viewer, click the Save button 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 you want to change.

    If a down arrow appears when you select the field, click the arrow and choose a value from the list that appears. If no down 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 the Save button.

    A confirmation message appears.

  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 you want to create an instance.
  2. Click the Create instance button in the Class Viewer.

    The viewer displays data for the new instance, and the Save button becomes active.

  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 the Save button.

Note You cannot add instances of abstract classes. An abstract class is used only as a template for derived classes and cannot have instances.


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 you want to delete.

    This selects the entire instance entry.

  3. Click the Delete instance button in the Class Viewer.

    A confirmation message appears.

  4. Click OK to delete the instance.

    The instance is deleted from the table.


Executing Methods

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 you want to work with.
  2. 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:

    • Select the class in the Class Viewer and click Instances.
    • Right-click the instance you want to work with and select Go to Object.
    • Select the Methods tab.
  3. Right-click the method and select Execute Method from the context menu.

    Parameters column shows the parameters defined for this method and their default values.

  4. 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 icon in the first column.
    Icon Description
    Indicates an input property.
    Indicates an output property.
    Indicates an input/output property.

  5. Click Execute.

    When the method is done executing, you can see the resulting parameter values, including the return value.


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, click the check boxes to select the classes you want to insert in the MOF file.
  2. Double-click the MOF Generator Wizard icon.

    A welcome screen appears.

  3. Click Next.

    The following screen appears:

    This screen shows each class you selected in step 1.

  4. For each class, do the following steps in order:
    • Select the class name from the list under Classes to generate code for. The instances of that class, if any, appear in the right pane.
    • Select whether you want the class definition in the MOF file by clicking the check box next to Include class definition.
    • Click the check boxes to select the instances to be included in the MOF file. If you want all instances to be included, click Select All.
  5. Click Next.

    The following screen appears.

  6. Enter the MOF File Name and the directory where you want it to reside or use the Browse button to select a directory.
  7. If you want to generate a Unicode .mof file, select the UNICODE check box.
  8. Click Finish.

    A message box appears notifying you that the .mof file has been generated. Click OK to dismiss the message and close the wizard.


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

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 icon. When the welcome screen appears, select Compile a .MOF file.
  2. Click Next. The following screen appears.

  3. Type the path and file name for the .mof file you want to compile (or use the Browse button to select the file). Then, type 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.

    The following screen appears:

  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.

    A message box informs you of successful compilation.

  7. Click OK to dismiss the message.


Checking the Syntax of a MOF File

To check the syntax of a .mof file

  1. Double-click the MOF Compiler Wizard icon. When the welcome screen appears, select Check the syntax of a .MOF file.
  2. Click Next. When the following screen appears, type the path and file name for the MOF file you want to check or use the Browse button to select the file.

  3. Click Finish.

    The wizard checks the file's syntax and reports the results in a message box.

  4. Click OK to dismiss the message.


Creating a Binary MOF File

To create a binary .mof file

  1. Double-click the MOF Compiler Wizard icon. When the welcome screen appears, select Create a binary .MOF file.
  2. Click Next.

    The following screen appears:

  3. Type the path and file name for the .mof file you want to compile or use the Browse button to select the file.
  4. Type the name of the binary .mof file to be created.
  5. Type the directory where the binary .mof file should be created or use the Browse button to select a directory.
  6. If you want to perform WMI syntax checks, select this check box.
  7. Click Next. The following screen appears.

  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.

    A message box informs you of successful compilation.

  10. Click OK to dismiss the message.


WBEM Event Registration Tool

The WBEM Event Registration Tool is designed for developers and system managers. It provides a graphical interface for what may also be accomplished programmatically. The WBEM 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 WBEM 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.

See Also

Timer Events

Permanent Event Consumers


WBEM Event Registration Tool Interface

The left pane of the WBEM Event Registration Tool displays the consumer, filter, or timer inheritance tree. The right pane displays any bindings you have defined between consumers and filters. An example of a WBEM Event Registration Tool screen is shown below.

The left pane of the WBEM Event Registration Tool shows the inheritance tree of consumers, filters, or timers contained in the current namespace. By default, the local computer displays the Root\CIMV2 namespace. You can select a different local namespace or a namespace on a remote computer.

Clicking the plus (+) and minus (-) boxes expands and contracts the tree display. The tree shows system classes and instances of those classes.

The left pane of the WBEM Event Registration Tool includes the following buttons and icons:

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.
An icon that denotes a class.
An icon that denotes an instance.
Help button. Double-click this button to display Help.

The right pane of the WBEM 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 WBEM Event Registration Tool includes the following buttons:

Register registers the selected filter-consumer combination.
View Instance Properties allows you to view some properties of the selected instance.

In the columns of the right pane, 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.


WBEM Event Registration Tool Functions

This section describes the functions you can perform in the WBEM Event Registration Tool.

Note You must install Windows Management and create a repository of classes on the target computer before you can use the WBEM 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 WBEM Event Viewer consumer provider with the Event subsystem. This .mof file is compiled automatically when Windows Management is first started, so that the WBEM 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 WBEM Event Registration Tool

  1. Click Start.
  2. Point to Programs and then click WMI SDK.
  3. Click Event Registration.

    The WMI Login dialog box appears. See WBEM Logon Dialog Box for instructions in using this dialog box.

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 WBEM Event Registration Tool, click the class and then click View Class Properties.

—or—

In the left pane of the WBEM Event Registration Tool, right-click the class and then select View Class Properties from the pop-up menu.

The View Class Properties dialog box appears.

Creating an Event Consumer Instance

Creating an Event Filter Instance

Creating an Event Timer Instance

Registering a Consumer for an Event


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.

The following procedure describes how to create an event consumer instance.

To create an event consumer instance

  1. From the drop-down list box, choose 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 on the class you want to instantiate, and choose New Instance from the pop-up menu. The Edit new instance properties dialog box appears.

  5. In the Edit new instance properties dialog box, type strings in the Description and Name fields, and type a value in the Severity field.
  6. Click OK to create the instance.

The following procedure is an example, which defines an instance that, when used with the ServiceStoppedEvent filter, triggers an event notification and displays it in the WBEM Event Viewer when a system service is stopped.

To create the ServiceStopped event consumer instance

  1. From the drop-down list box, choose Consumers.
  2. Click EventViewerConsumer and then click New Instance.

    —or—

    Right-click EventViewerConsumer and click New Instance from the pop-up menu.

    The Edit new instance properties dialog box appears.

  3. In the Edit new instance properties dialog box, type the following information:
    • In the Description field, type Service was stopped.
    • In the MachineName field, type 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 field, type ServiceStopped.
    • In the Severity field, type 1.
  4. Click OK to create the instance.

The following procedure is an example, which defines a consumer that works with IntervalTimerFilter or AbsTimerFilter. This triggers an event notification and displays it in the WBEM Event Viewer at regular intervals or at a particular date and time.

To create the TimerEvent event consumer instance

  1. From the drop-down list box, choose Consumers.
  2. Click the EventViewerConsumer class, and click the New Instance button.

    —or—

    Right-click on the EventViewerConsumer class and then click New Instance from the pop-up menu.

    The Edit new instance properties dialog box appears.

  3. In the Edit new instance properties dialog box, type the following information:
    • In the Description field, type TimerEventReceived.
    • In the Name field, type TimerEvent.
    • In the Severity field, type 2.
  4. Click OK to create the instance.

Viewing Class Properties

Creating an Event Filter Instance

Creating an Event Timer Instance

Registering a Consumer for an Event

See Also

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 drop-down list box, choose Filters.
  2. Click the class you want to create an instance and then click New Instance.

    —or—

    Right-click on the class you want to create an instance, and then click New Instance from the pop-up menu.

    The Edit new instance properties dialog box appears.

  3. In the Edit new instance properties dialog box, type the following information:
    • In the Name field, type a name for the filter.
    • In the Query field, type a WQL SELECT statement that specifies the event criteria.
    • In the Query Language field, type WQL.
  4. Click OK to create the instance.

The following procedure is an example, which defines a filter that works with the ServiceStopped consumer to display an event message in the WBEM Event Viewer when a system service is stopped.

To create the ServiceStoppedEvent filter

  1. From the drop-down list box, choose Filters.
  2. Click the __EventFilter class and then click New Instance.

    —or—

    Right-click __EventFilter and then click New Instance from the pop-up menu.

    The Edit new instance properties dialog box appears.

  3. In the Edit new instance properties dialog box, type the following information:
    1. In the Name field, type ServiceStoppedEvent.
    2. In the Query field, type the following WQL SELECT statement to specify the event criteria:
      select * from __InstanceModificationEvent within 5 where TargetInstance isa "Win32_Service" and TargetInstance.State="Stopped"
    3. In the Query Language field, type WQL.
  4. Click OK to create the instance.

The following procedure is an example, which defines a filter that works with the TimerEvent consumer and IntervalTimer to display an event notification in the WBEM Event Viewer every 5 seconds.

To create IntervalTimerFilter

  1. From the drop-down list box, choose Filters.
  2. Click __EventFilter and then click New Instance.

    —or—

    Right-click on the __EventFilter class and then click New Instance from the pop-up menu.

    The Edit new instance properties dialog box appears.

  3. In the Edit new instance properties dialog box, type the following information:
    • In the Name field, type IntervalTimerFilter.
    • In the Query field, type the following WQL SELECT statement to specify the event criteria:
      select * from __TimerEvent
    • In the Query Language field, type WQL.
  4. Click OK to create the instance.

The following procedure is an example, which defines a filter that works with the TimerEvent consumer and AbsTimer to display an event notification in the WBEM Event Viewer at a specified date and time.

To create the AbsTimerFilter

  1. From the drop-down list box, choose Filters.
  2. Click the __EventFilter class and then click New Instance.

    —or—

    Right-click on the __EventFilter class and then click New Instance from the pop-up menu.

    The Edit new instance properties dialog box appears.

  3. In the Edit new instance properties dialog box, type the following information:
    • In the Name field, type AbsTimerFilter.
    • In the Query field, type the following WQL SELECT statement to specify the event criteria:
      select * from __TimerEvent where TimerId="AbsTimer"
    • In the Query Language field, type WQL.
  4. Click OK to create the instance.

Viewing Class Properties

Creating an Event Consumer Instance

Creating an Event Timer Instance

Registering a Consumer for an Event

See Also

__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 WBEM Event Registration Tool provides the two subclasses of __TimerInstruction: __AbsoluteTimerInstruction and __IntervalTimerInstruction. You can create an instance with either or both of these.

The following procedures generally describe the creation of the two kinds of event timer instances.

To create an absolute event timer instance

  1. From the drop-down list box, choose 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 from the pop-up menu.

    The Edit new instance properties dialog box appears.

  4. Click the Value field of the EventDateTime row.

    The Time dialog box appears.

  5. In the Time dialog box, set the date, time, and time zone; then, click OK.
  6. In the TimerId field of the Edit new instance properties dialog box, type a name for the timer.
  7. Click OK to create the instance.

To create an interval event timer instance

  1. From the drop-down list box, choose Timers.
  2. Expand the tree to expose the subclasses.
  3. Click __IntervalTimerInstruction and click the New Instance button.

    —or—

  4. Right-click on __IntervalTimerInstruction and choose New Instance from the pop-up menu. The Edit new instance properties dialog box appears.

  5. In the IntervalBetweenEvents field, type a value in milliseconds.
  6. In the TimerId field, type a name for the timer.
  7. Click OK to create the instance.

The following procedure is an example, which creates an absolute timer instruction that works with the TimerEvent consumer and AbsTimerFilter to display an event notification in the WBEM Event Viewer at a particular date and time.

To create AbsTimer

  1. From the drop-down list box, choose 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 from the pop-up menu.

    The Edit new instance properties dialog box appears.

  4. Click the Value field of the EventDateTime row.

    The Time dialog box appears.

  5. In the Time dialog box, set the date, time, and time zone appropriately and then click OK.
  6. In the TimerId field of the Edit new instance properties dialog box, type AbsTimer.
  7. Click OK to create the instance.

The following procedure is an example, which creates an interval timer that works with the TimerEvent consumer and AbsTimerFilter to display an event message in the WBEM Event Viewer at regular intervals.

To create IntervalTimer

  1. From the drop-down list box, choose Timers.
  2. Expand the tree to expose the subclasses.
  3. Click __IntervalTimerInstruction and then click New Instance.

    —or—

    Right-click __IntervalTimerInstruction and then click New Instance from the pop-up menu.

    The Edit new instance properties dialog box appears.

  4. In the IntervalBetweenEvents field, type 5000.

    This means that the event notification will occur every 5000 milliseconds (every 5 seconds).

  5. In the TimerId field, type IntervalTimer.
  6. Click OK to create the instance.

Viewing Class Properties

Creating an Event Consumer Instance

Creating an Event Filter Instance

Registering a Consumer for an Event

See Also

Timer Events

__TimerInstruction

__AbsoluteTimerInstruction

__IntervalTimerInstruction


Registering a Consumer for an Event

If you followed the examples described in Creating an Event Timer Instance, you created permanent consumers. To register to receive an event notification, permanent consumers must create at least one of each of the following instances:

  • Event consumer instance
  • Event filter instance
  • Binding between the consumer and filter

The following procedures demonstrates how to create event consumer and event filter instances as well as timers that demonstrate their functionality.

To display the example consumers and filters

  1. Select Consumers in the drop-down list box and expand the whole inheritance tree. Then, select one of the example consumer instances.

    The Event Registration screen now looks like this:

To register the ServiceStopped consumer for an event

  1. In the left pane, click the ServiceStopped consumer.
  2. In the right pane, click the ServiceStoppedEvent filter.
  3. Click Register.

    The Event Registration screen now looks like this:

Note The name of the Register button now changes to Unregister. Click it to unregister the selected consumer and filter.

The following procedure describes how to bind specific consumers and filters.

To test the ServiceStopped consumer-filter binding

  1. In Control Panel, open the Services program.
  2. Find a running service that can be safely stopped.

    —or—

    Find a service that hasn't started, start it, and wait 5 seconds.

  3. Stop the service.

    The WBEM Event Viewer appears, notifying you of the event.

As shown in the WBEM 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.

To register the TimerEvent consumer for an absolute event

  1. From the drop-down list box, choose Timers.
  2. Expand the inheritance tree under __AbsoluteTimerInstruction and then right-click AbsTimer to open the Edit Instance Properties dialog box.
  3. Click the Value field of the EventDateTime property to open the Time dialog box.
  4. Set the time to a minute or two in the future and then click OK.
  5. From the drop-down list box, choose Consumers.
  6. In the left pane, expand the consumer inheritance tree and click the TimerEvent consumer.
  7. In the right pane, click AbsTimerFilter.
  8. Click Register.

    When you reach the set time, the WBEM Event Viewer appears, showing the timer event generated at the set time.

Interval events occur at regularly occurring intervals.

To register the TimerEvent consumer for an interval event

  1. From the drop-down list box, choose Consumers.
  2. In the left pane, expand the consumer inheritance tree and then right-click the TimerEvent consumer.
  3. In the right pane, click IntervalTimerFilter.
  4. Click Register.

    The WBEM Event Viewer appears, showing the timer event generated every five seconds:

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.

See Also

Viewing Class Properties

Creating an Event Consumer Instance

Creating an Event Filter Instance

Creating an Event Timer Instance

__FilterToConsumerBinding


WBEM Event Viewer

The WBEM 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 the WBEM Event Viewer for any event filters, so you can view incoming events that match the filters. You can start the WBEM Event Viewer manually using the "WBEM Event Viewer" shortcut in the WMI SDK program group. However, this is not necessary for the WBEM 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 the WBEM Event Viewer for different types of events, use the WBEM Event Registration Tool. This tool can be launched either independently by using the shortcut in the WMI SDK program group or from the WBEM Event Viewer itself by clicking Register.

With the WBEM Event Viewer, you can do the following:

  • 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 WBEM Event Registration Tool.
  • Clear the display.

Note All permanent event consumers, including the WBEM Event Viewer, require specific distributed COM (DCOM) permissions to launch automatically on a remote computer for a registered event.

To set the launch permissions for the WBEM Event Viewer

  1. Run the Dcomcnfg.exe program from the remote computers system directory.

    The Distributed COM Configuration Properties dialog box appears.

  2. From the WBEM Applications tab, select WBEM Event Viewer and click Properties.

    The WBEM Event Viewer Properties dialog box appears.

  3. From the security tab, select the Use custom launch permissions option and press Edit.

    The Registry Value Permissions dialog box appears.

  4. Press 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.


WBEM Event Viewer Interface

The WBEM Event Viewer screen looks like this.

Note You must install Windows Management and create a repository of classes on the target computer before you use the WBEM 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\WBEM.)

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 the WBEM Event Viewer contains the classes and instances required to declare and register the WBEM 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 WBEM 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.

To open the WBEM Event Viewer

  1. Click Start, point to Programs, and then click WMI SDK. Then, click WBEM Event Viewer.

Whenever an event is received by the WBEM Event Viewer (which occurs when an event is generated that matches an event filter for which the WBEM Event Viewer is registered), a line is added to the List view in the WBEM Event Viewer's main dialog box, which provides general information for the event.

The WBEM Event Viewer includes the following buttons.

Register for events starts WBEM 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 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.

The WBEM Event Viewer 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 WBEM Event Viewerand can be set differently in different instances of this class through the WBEM 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 WBEM 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 WBEM 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.

Note As events are received and displayed in the WBEM 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.


ActiveX Controls

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 WBEM Object Browser and WBEM 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
WBEM Class Navigator | Displays a tree view of the class structure in a namespace of the Common Information Model (CIM) repository.
WBEM Provider Wizard | Generates C++ provider framework code for specified objects.
WBEM EventList | Displays events that are forwarded to it.
WBEM Event Registration | Displays event filters, event consumers, and their bindings.
WBEM MOF Compiler Wizard | Compiles a specified Managed Object Format (.mof) file.
WBEM MOF Generator Wizard | Generates a .mof file for specified objects.
WBEM Multiple Instances Viewer | Displays the details for one or more objects in a table format.
WBEM Namespace Picker | Allows users to browse and select namespaces.
WBEM Instance Navigator | Displays the associations between objects in a namespace in the CIM repository.
WBEM Login | Provides login services for the WMI ActiveX controls.
WBEM Object Viewer | Displays the details for a specified object.
WBEM Object Viewer Container | Provides navigation features for the WBEM Object Viewer and the WBEM Multiple Instances Viewer .


Creating a WMI Browser in MFC

In the following tutorial, you will create a simple Windows Management Instrumentation (WMI) browser application 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++ 5.0 running under Microsoft® Visual Studio® 97. Other Integrated Development Environments (IDEs) that support MFC could be used 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 used to build executables.
  3. Choose a location for your program and give it the name WbemBrowser.

  4. Create a Single document (SDI) application. 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 WBEM 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 dialog box Components and Controls Gallery 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. Select WBEM Instance Navigator Control.

  3. Click Insert, and then OK. When you see the Confirm Classes dialog, click OK again, and then Close. This step will add a wrapper class for the WBEM 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. While you're at it, add a Boolean member variable called m_bReady. Then, add the following boldfaced lines to the CWbemBrowserView class definition:
    // Attributes
public:
    CWbemBrowserDoc* GetDocument();

    CNavigator m_Navigator;
    bool m_bReady;
  5. 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"

    Also, include the navigator.h file at the beginning of the WbemBrowserView.cpp file.

    #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.

  6. Use ClassWizard to generate the CWbemBrowserView::Create method and fill it with the following 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;
}
  7. 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)));
}
  8. Build the project and run it. The navigator control should appear, and should completely fill the client area of the frame.

    Now you are ready to call the CNavigator::OnReadySignal method to tell the navigator control to initialize itself. This code must be called only once, and it must be called after the navigator control window is fully created.

  9. To the CWbemBrowserView constructor, add the following code.
    CWbemBrowserView::CWbemBrowserView()
{
    m_bReady = false;
}
  10. Add these lines 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();
    }
}
  11. 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 appears with the suggested default of root\CIMV2.

    Clicking OK accepts this default, but the connection fails anyway, since you have not yet logged into a WMI server.


Adding the WBEM Login Control

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\Add to Project\Components and Controls dialog box, select the Registered ActiveX Controls folder.
  2. Select WBEM Login Control and add it to your project. Accept the default wrapper class name 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:
        CNavigator m_Navigator;
    CSecurity m_Security;
    bool m_bReady;
  5. To the beginning of the MainFrm.cpp and WbemBrowser.cpp files, add:
    #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:
    #include "navigator.h"
#include "security.h"

#include "WbemBrowserDoc.h"
#include "WbemBrowserView.h"
  7. Add these lines 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 the WMI component to log into. It appears later as part of the login dialog label.


Connecting the Navigator to the Login Control

The navigator control knows the namespace but not the WMI server. To access a namespace, it must first obtain an IWbemServices pointer from the server. It gets this by firing an event which is subsequently passed to the login control. The login control displays a dialog 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 will need to 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 will need to 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 Resource Editor knows how to add ActiveX controls to a dialog box, and the ClassWizard knows how to add event handlers to a CDialog based class.

To generate ActiveX wrappers

  1. Click on 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 the WBEM Login controls.
  3. Click on the WBEM Instance navigator button and add it somewhere to the dialog box.

  4. Press CTRL+W to bring up the ClassWizard. You will see IDC_INSTNAVCTRL1 in the Object ID's 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, one at a time, later.
  6. Open the WbemBrowser.cpp file and move the following lines from the definition of the CAboutDlg class to the CWbemBrowserView class in the WbemBrowserView.h file. The lines should be inserted 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 lines 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 to the start of the WbemBrowserView.cpp file.
    #include "navigator.h"
#include "security.h"

#define IDC_INSTNAVCTRL1                1000
  10. To complete the connection between the 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 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. Add code to this handler to connect it to the CSecurity::GetIWbemServices method, 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, this 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

If you compare the browser you've created so far with the WMI Object Browser application that ships with the WMI SDK, you'll see that you've created the Object Explorer, located in the left pane of a split window. To complete the browser, you must also create the Object Viewer, located in the 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. Use the ClassWizard to add a new CObjectView class to your project, by using CView as the base class.

  2. Add a CSplitterWnd member variable to the CMainFrm class definition.
    // Attributes
public:
    CSplitterWnd m_wndSplitter;
  3. Include the WbemBrowserView.h and ObjectView.h files at the beginning of the MainFrm.cpp file. 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:
    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 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.
  5. In the CObjectView class definition, add the following code.
    // Attributes
public:
    CWBEMViewContainer m_ViewContainer;
  6. 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"
  7. To the beginning of the ObjectView.cpp file, add the following code.
    #include "stdafx.h"

#include "wbemviewcontainer.h"

#include "WbemBrowser.h"
#include "ObjectView.h"
  8. Use ClassWizard to create the CObjectView::Create method. Replace the body of the method with the following 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.

  9. In order to fill the client area of the view with the control, you must override the OnSize event handler. Use ClassWizard to generate code for the WM_SIZE event and add the following boldfaced lines of code to it.
    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)));
}
  10. Build the project and run it. The navigator should appear in the left pane, and the object view 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. Display the IDD_ABOUTBOX dialog box.
  2. Click the WBEM Object Viewer Container button and add it to the dialog box.

  3. Press CTRL+W to bring up the Class Wizard dialog box. You will see IDC_OBJVIEWERCTRL1 in the Object ID 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 the WbemBrowser.cpp file and move the following lines from the definition of the CAboutDlg class to the CObjectView class in the ObjectView.h file. Insert the lines between the AFX_MSG brackets, just after the OnSize entry. The modified lines are displayed in boldface below, just after the move.
        // 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 lines from the implementation of the CAboutDlg class to the end of the ObjectView.cpp file. Replace each occurrence of the text "CAboutDlg" with "CObjectView". 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. To the beginning of the ObjectView.cpp file, add a #define statement for IDC_OBJVIEWERCTRL1.
    #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 the CObjectView a pointer to the navigator and login controls. This lets all three controls talk to each other.
  • Connect the CNavigator::OnNotifyOpenNameSpace event to the CWBEMViewContainer::SetNameSpace method. This initializes the NameSpace property and fires the GetIWbemServices event.
  • Call the CSecurity::GetIWbemServices method from the CWBEMViewContainer::GetIWbemServices event handler.

To allow the navigator, login, and object viewer container controls to talk to each other, you must add a pointer to the object viewer container control to the CWbemBrowserView class, and pointers to the navigator and login controls to the CObjectView class.

To connect navigator and 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, 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 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 the Navigator.h and Security.h files at the beginning of the ObjectView.cpp file.
    #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 error. The logical place to initialize the new member pointers is in the CMainFrm::OnCreateClient method, since CMainFrm knows about 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 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 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 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 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 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. Select a group object. You should see the associations of that object displayed in the right pane of browser.

    This completes the tutorial on creating a WMI browser in MFC.


Managed Object Format (MOF) Language

Managed Object Format (MOF) is a compiled language created by the Desktop 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. MOF definitions of classes and instances use ASCII or Unicode text. 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.

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 for Application Developers and WMI for Provider Developers.

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. 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(1)] sint32 InParam,
       [out, id(2)] sint32 OutParam);
    [Implemented]
    sint32 MyMethod3 ([in, out, id(3)] 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, by using separate declarations, the input and output parameters can be treated differently. For example, other qualifiers can be added only to the input parameter.

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. The only restrictions on naming are that qualifier names cannot have either leading or trailing underscores. Moreover, neither the standard WMI qualifiers or those included in the Desktop 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. Valid qualifier types and their corresponding CIM and Automation types are listed in the following table.

Qualifier type | CIM type | Automation type
String | String | VT_BSTR
Signed or unsigned 16-bit number | Sint16, Uint16 | VT_I2
Signed or unsigned 32-bit number | Sint32, Uint32 | VT_I4
Signed or unsigned 64-bit number | Sint64, Uint64 | VT_BSTR
Floating point | Real8 | VT_R8
Boolean | 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(1)] 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(1)] uint32 Param1);
    [static] sint32 MyMethod2 ([out, Id(1)] uint32 Param2);
    sint32 MyMethod3 ([in, Id(1)] uint32 Param3,
        [in, out, Id(2)] 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
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 Desktop 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 Enumerations

Integer enumeration properties can be defined in MOF syntax using the Values standard qualifier. The Values qualifier provides string values for the enumeration property.

[Values {"OK", "Error", "Degraded", "Unknown"}, Read]
sint32 Status;

In the preceding example, the Status property must be set to an integer in the range from zero (0) through 3. Each integer is mapped to an ordinal position in the Values string array. A property value of zero maps to the first entry in the array. 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 in the enumeration, 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 and 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.

String properties can also be associated with an enumeration using the Values qualifier. With a string property, the actual value of the property is the entry in the Values array. For example, Status can be set to "OK" or "Unknown", as in the following code.

[Values {"OK", "Error", "Degraded", "Unknown"}, Read]
string Status;

With integer properties, you can override the integer enumeration with explicit values using the ValueMap qualifier in conjunction with the Values qualifier. In this case, the Values qualifier contains an array of string values used for interpreting the corresponding integer property values. The ValueMap qualifier contains the integer values to map to these string values. The following code example demonstrates this princple.

[ Values {"OK", "Error", "Degraded", "Unknown"},
  ValueMap {"1", "5", "10", "15" } ]
uint32 Status;

In the preceding example, the string "OK" is used if the Status property has the integer value 1. If Status has the value 10, then "Degraded" is used. Note that Status cannot take on values such as 7 or 23, which are not in the ValueMap list. Also note that Status takes on integer values, in spite of the fact that the ValueMap elements are quoted strings. The Values qualifier, when used alone, can be applied to both string and integer property types; however, when used with the ValueMap qualifier, the property type must be an integer.


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 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.

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.

Class MyClass
{
    sint32 MyMethod1 ([in, id(1)] Win32_LogicalDisk ref DiskRef);
    sint32 MyMethod2 ([in, id(1)] object ref AnyObject);
};

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(1)] 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
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.
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.

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")


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

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.


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.


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.

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).


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

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. For example, consider a source that is an instance of the class Adapter. The Adapter class is associated with the Protocol class and with the Driver class. Issuing the following ASSOCIATORS OF statement retrieves all of the Protocol and Driver instances associated with the specified Adapter instance:

ASSOCIATORS OF {Adapter="AHA-294X"}

The following diagram illustrates this example. In this diagram, the source is an instance of the Adapter class. There are three association instances, two that reference a Protocol instance and one that references a Driver instance. The endpoints are the Driver and Protocol instances. Note that the Association instances act as "bindings" between the source and the endpoints. Also note that the terms source and endpoint are relative. If one of the Protocol instances is used as the source in a different query, then the endpoint is the Adapter instance.

The most 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. The following statement retrieves endpoint instances that are associated with the specified adapter:

ASSOCIATORS OF {Adapter="AHA-294X"}

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 ASSOCIATORS OF WHERE clause 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 following statement returns only endpoints that are associated with the source through the AdapterDriver association class or any of its derived classes:

ASSOCIATORS OF {Adapter="AHA-294X"} WHERE AssocClass = AdapterDriver

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 following statement returns definitions for the Driver and Protocol classes:

ASSOCIATORS OF {Adapter="AHA-294X"} WHERE ClassDefsOnly

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 they are associated with the target through a particular set of tagged association classes. For example, the following statement returns endpoint instances if the association class includes a qualifier called SpecialTag:

ASSOCIATORS OF {Adapter="AHA-294X"}
    WHERE RequiredAssocQualifier = SpecialTag

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 following statement returns endpoint instances that include a qualifier called AdapterTag:

ASSOCIATORS OF {Adapter="AHA-294X"}
    WHERE RequiredQualifier = AdapterTag

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 following statement returns endpoint instances that are derived from the SystemDriver class:

ASSOCIATORS OF {Adapter="AHA-294X"} WHERE ResultClass = SystemDriver

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 child property in their association with a source object, as the following query illustrates:

ASSOCIATORS OF {Adapter="AHA-294X"} WHERE ResultRole = child

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 child property, as the following query illustrates:

ASSOCIATORS OF {Adapter="AHA-294X"} WHERE Role = child

Every 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 ASSOCIATORS OF {A} query returns two X endpoints.


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 durations of 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.


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.


WBEMTest

[This is preliminary documentation and subject to change.]

WBEMTest is a utility you can use to view or modify Common Information Model (CIM) classes, instances, or methods when developing Windows Management Instrumentation (WMI) providers and WMI applications.

This section contains the following topics:

  • About WBEMTest

    This topic describes WBEMTest and what it is used for.

  • Using WBEMTest

    This topic shows how to use the functions of WBEMTest.


About WBEMTEST

[This is preliminary documentation and subject to change.]

WBEMTest is a general purpose utility you can use to create, enumerate, and delete classes and instances; execute the methods of instances; run queries; and display the Managed Object Format (MOF) code for classes and instances. Because WBEMTest acts as a front end to the COM API for WMI, you can use WBEMTest to check queries, classes, and instances when developing WMI providers and WMI client applications.

The executable file for WBEMTest, Wbemtest.exe, is installed in the WBEM directory of your windows system directory. On Microsoft® Windows NT®/Windows® 2000 systems, this is the Winnt\system32\Wbem.


WBEMTest Dialog Boxes

[This is preliminary documentation and subject to change.]

This section shows some of the dialog boxes that are used by WBEMTest.


The WBEMTest Main Dialog Box

[This is preliminary documentation and subject to change.]

The WBEMTest main dialog box is the user interface for the WBEMTest utility.

You can enumerate, create, open, and delete classes using the following buttons:

  • Enum Classes
  • Create Class
  • Open Class
  • Delete Class

You can enumerate, create, open, and delete instances using the following buttons:

  • Enum Instances
  • Create Instance
  • Open Instance
  • Delete Instance

You can open namespaces, execute queries, execute the methods of classes, and create refreshers using the following buttons:

  • Open Namespace
  • Query
  • Notification Query
  • Execute Method
  • Create Refresher

You can use the Execute asynchronously check box to perform actions asynchronously. If you are performing tasks that take a long time to execute, such as complex queries, asynchronous operations allow WBEMTest to perform other actions at the same time. For more information about asynchronous calls see Making an Asynchronous Call.

You can click Edit Context to set up a context object. With context objects, you can define properties and values for properties that some providers use as an additional source of information. For more information about context objects see IWbemContext.


WBEMTest Connect Dialog Box

[This is preliminary documentation and subject to change.]

Before you can use the functions of WBEMTest you need to log on to WMI. Click Connect to log on to WMI. The connect dialog box appears.

You can generally accept the default settings for the items on the Connect dialog box. A description of the fields of the connect dialog box are listed below.

  • The namespace field will show the default namespace for your computer. You can specify a different namespace on your computer or on another computer. For example, for access to the classes of the Win32 provider, you could specify "root\cimv2". If you wanted to access the cimv2 namespace on a remote computer named "myserver" you could specify "\\myserver\root\cimv2". To access remote computers you must grant permission to read or write from the remote computer using the WMI Permission Editor (Wbemperm.exe)
  • The credentials fields allow you to specify a user name, password and authority. You can log on to WMI as a different user using credentials that are different than the current logged on user. If you leave these boxes blank WMI will use the settings from the current Windows logon.
  • The locale field lets you specify a different locale by entering a localization code. If you want to use the current locale, leave this field blank. If not blank, this field 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\0x409"
  • The how to interpret empty password option buttons control what will happen if you leave the password field blank. WMI processes a blank password differently from no password at all. The default value for this field is NULL and causes WBEMTest to use the current windows password to connect to WMI. If you need to login to WMI using an empty password, you should select the "blank" option button.
  • The impersonation level option buttons allow you to set the distributed COM (DCOM) impersonation level that WEBEMTest will use. In most cases, you can use the default value for this option button, "impersonate", however, some providers may require specific impersonation settings. Consult the documentation for the provider you are using if you are not sure what value to use. Additionally, the impersonation level that you specify must be applicable to the operating system that you are using. For example, you can specify an impersonation level of "delegate" and WBEMTest is not running on a computer that uses the Windows 2000 operating system, this setting will be ignored. For more information about impersonation see Security Impersonation Technology Conceptual Overview and API and Setting the DCOM Impersonation Level for the Scripting API
  • The authentication level option buttons allow you to specify the distributed COM (DCOM) authentication level that will be used. These authentication levels control how information is authenticated by DCOM. Generally, the default value for this option button can be used. For more information about DCOM authentication levels see Setting the DCOM Authentication Level for the Scripting API


Object Editor Dialog Box

[This is preliminary documentation and subject to change.]

The Object Editor dialog box appears when you double-click a class or instance from the Query Result dialog box. The Object Editor dialog box also appears when you click Open Class or Enum Class on the main WBEMTest dialog box.

You can use the Object Editor dialog box to:

  • Edit the qualifiers, properties, and methods for the selected class or instance.
  • View the MOF code that creates the class or instance.
  • View instances of the class, the derived classes, and the superclass of the class, if you are editing a class definition.

For example, when you click Open Class on the WBEMTest main dialog box and type Win32_LogicalDisk in the Get Class Name dialog box the Object Editor for Win32_LogicalDisk dialog box appears.

If you double-click any of the items in the list boxes the appropriate editor will open for that object. For example, if you double-click the reset method in the methods list box, the method editor for the reset method will appear.


Object Editor Qualifier, Property, and Method Functions

[This is preliminary documentation and subject to change.]

The qualifier, property, and method functions for the Object Editor are as shown below:

  • Click Add Qualifier to open the Qualifier Editor dialog box You can use this feature to add qualifiers that apply to the class or instance as a whole as opposed to a specific property of the class or instance. Type in the values for the new qualifier and click Save Qualifier to create the new qualifier.
  • Click Edit Qualifier to open the Qualifier Editor dialog box for the qualifier that is selected. You can use this to change the value or flavors assigned to a qualifier.
  • Click Delete Qualifier to delete the currently selected qualifier.
  • Click Hide System Properties and system properties do not show in the Object Editor dialog box.
  • Click Add Property to define new properties and assign values to classes or instances. When you click Add Property the Property Editor dialog box appears.
  • Click Edit Property to change the definition for the currently selected property.
  • Click Delete Property to delete the currently selected qualifier.
  • Click Add Method to define the methods for a class or instance. When you click Add Method, the Method Editor dialog box appears.
  • Click Edit method to edit the methods for a class or instance. When you click Edit Method, the Method Editor dialog box appears.
  • Click Delete Method to delete the currently selected method.


Other Object Editor dialog box functions

[This is preliminary documentation and subject to change.]

The other buttons on the Object Editor dialog box are as follows:

  • Click Close to close the Object Editor dialog box.
  • Click Save Object to save the changes to the current class or instance.
  • Click Show MOF to open the MOF dialog box which contains the managed object format (MOF) code that you can use to construct the current object. It is important to remember that the MOF code shown in this dialog box might not be identical to the actual MOF code that created the class or instance. The original MOF file might have had comments and different formatting than this text shows. For more information about MOF code see Managed Object Format (MOF) Language
  • Click Superclass to run a schema query that shows the class that the current class or instance is derived from.
  • Click Derived to run a schema query that shows the child classes of the current class or instance.
  • Click Instances to show instances of the current class.
  • Use the Update type option buttons to control how the class will be updated. There are two groups of option buttons that control the update process.
Update Type | Meaning
Create only | Used for creation only. The save operation will fail if the class or instance already exists.
Update only | Causes this call to update. The class or instance must exist for the save operation to be successful.
Either | Causes the class or instance to be created if it does not exist or overwritten if it exists already.

Update Type | Meaning
Compatible | 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 value for this option button and is used for compatibility with previous versions of WMI. If the class has instances the update fails.
Safe | 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 value 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 fails.
Force | Forces updates of classes when conflicting child classes exist. For example, this value forces an update if a class qualifier was defined in a child class, and the base class tries to add the same qualifier in conflict with the existing one. In force mode this conflict is resolved by deleting the conflicting qualifier in the child class. If the class has instances the update fails.


Get Object Path Dialog Box

[This is preliminary documentation and subject to change.]

You can use the Get Object Path dialog box to specify the name of a class or the relative path to a class instance.

Object paths have the format: [Class].[KeyProperty] = Value

For example, if you have an instance of a class called Myclass that has a key property called Keyproperty with a value of "A" the object path would be: MyClass.KeyProperty="A". The following picture shows the object path.

For more information see Object Paths.


Get Class Name Dialog Box

[This is preliminary documentation and subject to change.]

Use the Get Class Name dialog box to specify class names for the open class function of WBEMTest.


Superclass Info Dialog Box

[This is preliminary documentation and subject to change.]

The enum classes function uses the Superclass Info dialog box. If you select the Recursive option button, WBEMTest will also enumerate the subclasses of the class you specify.


Query Dialog Box

[This is preliminary documentation and subject to change.]

Use the Query dialog box to compose a query and then execute it.

You can type the WBEMTest query in the Enter Query text box.

In Query Type, you can select a query language. Currently only Windows Management Instrumentation (WMI) Query Language (WQL) is supported.

You can use the Retrieve class prototype check box to indicate that you do not want instances from this query and to return the class that the instances would belong to if they were returned.

For more information about queries see Using Queries and WMI Query Language.


Query Result Dialog Box

[This is preliminary documentation and subject to change.]

The Query Result dialog box is displayed when you perform a function that enumerates classes or instances. This dialog box also appears for event notification queries to display events. For asynchronous event notification queries this dialog box displays the events as they are received. Click Add to show new events when you are running a semi-synchronous event notification query.

If the query results are instances, the relative path for the instances is displayed. You can double-click any of the objects in the Query Result dialog box and the Object Editor dialog box for that object appears.


Class Info Dialog Box

[This is preliminary documentation and subject to change.]

Use the Class Info dialog box to specify the name of the class for which you want to see instances. This dialog box appears when you click Enum instances. If you select Immedialte Only, only instances of the class you specify will be displayed. If you select Recursive, instances of the subclasses of the class you specify will be displayed.


Execute Method Dialog Box

[This is preliminary documentation and subject to change.]

You can use the Execute Method dialog box to run a method of a class or class instance.

There are several parts to the Execute Method dialog box:

  • Click Edit Object Path to edit the object path. You can set the object path to refer to a specific instance if necessary.
  • The Object Path text box shows the current object path.
  • Click Dismiss to close this dialog box without executing the method.
  • The Method drop down list displays the methods available for this class.
  • Click Edit In Parameters to set the various parameters the method might require.
  • Click Clear In Parameters to reset all the input parameters to the default settings.
  • Click Edit Out Parameters to view the output parameters for the method. The output parameters contain data returned from a method.


Property Editor Dialog Box

[This is preliminary documentation and subject to change.]

Use the Property Editor dialog box to create or edit properties of classes. In some cases, such as when editing an existing class, you might not be able to set all the fields on this dialog box.

The following steps describe how to add or edit a property.

To add or edit a property

  1. Enter the name of a new property in Property Name. You cannot change the name of existing properties.
  2. The name of the parent class of the current class or instance is displayed in Class of origin. You cannot change the Class of origin field.
  3. Specify the data type of the data stored in the property. For example, if the property will store string data you should specify CIM_STRING. Examples of valid CIM types are shown in the table below.
  4. Select the Array check box if this property will contain an array of objects of the type you declare.
  5. Define a value for the property in the Value box. This value will be the default value if this is a property of a class.
  6. Select standard qualifiers in the Qualifiers section by clicking the associated option button. For example, to specify this property as a key property click Key and the key qualifier will be added to the class. You can also add, delete and edit other qualifiers using Add Qualifier, Delete Qualifier, and Edit Qualifier.
  7. Click Save Property to update this property.

The following table shows valid CIM types you can select in the Type box.

CIM Type | Type of data stored
CIM_SINT8 | 8-bit signed integer
CIM_UINT8 | 8-bit unsigned integer
CIM_SINT16 | 16-bit signed integer
CIM_UINT16 | 16-bit unsigned integer
CIM_SINT32 | 32-bit signed integer
CIM_UINT32 | 32-bit unsigned integer
CIM_SINT64 | 64-bit signed integer
CIM_UINT64 | 64-bit unsigned integer
CIM_REAL32 | 32-bit real number
CIM_REAL64 | 64-bit real number
CIM_BOOLEAN | BOOLEAN value
CIM_STRING | String
CIM_DATETIME | Date/Time
CIM_REFERENCE | Reference object
CIM_CHAR16 | Character
CIM_OBJECT | CIM object


Qualifier Editor Dialog Box

[This is preliminary documentation and subject to change.]

You can define the name, data type, flavor, and value of a qualifier in the Qualifier Editor dialog box.

You can assign four common qualifier flavors to your qualifier by selecting the check boxes in the flavor section.

For more information on qualifiers see qualifiers and Qualifier Flavors.


Method Editor Dialog Box

[This is preliminary documentation and subject to change.]

You can use the Method Editor dialog box to add and edit methods to classes and class instances.

The Method Editor dialog box contains the following:

  • Enable the Edit Input Arguments button by clicking the Enable Input Args option button.

    Click the Edit Input Arguments button to open the Object Editor dialog box for an instance of the __Parameters class. You can use the object editor to edit or define new input parameters for a method.

  • Enable the Edit Output Arguments button by clicking the Enable Output Args option button.

    Click the Edit Output Arguments button to the Object Editor dialog box for an instance of the __Parameters class. You can use the object editor to edit or define new output parameters for a method.

  • Add, delete, and edit the qualifiers for this method in the Qualifiers section.
  • Click Save Method to save new methods and update existing methods.


Refresher Dialog Box

[This is preliminary documentation and subject to change.]

You can use the REFRESHER dialog box to add, delete, and update refreshers.

The REFRESHER dialog box contains the following:

  • Click Add to display the Get Object For refresher dialog box.
  • You can type the name of a class that supports refreshers and a refresher will be added to the list.
  • Delete refreshers from the list by clicking Delete.
  • Click Refresh to populate the instances with data.

Note The refreshers you create will be empty until you click Refresh. You can click Refresh as often as necessary to update the data in your refreshers.


Get Object For Refresher Dialog Box

[This is preliminary documentation and subject to change.]

You can use the Get Object For Refresher dialog box to specify the object path to a class or instance to which your refresher belongs.

The Get Object For Refresher dialog box contains the following:

  • Type the relative path to an instance and click Add Object if your refresher is an instance.
  • Type the class name of your refresher and click Add Enum if your refresher is an enumeration.


MOF Dialog Box

[This is preliminary documentation and subject to change.]

The MOF dialog box appears when you click Show MOF on the Object Editor dialog box. You can use the MOF dialog box to display the Managed Object Format (MOF) code when editing a class or class instance in the Object Editor dialog box.


Using WBEMTEST

[This is preliminary documentation and subject to change.]

This section shows how to connect to WMI from WBEMTest, use the WBEMTest class and instance functions, open a namespace, execute methods, and create a query.


Connecting to WMI with WBEMTest

[This is preliminary documentation and subject to change.]

When you start WBEMTest, the main dialog box appears. Before you can use the functions of WBEMTest, you need to log on to WMI.

The following steps describe how to log on to WMI.

To log on to WMI

  1. Click Connect.

    The WBEMTest Connect dialog box appears.

  2. Type the path to the namespace to which you want to log on.

    For example, you can type "root\cimv2" to connect to the namespace where the Win32 provider classes reside. The connect dialog box has options you can set but in most cases you can use the default settings.

  3. Click login on the connect dialog box.

    The namespace you connected to shows in the upper left corner of the WBEMTest main dialog box and the buttons on this dialog box are active.


Enumerating Classes with WBEMTest

[This is preliminary documentation and subject to change.]

You can display the child classes of a superclass by clicking Enum Classes on the WBEMTest main dialog box.

The following steps describe how to enumerate classes using WBEMTest.

To enumerate classes

  1. Click Enum Classes.

    The Superclass Info dialog box appears.

    Type the name of the superclass If you want to enumerate the child classes of a specific class. For example, you could specify "Cim_StorageExtent" as the superclass. To see all the top level classes for the current namespace, leave the Superclass Info dialog box empty and select the Immediate only option button. If you want to see all the classes in a namespace leave the Superclass Info dialog box empty and select the Recursive option button. When you select the Recursive option button, subclasses of the superclass, and all the subclasses of those subclasses will appear. If you select the Immediate only option button, only the immediate subclasses of the superclass you specify will appear.

  2. Click OK.

    The Query Result dialog box appears containing the subclass of the superclass you specified.


Creating a Class with WBEMTest

[This is preliminary documentation and subject to change.]

You can create a new class definition in the current namespace by clicking Create Class on the WBEMTest main dialog box.

The following steps describe how to create a new class using WBEMTest.

To create a new class

  1. Click Create Class.

    The Optional Superclass dialog box appears.

  2. If you are creating a new base class, leave this dialog box empty.
  3. If you are specifying an existing class definition you can use the current namespace on which the new class should be based.

    For example, if you specify Win32_LogicalDisk as the superclass, the new child class inherits the properties of the Win32_LogicalDisk class.

  4. Click Continue.

    The Object Editor dialog box appears.

  5. Select the __Class property.
  6. Select Edit Property.

    The Property Editor dialog box appears.

  7. Click Not Null and type the name for the new class in the text box.
  8. Click Save Property.

    The Object Editor dialog box appears.

  9. Define the properties, qualifiers, and methods for the new class. For a full description of how to define properties, qualifiers, and methods for a class, see the Object Editor dialog box.
  10. Click Save Object and the new class is created.


Opening Classes with WBEMTest

[This is preliminary documentation and subject to change.]

You can edit properties, qualifiers, and methods for the class you specify with the Open Class button on the WBEMTest main dialog box.

The following steps show how to open a class using WBEMTest.

To open a class

  1. Click Open Class on the main WBEMTest dialog box.

    The Get Class Name dialog box appears.

  2. Type the name of the class you want to open.
  3. Click OK.

    The object editor for the class you specified appears.

  4. Click Save Object in the Object Editor dialog box to save the changes to the class.


Deleting Classes with WBEMTest

[This is preliminary documentation and subject to change.]

You can delete a class in the current namespace with the Delete Class button on the WBEMTest main dialog box.

The following steps describe how to delete a class using WBEMTest.

To delete a class

  1. Click Delete Class on the WBEMTest main dialog box.

    The Get Class Name dialog box appears.

  2. Type the name of the class you want to delete and click OK.

    A dialog box warning you that the class may have derived classes or instances appears even if there are no derived classes or instances.

  3. If you are sure you want to delete the class, click Yes and the class will be deleted.


Enumerating Instances with WBEMTest

[This is preliminary documentation and subject to change.]

You can enumerate the instances of a class with the Enum Instances button on the main WBEMTest dialog box.

The following steps describe how to enumerate instances of a class using WBEMTest.

To enumerate instances of a class

  1. Click Enum Instances on the main WEBMTest dialog box.

    The Class Info dialog box appears.

  2. Type the name of the class for which you want to see instances.
  3. If you want to see instances of the derived classes of the superclass you specify, click the recursive option button.
  4. If you want to see only the immediate instances of the class you specify, click the immediate option button.
  5. Click OK.

    The query result dialog box appears. The relative path for each of the instances is displayed in the query result dialog box.

    Double-click any of the instances listed in the Query Result dialog box and the Object Editor dialog box appears for that instance.


Creating an Instance with WBEMTest

[This is preliminary documentation and subject to change.]

You can create a new instance of a class in the current namespace with the Create Instance button on the WBEMTest main dialog box.

The following steps describe how to create an instance of a class.

To create an instance of a class

  1. Click Create Instance on the main WEBMTest dialog box.

    The Get Class Name dialog box appears.

  2. Type the name of a class in the current namespace and click OK.

    The Instance Of dialog box appears. This dialog box is almost identical to the Object Editor dialog box. You can use the Instance Of dialog box to set properties for the new instance.

  3. Set the values of the properties for your new instance by clicking Edit Property on the Instance Of dialog box..

    If the instance you are creating has key properties, set them to an appropriate value before you save the instance.

    If you do not assign a value for the key property a globally unique identifier (GUID) is assigned to the key property by default.

  4. Click Save Object and the new instance is created.


Opening an Instance with WBEMTest

[This is preliminary documentation and subject to change.]

You can open an instance of a class with the Open Instance button on the WBEMTest main dialog box.

The following steps describe how to open an instance of a class.

To open an instance of a class

  1. Click Open Instance on the main WEBMTest dialog box.

    The Get Object Path dialog box appears.

  2. Type the relative object path for the instance you want to retrieve.

    For example, if you want to open an instance of the Win32_LogicalDisk class, type Win32_LogicalDisk.DeviceID="C:".

  3. Click OK.

    The Object Editor dialog box for the instance appears. You can use the Object Editor dialog box to view or edit the class instance you have opened.


Deleting an Instance with WBEMTest

[This is preliminary documentation and subject to change.]

You can delete an instance of a class with the Delete Instance button on the WBEMTest main dialog box.

The following steps describe how to delete an instance of a class using WBEMTest.

To delete an instance of a class

  1. Click Delete Instance on the main WBEMTest dialog box.

    The Get Object Path dialog box appears.

  2. Type the relative object path for the instance you want to delete.

    For example, to delete an instance of MyClass where the key property is F122, type MyClass.KeyProperty="F122".

  3. Click OK and the instance is deleted.

Note You cannot delete instances of dynamic classes. For example, if you attempt to delete an instance of Win32_Process, a Provider Not Capable error appears.


Opening a Namespace with WBEMTest

[This is preliminary documentation and subject to change.]

You can open a namespace within the namespace to which you are currently logged on with the Open Namespace button on the WBEMTest main dialog box.

The following steps describe how to open a namespace using WBEMTest.

To open a namespace

  1. Click Open Namespace on the main WBEMTest dialog box.

    The Get Object Path dialog box appears.

  2. In the Object Path text box, type the name of a namespace that is contained within the current namespace.

    For example, type cimv2 if you are already logged on to the root namespace.

  3. Click OK.

    If the logon is successful the namespace field on the WBEMTest main dialog box is updated to show the new active namespace.

Note You can only use the Open Namespace button to open namespaces inside the current active namespace. You also cannot move to a namespace that is closer to the root namespace than the current namespace. For example, if your current active namespace is root\cimv2 you cannot use the Open Namespace button to move to the root namespace. You must log on to WMI again to connect to other namespaces.


Executing Class and Data Queries

[This is preliminary documentation and subject to change.]

You can execute class (schema) and data queries with the Query button on the WBEMTest main dialog box.

To execute a query

  1. Click Query on the main WEBMTest dialog box.

    The Query dialog box appears.

  2. In the Enter Query box, type your query.

    The following is an example of a query that checks for instances of Win32_Logicaldisk that have a device ID of "C:" or "D:" and have at least 560 MB of disk space available:

    SELECT * FROM Win32_LogicalDisk WHERE (Name = "C:" OR Name = "D:") AND FreeSpace > 560000000
  3. If you only want to see the class definition, select the Retrieve class prototype check box.

    If you do not select the Retrieve class prototype check box, instances are returned unless you construct a schema query.

  4. Click Apply to execute the query.

    The Query Result dialog box appears. WBEMTest attempts to return class instances based on the criteria you specify.

Note You can create data and schema queries with the query option. You cannot create event queries with the query option. To perform event queries, click Notification Query.

For more information about WQL and constructing queries see WMI Query Language, and Schema queries.


Executing a Notification Query with WBEMTest

[This is preliminary documentation and subject to change.]

You can query for event notifications with the Notification Query button on the WBEMTest main dialog box.

The following steps describe how to run an event notification query using WBEMTest.

To run an event notification query

  1. Click Notification Query on the WBEMTest main dialog box.

    The query dialog box appears.

  2. In the Enter Query box, type an event notification query.

    The following is an example of an event query that notifies you when a log event occurs.

    SELECT * FROM __instancecreationevent WHERE TargetInstance ISA 'Win32_NTLogEvent'
  3. Click Apply.

    The Query Result dialog box appears. The words Operation in Progress appear in the lower-right corner Indicating that WMI is processing your query. Because event notification queries are never complete, the Operation in Progress status message will continue to show on the Query Result dialog box until you stop the query.

  4. If your event notification query is running semisynchronously you must poll for results by clicking the Add button.
  5. If your event notification query is running asynchronously, events are displayed in the Query Result dialog box as the events are received.

    If you want to view an event notification, double-click the event in the Query Result dialog box. The Instance Of dialog box appears.

  6. Click Close to stop the query.

Note If you want your event notification query to run asynchronously, select the Execute asynchronously check box on the WBEMTest main dialog box.

For more information about events and event notification see Event Notification.


Executing a Method with WBEMTest

[This is preliminary documentation and subject to change.]

You can execute the methods of classes or class instances with the Execute Method button on the WBEMTest main dialog box.

The following steps show how to execute the Create method for the Win32_Process class of the Win32 Provider.

To execute a method of a class instance.

  1. Click Execute Method on the WBEMTest main dialog box.

    The Get Object Path dialog box appears.

  2. If the method you are executing applies to a specific instance, type the relative path to the specific instance of that class.
  3. If the method applies to the class in general, type only the class name. For example you can type Win32_Process.
  4. Click OK.

    The Execute Method dialog box appears.

  5. Click Edit In Parameters to set up the input parameters for the Create method.

    The Object Editor dialog box appears. Most methods require specific input parameters to execute correctly. The properties that you need to set depend on the method you are executing. In this example we are executing a method that only requires us to set only the commandline parameter that is the name of the process we want to create.

  6. Click the CommandLine property and click Edit Property.

    WBEMTest creates an instance of the __Parameters class and opens the Object Editor dialog box for this object. The properties of the __Parameters object define the in parameters for the method.

  7. Click the CommandLine property to select it.
  8. Click Edit Property.

    The Property Editor dialog box appears.

  9. Select the Not NULL option button and type the name of the executable to launch as a new process.

    For example, you can type calc.exe if you want the new process to be the Windows calculator.

  10. Click Save Property when you are done setting up the in parameters. The Execute Method dialog box appears.
  11. Click Execute and the method runs.

    In this example, an instance of the Windows calculator starts on your computer.

  12. If the method is successful, a dialog box appears with the words Method executed successfully.
    1. Click Edit Out Parameters to see the out parameters of the Create method.

    WMI creates an instance of the __Parameter class that you can examine to see the result code of the method returned. If the method did not execute successfully, you can determine the error code by examining the value of the ReturnValue property. Some methods return the data as values of properties of the __Parameter instance. The Create method returns the process ID of the new process in a property called ProcessId.


Creating a Refresher with WBEMTest

[This is preliminary documentation and subject to change.]

Refreshers are processes that allow providers to deliver information at a very high rate. Because refreshers are an in-process DLL to the client applications or an in-process DLL to WMI in the case of remote providers, they can deliver management information much faster than standard providers. You can create a refresher using WBEMTest if the provider you are using supports refreshers. The Performance Monitor Provider is an example of a standard provider that supports refreshers. If your operating system is Windows 2000 you probably already have this provider installed.

The following steps describe how to create a refresher using WBEMTest.

To create a refresher using WBEMTest

  1. Click Create Refresher in the WBEMTest main dialog box.

    The REFRESHER dialog box appears.

  2. Click Add to add a new refresher.

    The Get Object For Refresher dialog box appears.

  3. Type the name of the class or the path to the instance of which your refresher is part in the Object Path box.

    If your system has the Performance Monitor Provider installed and you are logged on to the root\default namespace you can create a refresher for the Win32Perf_RawProcess class.

  4. Click add enum because the refresher for the Win32Perf_RawProcess class is an enumeration.

    The refresher dialog box appears with the new refresher in the list.

  5. Click refresh to populate the refresher.
  6. Double-click the refresher to see the enumeration.

    The Query Result dialog box appears.


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:

WMI System Classes, a complete listing of the classes defined by WMI.

WMI System Properties, a complete listing of the properties supported by WMI.

WMI Standard Qualifiers, a complete listing of the qualifiers supported by WMI.

Provider Framework Classes, including CInstance Class Methods, Provider Class Methods, CFrameworkQuery Class Methods, and CWbemProviderGlue Class Methods.

Provider Framework Utility Classes, including WBEMTime Class Methods, and WBEMTimeSpan Class Methods.

COM API for WMI, a complete listing of the COM interfaces that are used by C and C++ management applications and providers to access WMI.

Scripting API for WMI, a 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, including WBEM Class Navigator, WBEM Provider Wizard, WBEM EventList, WBEM Event Registration, WBEM MOF Compiler Wizard, WBEM MOF Generator Wizard, WBEM Multiple Instances Viewer, WBEM Namespace Picker, WBEM Instance Navigator, WBEM Login, WBEM Object Viewer, and WBEM Object Viewer Container.

SQL for WMI, which contains an alphabetical listing the supported WMI ODBC functions.

MOF Compiler, a description of the command-line syntax used by the Managed Object Format (MOF) compiler.

Backus Naur Form Syntax, a description of the BNF syntax for MOF, Structured Query Language version 1 (SQL1), and object paths.

SNMP Compiler Error Messages, which describes the various error conditions that can result when the SNMP information module compiler parses a MIB module.

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, a description of the syntax used by the WMI executable file, Winmgmt.exe.

Wbemdump, a 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 included in the WMI software development kit (SDK) that are based on the Common Information Model (CIM). 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 that is 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 most, but not all system classes. For a list of system classes you can derive from, see System Classes You Can Derive From. For a list of system classes you cannot derive from, see System Classes You Cannot Derive From.

The documentation for each of the system classes includes only the non-system local properties. Properties that are inherited are documented with their original class only. Links are available with each class definition to allow the reader to quickly and easily navigate the class hierarchy.

The following list includes all of the WMI system classes:

__AbsoluteTimerInstruction

__AggregateEvent

__CIMOMIdentification

__ClassCreationEvent

__ClassDeletionEvent

__ClassModificationEvent

__ClassOperationEvent

__ClassProviderRegistration

__Event

__EventConsumer

__EventConsumerProviderRegistration

__EventFilter

__EventGenerator

__EventProviderRegistration

__ExtendedStatus

__ExtrinsicEvent

__FilterToConsumerBinding

__Group

__IndicationRelated

__InstanceCreationEvent

__InstanceDeletionEvent

__InstanceModificationEvent

__InstanceOperationEvent

__InstanceProviderRegistration

__IntervalTimerInstruction

__MethodProviderRegistration

__Namespace

__NamespaceCreationEvent

__NamespaceDeletionEvent

__NamespaceModificationEvent

__NamespaceOperationEvent

__NotifyStatus

__NTLMGroup

__NTLMUser

__ObjectProviderRegistration

__PARAMETERS

__Provider

__SecurityRelatedClass

__Subject

__SystemClass

__TimerEvent

__TimerInstruction

__TimerNextFiring

__User

__Win32Provider


System Classes You Can Derive From

Only the following system classes can serve as base classes for your derived classes.

System Class | Use
__EventConsumer | to create new consumer types
__ExtendedStatus | to create new error object types
__ExtrinsicEvent | to create new event types
__Namespace | to be used by the SNMP provider to create its namespaces


__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;
};

Properties

MachineName
Name of the computer on which the event consumer class resides.

Remarks

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


__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

Description
Any user-defined string that describes an error or operational status.
Operation
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 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 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

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 StatusCode 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.


__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.


__Namespace

The __Namespace system class represents a WMI namespace.

class __NAMESPACE : __SystemClass
{
  [key] string Name;
};

Properties

Name
The namespace name.

Remarks

Creating a new instance of the __Namespace class 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 three instances of the __Namespace class. One has its Name property set to "Default," a second has Name set to "Security", and a third has Name set to "Cimv2." These instances represent the Root\Default, Root\Security, and Root\Cimv2 namespaces, respectively.


System Classes You Cannot Derive From

The following system classes must not be used as base classes for your derived classes.

System Class

__AbsoluteTimerInstruction
__AggregateEvent
__CIMOMIdentification
__ClassCreationEvent
__ClassDeletionEvent
__ClassModificationEvent
__ClassOperationEvent
__ClassProviderRegistration
__Event
__EventConsumerProviderRegistration
__EventFilter
__EventGenerator
__EventProviderRegistration
__FilterToConsumerBinding
__Group
__IndicationRelated
__InstanceCreationEvent
__InstanceDeletionEvent
__InstanceModificationEvent
__InstanceOperationEvent
__InstanceProviderRegistration
__IntervalTimerInstruction
__MethodProviderRegistration
__NamespaceCreationEvent
__NamespaceDeletionEvent
__NamespaceModificationEvent
__NamespaceOperationEvent
__NotifyStatus
__NTLMGroup
__NTLMUser
__ObjectProviderRegistration
__PARAMETERS
__PropertyProviderRegistration
__Provider
__ProviderRegistration
__SecurityRelatedClass
__Subject
__SystemClass
__TimerEvent
__TimerInstruction
__TimerNextFiring
__User
__Win32Provider


__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

EventDateTime
A fixed-length string in DMTF format that specifies when the timer should fire.

Remarks

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. The TimerId property is inherited from the __TimerInstruction superclass.

See Also

Timer Events


__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

NumberOfEvents
The number of events combined to produce this single summary event.
Representative
A 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

There are no properties inherited from the __IndicationRelated superclass.

Event providers never generate aggregate events. They must ignore the GROUP WITHIN clause in their processing of event queries.

See Also

Event Queries


__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

SetupDate
A string in the Desktop 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
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
Indicates the version of the actual WinMgmt.exe image currently executing. This is of the form:

"1.00.184.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.

VersionUsedToCreateDB
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.


__ClassCreationEvent

The __ClassCreationEvent system class represents a class creation event, which is a type of intrinsic event that is generated when a new class is added to the namespace.

class __ClassCreationEvent : __ClassOperationEvent
{
};

Properties

None.

Remarks

The TargetClass property inherited from __ClassOperationEvent contains a copy of the class that was created.


__ClassDeletionEvent

The __ClassDeletionEvent system class represents a class deletion event, which is a type of intrinsic event that is generated when a class is removed from the namespace.

class __ClassDeletionEvent : __ClassOperationEvent
{
};

Properties

None.

Remarks

The TargetClass property inherited from __ClassOperationEvent contains a copy of the class that was deleted.


__ClassModificationEvent

The __ClassModificationEvent system class represents a class modification event, which is a type of intrinsic event that is generated when a class is changed in the namespace.

class __ClassModificationEvent : __ClassOperationEvent
{
  object PreviousClass;
};

Properties

PreviousClass
Contains a copy of the original version of the class.

Remarks

The event reports both the new and old versions of the class definition. The TargetClass property inherited from __ClassOperationEvent contains the new version of the class, and the PreviousClass property contains the class as it was before the change.


__ClassOperationEvent

The __ClassOperationEvent system class is a base class for all intrinsic events that relate to a class.

class __ClassOperationEvent : __Event
{
  object TargetClass;
};

Properties

TargetClass
The 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

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


__ClassProviderRegistration

The __ClassProviderRegistration system class registers class providers with WMI.

class __ClassProviderRegistration : __ObjectProviderRegistration
{
  [key] __Provider ref provider;
  string ResultSetQueries[];
  string ReferencedSetQueries[];
  string UnsupportedQueries[];
};

Properties

ResultSetQueries
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.
ReferencedSetQueries
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.
UnsupportedQueries
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 inherits several properties from its superclasses in the class hierarchy:

__ObjectProviderRegistration,

__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. When included in a __ClassProviderRegistration instance, the Provider property specifies the name of the class provider.

See Also

Registering Class and Instance Providers


__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.

See Also

Intrinsic and Extrinsic Events, Event Notification, __ClassOperationEvent, __InstanceOperationEvent, __NamespaceOperationEvent


__EventConsumerProviderRegistration

The __EventConsumerProviderRegistration system class registers event consumer providers with WMI.

class __EventConsumerProviderRegistration : __ProviderRegistration
{
  [key] __Provider ref provider;
  string ConsumerClassNames[];
};

Properties

ConsumerClassNames
One or more names of logical consumer classes that are supported by the event consumer provider.

Remarks

The __EventConsumerProviderRegistration class inherits the Provider property from __ProviderRegistration. When included in an __EventConsumerProviderRegistration instance, the Provider property specifies the name of the event consumer provider.

See Also

Registering an Event Consumer Provider, Implementing an Event Consumer Provider


__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;
};

Properties

Name
A string that uniquely identifies 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
A 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
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".

See Also

Creating an Event Filter, Permanent Event Consumers


__EventGenerator

The __EventGenerator system class is an 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.

[abstract]
class __EventGenerator : __IndicationRelated
{
};

Properties

None.

Remarks

The __EventGenerator system class is the base class for events that are neither extrinsic or intrinsic. An example of this type of event is the timer event, which is an event that occurs at a specific day and time or at a regular interval.


__EventProviderRegistration

The __EventProviderRegistration system class registers event providers with WMI.

class __EventProviderRegistration : __ProviderRegistration
{
  [key] __Provider ref provider;
  string EventQueryList[];
};

Properties

EventQueryList
One or more WQL queries that describe the events that the event provider supports.

Remarks

The __EventProviderRegistration class inherits the Provider property from __ProviderRegistration. When included in an __EventProviderRegistration instance, the Provider property specifies the name of the event provider.

See Also

Registering an Event Provider, Implementing an Event Provider


__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] __EventConsumer ref Consumer;
  [key] __EventFilter ref Filter;
  [not_null: DisableOverride ToInstance ToSubClass] boolean DeliverSynchronously = FALSE;
};

Properties

Consumer
Object path to a logical consumer, a recipient of the event. A logical consumer is an instance of a class derived from __EventConsumer.
Filter
Object path to an event filter, a query that specifies the type of event to be received.
DeliverSynchronously
Indicates whether the event should be delivered to the logical consumer synchronously or asynchronously. If it is set to TRUE, the delivery is synchronous. If it is set to FALSE, it is asynchronous. The default value is FALSE.

Remarks

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


__Group

The __Group system class is used to represent groups of users through WMI security. This class is only available in the Root\Security namespace.

[abstract]
class __Group : __Subject
{
};

Properties

None.

Remarks

The __Group system class inherits several properties from __Subject that describe the access rights for the group. These properties are:

  • Name
  • Authority
  • Enabled
  • Permissions
  • ExecuteMethods
  • EditSecurity

See Also

Security 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.


__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

None

Remarks

The TargetInstance property inherited from __InstanceOperationEvent contains a copy of the instance that was created.


__InstanceDeletionEvent

The __InstanceDeletionEvent system class represents an instance deletion event, which is a type of intrinsic event that is generated when an instance is deleted from the namespace.

class __InstanceDeletionEvent : __InstanceOperationEvent
{
};

Properties

None.

Remarks

The TargetInstance property inherited from __InstanceOperationEvent contains a copy of the instance that was deleted.


__InstanceModificationEvent

The __InstanceModificationEvent system class represents an instance modification event, which is a type of intrinsic event that is generated when an instance changes in the namespace.

class __InstanceModificationEvent : __InstanceOperationEvent
{
  object PreviousInstance;
};

Properties

PreviousInstance
Contains a copy of the instance prior to modification.

Remarks

The TargetInstance property inherited from __InstanceOperationEvent contains the new version of the changed instance. The PreviousInstance local property contains a copy of the instance before it was modified.


__InstanceOperationEvent

The __InstanceOperationEvent system class is a base class for all intrinsic events that relate to an instance.

class __InstanceOperationEvent : __Event
{
  object TargetInstance;
};

Properties

TargetInstance
The 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

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


__InstanceProviderRegistration

The __InstanceProviderRegistration system class registers instance providers with WMI.

class __InstanceProviderRegistration : __ObjectProviderRegistration
{
  [key] __Provider ref provider;
};

Properties

None.

Remarks

The __InstanceProviderRegistration class inherits several properties from its superclasses in the class hierarchy:

__ObjectProviderRegistration,

__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. When included in an __InstanceProviderRegistration instance, the Provider property specifies the name of the instance provider.

See Also

Registering Class and Instance Providers


__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

IntervalBetweenEvents
Number of milliseconds between event firings.

Remarks

The __IntervalTimerEvent system class inherits two properties from its superclass: TimerId and SkipIfPassed. The TimerId property is the key property for the class; it uniquely identifies this interval timer event. The event query entered to register for an interval timer event is usually based on the TimerId property.

The SkipIfPassed property is a Boolean value that 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 for this property is FALSE. Once WMI or the Consumer becomes available again, a notification event will be generated and received. 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 the SkipIfPassed property 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. See Permanent Event Consumers for more information.

See Also

Timer Events


__MethodProviderRegistration

The __MethodProviderRegistration system class registers method providers with WMI.

class __MethodProviderRegistration : __ProviderRegistration
{
  [key] __Provider ref provider;
};

Properties

None.

Remarks

The __MethodProviderRegistration class inherits the Provider property from the __ProviderRegistration superclass. The __ProviderRegistration class defines the Provider property. When included in a __MethodProviderRegistration instance, the Provider property specifies the name of the method provider.

See Also

Registering a Method Provider


__NamespaceCreationEvent

The __NamespaceCreationEvent system class represents a namespace creation event, which is a type of intrinsic event that is generated when a new namespace is added to the namespace.

class __NamespaceCreationEvent : __NamespaceOperationEvent
{
};

Properties

None.

Remarks

The __NamespaceCreationEvent class inherits the TargetNamespace property from its superclass, __NamespaceOperationEvent. TargetNamespace contains a copy of the __Namespace instance that was created. The Name property of the __Namespace instance indicates which namespace was created.


__NamespaceDeletionEvent

The __NamespaceDeletionEvent system class represents a namespace deletion event, which is a type of intrinsic event that is generated when a new namespace is removed from the namespace.

class __NamespaceDeletionEvent : __NamespaceOperationEvent
{
};

Properties

None.

Remarks

The __NamespaceDeletionEvent class inherits the TargetNamespace property from its superclass, __NamespaceOperationEvent. TargetNamespace contains a copy of the __Namespace instance that was deleted. The Name property of the __Namespace instance indicates which namespace was deleted.


__NamespaceModificationEvent

The __NamespaceModificationEvent system class represents a namespace modification event, which is a type of intrinsic event that is generated when a new namespace is removed from the namespace.

class __NamespaceModificationEvent : __NamespaceOperationEvent
{
  __Namespace PreviousNamespace;
};

Properties

PreviousNamespace
Contains a copy of the original version of the __Namespace instance. The Name property of this instance indicates which namespace was modified.

Remarks

The __NamespaceModificationEvent class inherits the TargetNamespace property from its superclass, __NamespaceOperationEvent. TargetNamespace contains a copy of the version of the __Namespace instance before it was modified. The Name property of this __Namespace instance indicates which namespace was modified.

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.


__NamespaceOperationEvent

The __NamespaceOperationEvent system class is a base class for all intrinsic events that relate to a namespace.

class __NamespaceOperationEvent : __Event
{
  __Namespace TargetNamespace;
};

Properties

TargetNamespace
The 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

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


__NotifyStatus

The __NotifyStatus system class is a base class that can serve as the superclass for provider-defined error classes.

[abstract: DisableOverride ToInstance ToSubClass]
class __NotifyStatus
{
  uint32 StatusCode;
};

Properties

StatusCode
Contains an error or information code for an operation. This can be any user-defined code, but the value zero 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.


__NTLMGroup

The __NTLMGroup system class is used to grant a group of users permission to access WMI. Any user belonging to a group inherits the permissions assigned to the group. The __NTLMGroup class is available on Microsoft® Windows NT®/Windows® 2000 platforms only. Instances of this class do not affect a user's permissions when logging on to a Microsoft® Windows® 95 or Windows 98 system.

class __NTLMGroup : __Subject
{
  sint32 GroupType;
};

Properties

GroupType
An enumeration indicating the type of group. Valid values are:
Value | Meaning
0 | Local group
1 | Global group

See Also

NTLM Group Support on Windows NT/Windows 2000


__NTLMUser

The __NTLMUser system class is used to grant an individual user permission to access WMI. Instances of this class have no effect during a local login to Windows 95/98 systems. They are used only to authenticate remote logins. On Windows NT/Windows 2000 systems, instances of this class participate in both local and remote logins.

class __NTLMUser : __User
{
  sint32 GroupType;
};

Properties

GroupType
An enumeration indicating the type of group. Valid values are:
Value | Meaning
0 | Local group
1 | Global group

See Also

Security Classes


__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

InteractionType
An integer that indicates whether the class or instance provider supplies its own data, or relies on WMI and the Common Information Model (CIM) repository. Valid values for this property are:
Value | Description
0 | Provider is a pull provider.
1 | Provider is a push provider.

The default value for InteractionType is 1 or 2.

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.

SupportsPut
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:
Provider type | Method to support data modification
Class providers | IWbemServices::PutClassAsync
Instance providers | IWbemServices::PutInstanceAsync

If it is set to FALSE, the provider does not support data modification and returns WBEM_E_PROVIDER_NOT_CAPABLE from PutClassAsync or PutInstanceAsync.

SupportsGet
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.
SupportsDelete
Indicates whether the provider supports data deletion. If it is set to TRUE, the provider supports class or instance deletion by implementing one of the following methods:
Provider type | Method
Class providers | IWbemServices::DeleteClassAsync
Instance providers | IWbemServices::DeleteInstanceAsync

If it is set to FALSE, the provider does not support data deletion, and returns WBEM_E_PROVIDER_NOT_CAPABLE from DeleteClassAsync or DeleteInstanceAsync.

SupportsEnumeration
Indicates whether the provider supports data enumeration. If it is set to TRUE, the provider supports data enumeration by implementing one of the following methods:
Provider type | Method
Class providers | IWbemServices::CreateClassEnumAsync
Instance providers | IWbemServices::CreateInstanceEnumAsync

If it is set to FALSE, the provider does not support data enumeration, and returns WBEM_E_PROVIDER_NOT_CAPABLE from CreateClassEnumAsync or CreateInstanceEnumAsync.

QuerySupportLevels
An array of strings that indicate the type of support for query processing that the provider includes. 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

Remarks

The __ObjectProviderRegistration inherits the Provider property from the __ProviderRegistration superclass. The Provider property specifies the name of the class or instance provider.

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.


__PARAMETERS

The __PARAMETERS system class is used to define methods and to pass input and output arguments to a method provider.

[abstract]
class __PARAMETERS
{
};

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


__PropertyProviderRegistration

The __PropertyProviderRegistration system class registers property providers with WMI .

class __PropertyProviderRegistration : __ProviderRegistration
{
  [key] __Provider ref provider;
  boolean SupportsPut = FALSE;
  boolean SupportsGet = FALSE;
};

Properties

SupportsPut
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.
SupportsGet
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.

Remarks

The __PropertyProviderRegistration class inherits the Provider property from the __ProviderRegistration superclass. When included in a __PropertyProviderRegistration instance, the Provider property specifies the name of the property provider.

See Also

Registering a Property Provider


__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

Name
A 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

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

provider
A 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

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


__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. The __SecurityRelatedClass class is available only in the Root\Security namespace.

[abstract]
class __SecurityRelatedClass
{
};

Properties

None.


__Subject

The __Subject system class is an abstract base class used to describe all types of users and groups. No instances of this class are ever created. Instances of __NTLMUser, a class that derives from a subclass of __Subject called __User, and __NTLMGroup are created to model users and groups.

[abstract]
class __Subject : __SecurityRelatedClass
{
  [key] string Name;
  [key] string Authority = ".";
  boolean Enabled = FALSE;
  sint32 Permissions;
  boolean ExecuteMethods = FALSE;
  boolean EditSecurity = FALSE;
};

Properties

Name
A string identifying the subject's full name. If the subject is a user, this is the user name. If the subject is a group, this is the group name. The combination of Name and Authority must be unique. Group names and user names occupy the same scope. Group and user names must not conflict.
Authority
Name of the domain in which the user or group is defined. A value of "." indicates that the user or group is local.
Enabled
Indicates whether the subject is active, and should be assigned permissions. If it is TRUE, the subject is considered enabled and active. If it is FALSE, the subject cannot log on. The default setting is FALSE.
Permissions
Integer value that represents the access rights for the subject. This property can be set to one of the following values:
Value | Meaning
0 | Subject has read-only access to classes and instances.
1 | Subject has read/write access to instances.
2 | Subject has read/write access to classes and instances.

ExecuteMethods
Indicates whether the subject can execute methods. If it is TRUE, the subject can execute methods. The default setting is FALSE.
EditSecurity
Indicates whether the subject has full access to the Root\Security namespace. If it is TRUE, the subject can create, modify, and delete subjects. If it is FALSE, the subject has no access to Root\Security. The default setting is FALSE.

See Also

Security 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.


__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

NumFirings
Number of times the event occurred before a notification was delivered to the consumer.
TimerId
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

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


__TimerInstruction

The __TimerInstruction system class is a 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 SkipIfPassed = FALSE;
};

Properties

TimerId
A 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.
SkipIfPassed
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 for this Boolean property is FALSE. Once WMI or the consumer becomes available again, a notification event will be generated and received. If the SkipIfPassed property is set to true, the event will not occur.

Remarks

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.


__TimerNextFiring

The __TimerNextFiring system class is a reserved class, and should not be manipulated by the user.


__User

The __User system class is an intermediate base class for representing users of various types through WMI security. Instances of this class are not created. Instances of a subclass, __NTLMUser, are created to add individual users.

This class is only available in the Root\Security namespace.

[abstract]
class __User : __Subject
{
};

Properties

None

Remarks

The __User system class inherits several properties from __Subject that describe the access rights for the user. These properties are:

  • Name
  • Authority
  • Enabled
  • Permissions
  • ExecuteMethods
  • EditSecurity

See Also

Security 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 Pure = TRUE;
};

Properties

CLSID
A GUID that represents the class identifier (CLSID) of the provider's COM object. This COM object must contain an implementation of the IWbemProviderInit interface.
ClientLoadableCLSID
Reserved for future use.
PerUserInitialization
If set to TRUE, the provider is initialized once for each actual Windows NT/Windows 2000 NTLM user making requests of the provider. If set to FALSE, the provider is initialized once for all users. The default value is FALSE.
ImpersonationLevel
Reserved for future use, and must be set to 0.
InitializeAsAdminFirst
If set to TRUE, the provider requests that it is fully initialized as "Admin" before initializations begin for users. The default value is FALSE.
InitializationReentrancy
A set of flags that provide information about serialization. A value of 0 indicates that all initialization of this provider must be serialized, a value of 1 indicates that all initializations of this provider in the same namespace must be serialized, and a value of 2 indicates that no initialization serialization is necessary.
DefaultMachineName
String that identifies the machine on which to launch the provider. If the provider runs on the local machine, it is NULL.
Pure
If set to TRUE, 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 the Remarks section that follows for more information.
UnloadTimeout
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. However, it is recommended that providers set UnloadTimeout because it will be used in future versions.

Remarks

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


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 and class instances, the properties or methods of classes and class instances, and the parameters of methods. Qualifiers are optional. They can be defined 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 is describing, as is shown in the following class declaration:

[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 predefined values have the implied value of TRUE. For example, if the Abstract qualifier is present, indicating that the class in question is abstract, it implies that Abstract is TRUE.

Windows Management Instrumentation (WMI) defines standard qualifiers, and developers can also define qualifiers. The following list describes each of the standard qualifiers. The name of the qualifier is followed by its data type and an indicator of whether the qualifier can be attached to a class, an instance, a property, or a method.

Abstract (VT_BOOL, class)
Indicates that a class cannot be instantiated. The absence of this qualifier indicates that the class is not abstract.
Association (VT_BOOL, class)
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.
Cimtype (VT_BSTR, property)
Contains text describing the type of a property. This text can be the MOF type such as "string" and "sint32", or the Common Information Model (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, except in the following two cases:
  • Reference properties have the type CIM_REFERENCE. However, 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.

  • Embedded object properties have the type CIM_OBJECT. 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 (VT_BSTR, class)
Indicates a class that has instances associated with additional information dynamically supplied by a provider.
Dynamic (VT_BOOL, class or property)
Indicates a class whose instances are dynamically created. 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 (VT_BOOL, instance)
Indicates 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 (VT_I4, property or method parameter)
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 (VT_BOOL, method)
Indicates that a method has an implementation supplied by a provider.
In (VT_BOOL, method parameter)
Indicates that a parameter is an input parameter.
In, out (VT_BOOL, method parameter)
Indicates that a parameter is both an input and an output parameter.
Indexed (VT_BOOL, property)
Requests a class property be indexed. Only the value TRUE is allowed.
InstanceContext (VT_BSTR, instance)
Indicates 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.
Key (VT_BOOL, property)
Marks a class property as a key. Only the value TRUE is allowed. A number of rules exist that determine which properties may be keys. For more information on these rules, see Key Properties.
Maxlen (VT_I4, property)
This qualifier is used to suggest the maximum number of elements that should be stored in an array.
Not_Null (VT_BOOL, property)
Indicates 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.
Out (VT_BOOL, method parameter)
Indicates that a parameter is an output parameter.
Optional (VT_BOOL, method parameter)
Indicates that a parameter is not required, and that it has a well-behaved default value.
PropertyContext (VT_BSTR, property)
Indicates 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 (VT_BSTR, class)
Indicates a class's 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.
Read (VT_BOOL, property)
Indicates that a property is read-only.
Singleton (VT_BOOL, class)
Designates a class that can only have one instance and that does not contain key properties. Only the value TRUE is allowed.
Static (VT_BOOL, method)
Indicates that a method can only be called using the class definition. The method cannot be invoked from an instance.
Subtype (VT_BSTR, property)
Indicates that a property of type CIM_DATETIME represents a time interval rather than a specific time. The value of this qualifier must be "interval" to identify the property as an interval. All other values for this qualifier are reserved for future use.
Values (VT_BSTR array, property)
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.
ValueMap (VT_BSTR array, property)
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, and the corresponding property must be an integer. For more information, see MOF Enumerations.
Write (VT_BOOL, property)
Indicates that a property is read/write.


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) CString. It is provided for implementers who do not wish to program with MFC.


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 IWbemClassObject interface.


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

Framework providers should not call this method to commit. Instead, they should call Provider::Commit.


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 GetMethodContext, but if it does, it is responsible for releasing the IWbemClassObject pointer by calling its Release method.


CInstance::GetDateTime

The GetDateTime method returns a date/time property.

bool GetDateTime(
  LPCWSTR name,
  WBEMTime& wbemtime
) const;

Parameters

name
Name of the date/time property retrieved.
wbemtime
Buffer to receive the date/time 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 date/time 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 type that is DOUBLE-compatible 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 type that is CInstance-compatible 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 will probably never call GetMethodContext , but if they do, they are responsible for releasing the MethodContext pointer by calling its Release method.


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. More information is available in the log file, Framework.log.


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 timespan.

bool GetTimeSpan(
  LPCWSTR name,
  WBEMTimeSpan& wbemtimespan
) const;

Parameters

name
Name of the timespan property retrieved.
wbemtimespan
Buffer to receive the timespan property.

Return Values

Returns TRUE if the operation was successful and FALSE if the supplied timespan 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(
  const CHString& name,
  __int64& wbemint64
) const;
bool GetWBEMINT64(
  const CHString& name,
  unsigned __int64& wbemint64
) const;

Parameters

name
Name of the 64-bit integer property retrieved.
wbemint64
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);


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.


CInstance::SetDOUBLE

The SetDOUBLE method sets a WORD 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 timespan 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 timespan 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 __int64 wbemint64
);
bool SetWBEMINT64(
  LPCWSTR name,
  const unsigned __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
Address of the new CHString instance.
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.


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
);

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 for version 1 of the provider framework.

Return Values

Use the SUCCEEDED or FAILED macros on the returned HRESULT to determine if the method was successful.

Remarks

After the instance has been committed, the pInstance pointer must not be deleted. If the client cancels the query, the Commit method will return an error. A provider writer can use this fact to terminate an enumeration.


Provider::CreateNewInstance

The CreateNewInstance method allocates a new CInstance object and returns a pointer to it. The user must call Release on the returned CInstance pointer unless the pointer is included in a call to Commit. This is a helper function and should not be overridden.

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 either calling Relase or Commit on the returned CInstance pointer.


Provider::DeleteInstance

The DeleteInstance method deletes an instance.

HRESULT DeleteInstance(
  const CInstance& Instance,
  long lFlags
);

Parameters

Instance
Instance to be deleted.
lFlags
A bitmask of flags with information about the delete operation. Currently, lFlags must be set to zero (0).

Return Values

Provider::DeleteInstance returns WBEM_E_PROVIDER_NOT_CAPABLE.

Remarks

Framework providers that allow instances to be deleted must override this method. See IWbemServices::DeleteInstance for information about deleting instances.


Provider::EnumerateInstances

The EnumerateInstances method retrieves all instances of a framework provider's class.

HRESULT EnumerateInstances(
  MethodContext *pMethodContext,
  long lFlags
);

Parameters

pMethodContext
Pointer to the method context wrapper passed by WMI in a previous call.
lFlags
A bitmask of flags providing information about the operation. Currently, lFlags is reserved and must be zero (0).

Return Values

Returns WBEM_E_PROVIDER_NOT_CAPABLE.

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

The ExecMethod method invokes a method on a class or instance.

HRESULT ExecMethod(
  const CInstance& Instance,
  const BSTR bstrMethodName,
  CInstance *pInParams,
  CInstance *pOutParams,
  long lFlags
);

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
Reserved; this parameter must be set to zero (0).

Return Values

Returns WBEM_E_PROVIDER_NOT_CAPABLE.

Framework providers that override this method can return WBEM_S_NO_ERROR on success, one of the following codes on failure, or any other HRESULT error:

Return code | Description
WBEM_E_ACCESS_DENIED | Security or file open problem.
WBEM_E_OUT_OF_MEMORY | Lack of memory.
WBEM_E_NOT_FOUND | Request made for data that does not exist.
WBEM_E_INVALID_PARAMETER | Invalid value for a parameter or property was specified.
WBEM_E_VALUE_OUT_OF_RANGE | Request was made with an out-of-range value.
WBEM_E_READ_ONLY | Request was made to make a change to read-only data.
WBEM_E_FAILED | Operation failed.

Remarks

Framework method providers must override this method and supply their own implementation. See IWbemServices::ExecMethod for more information.


Provider::ExecQuery

The ExecQuery method processes a WQL query.

HRESULT ExecQuery(
  MethodContext *pMethodContext,
  CFrameworkQuery& Query,
  long lFlags
);

Parameters

pMethodContext
Pointer to the current method context.
Query
Pointer to a query that has already been parsed by the provider framework.
lFlags
A bitmask of flags providing information about the query operation. At present, lFlags is reserved and must be zero (0).

Return Values

Returns WBEM_E_PROVIDER_NOT_CAPABLE.

Framework providers that override this method can return WBEM_S_NO_ERROR on success, one of the following codes on failure, or any other HRESULT error:

Return code | Description
WBEM_E_ACCESS_DENIED | Security or file open problem.
WBEM_E_OUT_OF_MEMORY | Lack of memory.
WBEM_E_NOT_FOUND | Request made for data that does not exist.
WBEM_E_INVALID_PARAMETER | Invalid value for a parameter or property was specified.
WBEM_E_VALUE_OUT_OF_RANGE | Request was made with an out-of-range value.
WBEM_E_FAILED | Operation failed.

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, which in turn calls CreateInstanceEnum to filter out the instances.


Provider::Flush

The Flush method deletes all unnecessary memory usage (including the cache) when it is implemented in the class object.

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.

Version 1 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 an object path to a specified instance. GetLocalInstancePath is a helper function and cannot be overridden.

bool GetLocalInstancePath(
  const CInstance *pInstance,
  CHString& strPath
);

Parameters

pInstance
Pointer to the instance that the path should be built for.
strPath
Newly built object path.

Return Values

Returns TRUE if the operation was successful and FALSE if the operation was unsuccessful.


Provider::GetObject

The GetObject method retrieves an instance of a class.

HRESULT GetObject(
  CInstance *pInstance,
  long lFlags
);

Parameters

pInstance
Pointer to a CInstance object to be filled in by the framework provider.
lFlags
A bitmask of flags that indicate information about the operation. Currently, lFlags is reserved and must be zero (0).

Return Values

If successful, the method returns WBEM_S_NO_ERROR. If unsuccessful, the method returns one of the following codes.

Return code | Description
WBEM_E_ACCESS_DENIED | Security or file open problem.
WBEM_E_OUT_OF_MEMORY | Lack of memory.
WBEM_E_NOT_FOUND | Request made for data that does not exist.
WBEM_E_INVALID_PARAMETER | Invalid value for a parameter or property was specified.
WBEM_E_VALUE_OUT_OF_RANGE | Request was made with an out-of-range value.
WBEM_E_FAILED | Operation failed.

Remarks

Framework providers must override this method. Provider::GetObject provides an instance with only the key properties. The provider version of GetObject must fill in all of the other properties.


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 local path.

Return Values

Returns the local 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
);

Parameters

newInstance
Instance that is updated.
lFlags
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

Provider::PutInstance returns WBEM_E_PROVIDER_NOT_CAPABLE.

Framework providers that override this method can return WBEM_S_NO_ERROR on success, one of the following codes on failure, or any other HRESULT error:

Return code | Description
WBEM_E_ACCESS_DENIED | Security or file open problem
WBEM_E_OUT_OF_MEMORY | Lack of memory.
WBEM_E_NOT_FOUND | Request made for data that does not exist.
WBEM_E_INVALID_PARAMETER | Invalid parameter or property value was specified.
WBEM_E_VALUE_OUT_OF_RANGE | Request was made with an out-of-range value.
WBEM_E_READ_ONLY | Request was made to make a change to read-only data.
WBEM_E_FAILED | Operation failed.

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 constant 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 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.

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 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.

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 enum 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 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 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.

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 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.

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 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 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.

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.


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 * is specified as one of the fields, it is returned in the same way as all other properties. Since

SELECT *, Name FROM Win32_BIOS

is a valid query, this class will actually return the "*" character as one of the elements of the string array.


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.


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.


CFrameworkQuery::GetValuesForProp

The GetValuesForProp method returns all of the values for a particular property specified in a query.

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

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.

Remarks

Given a property name, this method returns all of the result values in a CHStringArray or BSTR array. 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.


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(
  const CHString& 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.


CWbemProviderGlue::FillInstance

The FillInstance method retrieves the non-key property values for an instance supported by another provider.

HRESULT FillInstance(
  CInstance *pInstance,
  LPCTSTR pszNamespace
);

HRESULT FillInstance(
  MethodContext *pMethodContext,
  CInstance *pInstance
);

Parameters

pInstance
Pointer to the instance that is supplied with property values.
pszNamespace
Pointer to the namespace of the instance. This parameter can be NULL to indicate the default namespace.
pMethodContext
Pointer to the current method context.

Return Values

Return Code | Description
WBEM_S_NO_ERROR | The operation was successful.
WBEM_E_INVALID_CLASS | The class of the instance pointed to by pInstance was invalid.

Remarks

FillInstance allows framework providers to access data from other providers without having to make a WMI API call. Framework providers pass an instance to FillInstance with only the key property values specified. FillInstance locates the correct provider for the instance and calls that provider to supply the rest of the property values.


CWbemProviderGlue::FrameworkLoginDLL

The FrameworkLoginDLL method is called when DLL_PROCESS_ATTACH is sent to DllMain to determine whether the provider server can be loaded.

BOOL CWbemProviderGlue::FrameworkLoginDLL(
  const CHString& 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.

BOOL CWbemProviderGlue::FrameworkLogoffDLL(
  const CHString& 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 WbemProviderGlue is zero. This approach prevents unloading any client DLL while instances of WbemProviderGlue still exist.


CWbemProviderGlue::GetAllDerivedInstances

The GetAllDerivedInstances method retrieves a list of instances derived from a particular base class.

HRESULT GetAllDerivedInstances(
  LPCTSTR pszBaseClassName,
  TRefPointerCollection<CInstance> *pList,
  MethodContext *pMethodContext,
  LPCTSTR 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
Pointer to the namespace of the provider responsible for the class specified by pszBaseClassName.

Return Values

The method returns WBEM_S_NO_ERROR if the operation was successful and WBEM_E_OUT_OF_MEMORY if the operation failed due to lack of memory.

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.

The return codes include all the possible returns from IWbemServices::ExecQuery.


CWbemProviderGlue::GetAllDerivedInstancesAsynch

The GetAllDerivedInstancesAsynch method retrieves a list of instances supported by a particular provider and derived from a particular base class. GetAllDerivedInstancesAsynch allows the provider to respond asynchronously by returning one instance at a time.

HRESULT WINAPI GetAllDerivedInstancesAsynch(
  LPCTSTR pszProviderName,
  Provider *pRequester,
  LPProviderInstanceCallback pCallback,
  LPCTSTR pszNamespace,
  MethodContext *pMethodContext,
  void* pUserData
);

Parameters

pszProviderName
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 pszProviderName.
pszNamespace
Namespace of the provider specified by pszProviderName. This parameter can be NULL to indicate the current namespace.
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

Return Code | Description
WBEM_E_INVALID_CLASS | The class supported by the provider specified in pszProviderName is invalid.
WBEM_E_OUT_OF_MEMORY | The operation failed due to lack of memory.
WBEM_S_NO_ERROR | The operation was successful.

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.


CWbemProviderGlue::GetAllInstances

The GetAllInstances method retrieves a list of instances supported by a particular provider.

HRESULT GetAllInstances(
  LPCTSTR pszProviderName,
  TRefPointerCollection<CInstance> *pList,
  LPCTSTR pszNamespace,
  MethodContext *pMethodContext
);

Parameters

pszProviderName
Name of provider for which list should be returned.
pList
Linked list of instances supported by the provider specified by pszProviderName.
pszNamespace
Namespace of the provider specified by pszProviderName. 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

Return code | Description
WBEM_S_NO_ERROR | The operation was successful.
WBEM_E_INVALID_CLASS | The class supported by the provider specified in pszProviderName is invalid.
WBEM_E_OUT_OF_MEMORY | The operation failed due to lack of memory.

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.


CWbemProviderGlue::GetAllInstancesAsynch

The GetAllInstancesAsynch method retrieves a list of instances supported by a particular provider. GetAllInstancesAsynch allows the provider to respond asynchronously by returning one instance at a time.

HRESULT GetAllInstancesAsync(
  LPCTSTR pszProviderName,
  Provider *pRequester,
  LPProviderInstanceCallback pCallback,
  LPCTSTR pszNamespace,
  MethodContext *pMethodContext,
  void *pUserData
);

Parameters

pszProviderName
Name of provider for which list 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 pszProviderName.
pszNamespace
Namespace of the provider specified by pszProviderName. This parameter can be NULL to indicate the current namespace.
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

Return code | Description
WBEM_E_INVALID_CLASS | The class supported by the provider specified in pszProviderName is invalid.
WBEM_E_OUT_OF_MEMORY | The operation failed due to lack of memory.
WBEM_S_NO_ERROR | The operation was successful.

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 *).


CWbemProviderGlue::GetEmptyInstance

The GetEmptyInstance method retrieves a single instance from a particular provider. None of the properties of the instance are supplied.

HRESULT WINAPI GetEmptyInstance(
  MethodContext *pMethodContext,
  LPCTSTR pszProviderName,
  CInstance **ppInstance,
  LPCSTR pszNamespace = NULL
);
HRESULT WINAPI GetEmptyInstance(
  LPCTSTR pszProviderName,
  CInstance **ppInstance,
  LPCSTR pszNamespace = NULL
);

Parameters

pMethodContext
A pointer to the current context.
pszProviderName
Name of provider supporting the instance 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 provider specified by pszProviderName. This parameter can be NULL to indicate the current namespace.

Return Values

Return code | Description
WBEM_S_NO_ERROR | The operation was successful.
WBEM_E_OUT_OF_MEMORY | The operation failed due to lack of memory.
WBEM_E_FAILED | The operation failed due to a problem other than lack of memory.

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.


CWbemProviderGlue::GetFrameworkVersion

The GetFrameworkVersion method returns the product version of the provider framework server (FRAMEDYN.DLL).

CHString GetFrameworkVersion();

Parameters

None.

Return Values

The method returns the product version of the framework provider server FRAMEDYN.DLL, which is the DLL that implements the methods in the Provider Framework Classes. It also implements the methods in the Provider Framework Utility Classes.

Note The WMI SDK also installs Framedyd.dll, the debug version of Framedyn.dll. Programmers who are writing new providers may prefer to work with this debug version. The CimWin32 providers load the retail version, Framedyn.dll.

Remarks

This information is taken directly from the file version information resource.


CWbemProviderGlue::GetInstanceByPath

The GetInstanceByPath method retrieves an instance identified by a particular object path.

HRESULT WINAPI GetInstanceByPath(
  LPCTSTR pszInstancePath,
  CInstance **ppInstance,
  MethodContext *pMethodContext
);

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 CInstance 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

Return code | Description
WBEM_S_NO_ERROR | The operation was successful.
WBEM_E_INVALID_PARAMETER | The operation failed because one or more parameters were invalid.
WBEM_E_FAILED | The operation failed due to a problem other than an invalid parameter.

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.

For version 1.0 of the provider framework, pszInstancePath must point to a local path. In fact, the path must not only be on the same computer, the path must also be in the same namespace.


CWbemProviderGlue::GetInstancesByQuery

The GetInstancesByQuery method retrieves a list of instances that match a particular query.

HRESULT WINAPI GetInstancesByQuery(
  LPCTSTR Query,
  TRefPointerCollection<CInstance> *pList,
  MethodContext *pMethodContext,
  LPCTSTR pszNamespace
);

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. This parameter can be NULL to indicate the default namespace.

Return Values

The method returns WBEM_S_NO_ERROR if the operation was successful and WBEM_E_FAILED if the operation failed.

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.

HRESULT WINAPI GetInstancesByQueryAsynch(
  LPCTSTR query,
  Provider *pRequester,
  LPProviderInstanceCallback pCallback,
  LPCTSTR pszNamespace,
  MethodContext *pMethodContext,
  void *pUserData );

Parameters

query
The query to be executed.
pRequester
The "This" pointer for the callback function pointed to by pCallback.
pCallback
Pointer to a function that is called to return each instance specified by query.
pszNamespace
Namespace for query. This parameter can be NULL to indicate the current namespace.
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_E_OUT_OF_MEMORY if the operation failed due to lack of memory and WBEM_S_NO_ERROR if the operation was successful.

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.

bool IsDerivedFrom(
  LPCTSTR pszBaseClassName,
  LPCTSTR pszDerivedClassName,
  MethodContext *pMethodContext,
  LPCTSTR 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.


Provider Framework Utility Classes

The provider framework utility library, Utillib.lib, implements several provider helper classes.

Utility class | Description
WBEMTime | Facilitates conversions between various Windows® NT/Windows® 2000 and ANSI C runtime time formats.
WBEMTimeSpan | Contains helper functions used to calculate and hold the time span difference between two WBEMTime objects.

framedyd.dll implements these methods in the debug build, and framedyn.dll implements them in the release build.

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 CIM datetime format:

yyyymmddHHMMSS.mmmmmmsUUU

BSTRs returned by WBEMTime methods are in CIM 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 only 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 Windows NT®/Windows® 2000 and ANSI C runtime time formats. See also WBEMTimeSpan Class Methods.


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::WBEMTime

The WBEMTime class constructor facilitates conversions between various Windows NT/Windows 2000 and ANSI C runtime 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 MSDN 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 CIM time format.


WBEMTime::operator=

The WBEMTime class assignment operators have been overloaded to facilitate conversions between various Windows NT/Windows 2000 and ANSI C runtime time formats.

const WBEMTime& operator=(
  const time_t& t
);
const WBEMTime& operator=(
  const struct tm tmin
);

Parameters

t
An ANSI C time_t structure that holds time values.
tmin
An ANSI C tm structure that holds time values representing the number of seconds since 1970.


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 another object's time.

const WBEMTime& operator+(
  const WBEMTime& uAdd
);

Parameters

uAdd
A reference to the WBEMTime object, whose time will be added to the specified object.


WBEMTime::operator-

The WBEMTime class subtraction operator has been overloaded to decrement an object's time by another object's time.

const WBEMTime& operator-(
  const WBEMTime& uSubtract
);

Parameters

uSubtract
A reference to the WBEMTime object, whose time will be subtracted from the specified object.


WBEMTime Comparison Operators

The WBEMTime comparison operators (== < <= > >=) have been overloaded to compare two WBEMTime objects..

BOOL operator==(
  const WBEMTime& uTarget
);
BOOL operator!=(
  const WBEMTime& uTarget
);
BOOL operator<(
  const WBEMTime& uTarget
);
BOOL operator<=(
  const WBEMTime& uTarget
);
BOOL operator>(
  const WBEMTime& uTarget
);
BOOL operator>=(
  const WBEMTime& uTarget
);

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::GetBSTR

The GetBSTR method presents the time as a BSTR in WMI time format.

BSTR GetBSTR(void) throw (CHeap_Exception);

Parameters

None.

Return Values

The method returns a BSTR in CIM time format. The time is given as GMT. If the internal time value is INVALID_TIME, the BSTR will be set to zero.

Remarks

The calling function must call SysFreeString on the return value.

See Also

WBEMTime::GetDMTF


WBEMTime::GetDMTF

The GetDMTF method gets the time as a BSTR in CIM time format.

BSTR GetDMTF(
  BOOL bLocal = FALSE
) throw (CHeap_Exception);

Parameters

bLocal
If TRUE, returns the local time, adjusted for daylight savings time; otherwise, returns GMT.

Return Values

A BSTR in WMI time format.

Remarks

The calling function must call SysFreeString on the return value.

See Also

WBEMTime::GetBSTR, WBEMTime::SetDMTF


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.


WBEMTime::GetStructtm

The GetStructtm method gets the time as an ANSI C runtime struct tm structure.

BOOL GetStructtm(
  struct tm *ptm
);

Parameters

ptm
An ANSI C runtime struct tm structure.

Return Values

The method returns TRUE if the time is valid and FALSE if the time is invalid.


WBEMTime::GetSYSTEMTIME

The GetSYSTEMTIME method gets the time as an MFC SYSTEMTIME structure.

BOOL GetSYSTEMTIME(
  SYSTEMTIME *pst
);

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 and FALSE if the time is invalid.


WBEMTime::Gettime_t

The Gettime_t method gets the time as an ANSI C runtime time_t variable.

BOOL Gettime_t(
  time_t *ptm
);

Parameters

ptm
An ANSI C runtime 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 time is valid and FALSE if the time is invalid.


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 CIM time format.

BOOL SetDMTF(
  const BSTR wszText
);

Parameters

wszText
A BSTR in WMI time format.

Return Values

The method returns TRUE if the time is valid and FALSE if the time is invalid.

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.

See also WBEMTime Class Methods.


WBEMTimeSpan::WBEMTimeSpan

The WBEMTimeSpan class constructor creates and holds a time span.

WBEMTimeSpan();
WBEMTimeSpan(
  int iDays,
  int iHours,
  int iMinutes,
  int iSeconds,
  int iMSec=0,
  int iUSec=0,
  int iNSec=0
);
WBEMTimeSpan(
  const time_t& t
);
WBEMTimeSpan(
  const FILETIME& ft
);
WBEMTimeSpan(
  BSTR bstrWBEMFormat
);

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.
t
An ANSI C runtime long integer that holds time values.
ft
The MFC FILETIME structure, a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601.
bstrWBEMFormat
A BSTR in CIM time format.


WBEMTimeSpan::operator=

The WBEMTimeSpan class assignment operators have been overloaded to facilitate conversions between various Windows NT/Windows 2000 and ANSI C runtime time formats.

const WBEMTimeSpan& operator=(
  const time_t& t
);
const WBEMTimeSpan& operator=(
  const FILETIME& ft
);
const WBEMTimeSpan& operator=(
  BSTR bstrWBEMFormat
);

Parameters

t
An ANSI C runtime long integer that holds time values.
ft
The MFC FILETIME structure, a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601.
bstrWBEMFormat
A BSTR in CIM time 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 third object returned by the method.

WBEMTimeSpan& operator+(
  const WBEMTimeSpan& uAdd
);

Parameters

uAdd
A reference to the 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 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::GetBSTR

The GetBSTR method gets the time span as a BSTR in WMI time span format.

BSTR GetBSTR();

Parameters

None.

Return Values

A BSTR in CIM interval format. The time is given in nanoseconds.

Remarks

The calling function must call SysFreeString on the return value.


WBEMTimeSpan::GetFILETIME

The GetFILETIME method gets the time as an MFC FILETIME structure, that is, a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601.

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.


WBEMTimeSpan::Gettime_t

The Gettime_t method gets the time as an ANSI C runtime time_t variable.

BOOL GetStructtm(
  time_t *ptm
);

Parameters

ptm
An ANSI C runtime time_t variable, which represents the number of seconds since 1970.

Return Values

The method returns TRUE if the time is valid and FALSE if the time is invalid.


WBEMTimeSpan::IsOk

The IsOk method indicates whether the WBEMTimeSpan object represents a valid time span.

BOOL IsOk();

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 reference documents the application programming interface (API) components for the Windows Management Instrumentation (WMI) Component Object Model (COM). Using the API components covered following, 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 the Microsoft® Visual C++® development system version 5.0 and later. 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.
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.
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 optionally is implemented by event providers that expose information on the kinds of event query filters that are currently active, in order to optimize performance.
IWbemLocator | This interface obtains the initial pointer to the IWbemServices interface for WMI on a specific host computer.
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.
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.
IWbemServices | This is the primary interface to WMI . It provides management services to client processes and to other providers.
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.


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.

Methods in Vtable Order

IUnknown Methods | Description
QueryInterface | Determines if the current object supports a given interface.
AddRef | Increases the object's reference count by 1.
Release | Decrements the object's reference count by 1, and frees the object when the reference count is zero.

IEnumWbemClassObject Methods | Description
Reset | Resets an enumeration sequence back to the beginning.
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.
Clone | Makes a copy of the enumerator.
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.


IEnumWbemClassObject::QueryInterface

The IEnumWbemClassObject::QueryInterface method determines if the object supports a particular COM interface. If it does, the system increases the object's reference count, and the application can use that interface immediately. The QueryInterface method allows the extension of objects without interfering with the existing or future functionality of the objects.

HRESULT QueryInterface(
  [in] REFIID riid,
  [out] LPVOID *ppv
);

Parameters

riid
The COM interface identifier of the requested interface.
ppv
Address of a pointer that is filled with the interface pointer if the query succeeds.

Return Values

Returns standard COM error codes for QueryInterface. It returns WBEM_S_NO_ERROR if the call succeeds. If the call fails because the requested interface is not supported, the method returns E_NOINTERFACE.

Remarks

This method will return a pointer to the requested interface if it is supported. You must call the Release method to free the resources associated with this interface when it is no longer needed.

This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

Iunknown Interface Basics


IEnumWbemClassObject::AddRef

The IEnumWbemClassObject::AddRef method increases the object's reference count by 1.

ULONG AddRef( );

Parameters

None.

Return Values

Returns the new reference count.

Remarks

When the object is created, its reference count is set to 1. Every time an application obtains an interface to the object, or calls the AddRef method, the object's reference count is increased by 1. Use the Release method to decrease the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For a complete discussion of IUnknown methods, see IUnknown Programming Basics.

For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IEnumWbemClassObject::Release

The IEnumWbemClassObject::Release method decreases the object's reference count by 1.

ULONG Release( );

Parameters

None.

Return Values

Returns the new reference count.

Remarks

The object deallocates itself when its reference count reaches zero. Use the AddRef method to increase the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


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

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.


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(
  [in] LONG lTimeOut,
  [in] ULONG uCount,
  [out, size_is(uCount) length_is(*puReturned)] IWbemClassObject **ppObjects,
  [out] ULONG *puReturned
);

Parameters

lTimeOut
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
The number of requested objects.
ppObjects
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 interface pointers that are received when they are no longer needed.
puReturned
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

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 timeout 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.

In the following sample, since objects are only requested one at a time, checking the return code for WBEM_S_NO_ERROR is correct:

void ListObjects(
    IEnumWbemClassObject *pEnum,
    IWbemObjectSink *pSink
    )
{
    HRESULT hRes;

    while (1)
    {
        hRes = pEnum->NextAsync(5, pSink);

    if (hRes == WBEM_S_FALSE)
        break;

    // Objects are being delivered via another thread to <pSink>

    // ... do other work

    // continue

    }
}

In the next sample, Next may return WBEM_S_FALSE, even though some objects are returned. You need to check uReturned:

void ListObjects2(IEnumWbemClassObject *pEnum)
{
    pEnum->Reset();

    IWbemClassObject *paObjects[10];
    ULONG uReturned;
    HRESULT hRes;

    while (1)
    {
        hRes = pEnum->Next(INFINITE, 10, paObjects, &uReturned);

        if (uReturned == 0)
            break;

        for (ULONG u = 0; u < uReturned; u++)
        {
            IWbemClassObject *pObj = paObjects[u];

            // ... use the object

            pObj->Release();
        }

    }

    // examine hRes to see if the termination finished normally
}


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(
  [in] ULONG uCount,
  [in] IWbemObjectSink *pSink
);

Parameters

uCount
The number of objects being requested.
pSink
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

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.

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. This is followed by a call to IWbemObjectSink::SetStatus with a value of WBEM_S_FALSE, or the error code if an error occurred. If there are no available objects, Indicate is not called. However, a final call to IWbemObjectSink::SetStatus will always occur to indicate the status of the entire operation.

If fewer objects are available than the number requested, IWbemObjectSink::Indicate is called for those objects that are available. This is followed by a call to IWbemObjectSink::SetStatus with a value of WBEM_S_FALSE, or the error code if an error occurred

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;
    }
}


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(
  [out] IEnumWbemClassObject **ppEnum
);

Parameters

ppEnum
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

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;
}


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(
  [in] LONG lTimeOut,
  [in] ULONG UCount
);

Parameters

lTimeOut
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
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

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.


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.

Methods in Vtable Order

IUnknown Methods | Description
QueryInterface | Determines if the current object supports a given interface.
AddRef | Increases the object's reference count by 1.
Release | Decrements the object's reference count by 1, and frees the object when the reference count is zero.

IWbemCallResult Methods | Description
GetResultObject | Returns an IWbemClassObject; which is the result of a semisynchronous call to IWbemServices::GetObject.
GetResultString | Returns an Object Path; which is the result of a semisynchronous call to IWbemServices::PutInstance.
GetResultServices | Returns the result of a semisynchronous call to IWbemServices::OpenNamespace verb action.
GetCallStatus | Reports whether a semisynchronous call was successful.


IWbemCallResult::QueryInterface

The IWbemCallResult::QueryInterface method determines if the object supports a particular COM interface. If it does, the system increases the object's reference count, and the application can use the returned interface pointer immediately. The QueryInterface method allows the extension of objects without interfering with the existing or future functionality of the objects

HRESULT IWbemCallResult::QueryInterface(
  [in] REFIID riid,
  [out] LPVOID *ppv
);

Parameters

riid
The COM interface identifier of the requested interface.
ppv
Address of a pointer that will be filled with the interface pointer if the query succeeds.

Return Values

Returns standard COM error codes for QueryInterface. It returns WBEM_S_NO_ERROR if the call succeeds. If the call fails because the requested interface was not supported, it returns E_NOINTERFACE.

Note DCOM-specific error codes may also be returned if network problems cause you to lose the remote connection to Windows Management.

Remarks

This method will return a pointer to the requested interface if it is supported. You must call the Release method to free the resources associated with this interface when it is no longer needed.

This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemCallResult::AddRef

The IWbemCallResult::AddRef method increases the object's reference count by 1.

ULONG AddRef( );

Parameters

None.

Return Values

Returns the new reference count.

Remarks

Every time an application obtains an interface to the object or calls the AddRef method, the object's reference count increases by 1. Use the Release method to decrease the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For a complete discussion of IUnknown methods, see IUnknown Programming Basics.

For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemCallResult::Release

The IWbemCallResult::Release method decreases the object's reference count by 1.

ULONG Release( );

Parameters

None.

Return Values

Returns the new reference count.

Remarks

The object deallocates itself when its reference count reaches zero. Use the AddRef method to increase the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


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(
  [in] LONG lTimeout,
  [out] IWbemClassObject **ppResultObject
);

Parameters

lTimeout
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
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

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.

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(
  [in] LONG lTimeout,
  [out] BSTR *pstrResultString
);

Parameters

lTimeout
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
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

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.

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(
  [in] LONG lTimeout,
  [out] IWbemServices **ppServices
);

Parameters

lTimeout
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
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 Release on the returned object when it is no longer required.

On error, a new object is not returned.

Return Values

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.

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(
  [in] LONG lTimeout,
  [out] LONG *plStatus
);

Parameters

lTimeout
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
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

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.

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.

Methods in Vtable Order

IUnknown Methods | Description
QueryInterface | Determines if this object supports WMI interfaces.
AddRef | Increases the object's reference count by 1.
Release | Decrements the reference count by 1 and frees the object when the reference count is zero.

IWbemClassObject Methods | Description
GetQualifierSet | Allows access to the qualifier set of the entire object.
Get | Gets a particular property value.
Put | Updates or creates a particular property value.
Delete | Removes the specified property from the object.
GetNames | Obtains a list of the names of the properties in the object.
BeginEnumeration | Begins an enumeration of the properties.
Next | Obtains the next property in an enumeration after an initial call to BeginEnumeration.
EndEnumeration | Ends an enumeration begun with BeginEnumeration.
GetPropertyQualifierSet | Allows access to the qualifiers of a particular property.
Clone | Makes a copy of the current object.
GetObjectText | Obtains the textual rendition of the object in Managed Object Format (MOF) syntax.
SpawnDerivedClass | Creates a new derived class from the current class.
SpawnInstance | Creates a new instance from the current class.
CompareTo | Tests two objects for equality.
GetPropertyOrigin | Reports the class in which a particular property was introduced.
InheritsFrom | Reports whether the current object inherits from a particular class.
GetMethod | Gets the in- and out-parameter definitions for a specific CIM method.
PutMethod | Creates a CIM method.
DeleteMethod | Removes a CIM method.
BeginMethodEnumeration | Begins an enumeration of CIM methods for the object.
NextMethod | Retrieves the next CIM method definition in an enumeration of methods.
EndMethodEnumeration | Ends the enumeration of CIM methods for an object.
GetMethodQualifierSet | Returns the qualifier set object for a specific CIM method.
GetMethodOrigin | Reports the class in which a CIM method is defined.


IWbemClassObject::QueryInterface

The IWbemClassObject::QueryInterface method determines if the object supports a particular COM interface. If it does, the system increases the object's reference count, and the application can use that interface immediately. The QueryInterface method allows the extension of objects without interfering with the existing or future functionality of the objects.

HRESULT IWbemClassObject::QueryInterface(
  [in] REFIID riid,
  [out] LPVOID *ppv
);

Parameters

riid
The COM interface identifier of the requested interface.
ppv
Address of a pointer that is filled with the interface pointer if the query succeeds.

Return Values

Returns standard COM error codes for QueryInterface. It returns WBEM_S_NO_ERROR if the call succeeds. If the requested interface is not supported this call will fail and return E_NOINTERFACE.

Remarks

This method will return a pointer to the requested interface if it is supported. You must call the Release method to free the resources associated with this interface when it is no longer needed. This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemClassObject::AddRef

The IWbemClassObject::AddRef method increases the object's reference count by 1.

ULONG AddRef( );

Parameters

None.

Return Values

Returns the new reference count.

Remarks

When you create the object, its reference count is set to 1. Every time an application obtains an interface to the object or calls the AddRef method, the object's reference count increases by 1. Use the Release method to decrease the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For a complete discussion of IUnknown methods, see IUnknown Programming Basics.

For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemClassObject::Release

The IWbemClassObject::Release method decreases the object's reference count by 1.

ULONG IWbemClassObject::Release( );

Parameters

None.

Return Values

Returns the new reference count.

Remarks

The object deallocates itself when its reference count reaches zero. Use the AddRef method to increase the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


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(
  [out] IWbemQualifierSet **ppQualSet
);

Parameters

ppQualSet
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

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.

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(
  [in] BSTR strName,
  [in] LONG lFlags,
  [out, OPTIONAL] VARIANT *pVal,
  [out, OPTIONAL] CIMTYPE *pvtType,
  [out, OPTIONAL] LONG *plFlavor
);

Parameters

strName
The desired property name. This must point to a valid BSTR. It is treated as read-only.
lFlags
Reserved. It must be zero.
pVal
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), 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
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, etc. This indicates the CIM semantics of the property value packed into the VARIANT.
plFlavor
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.

Return Values

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" vs. 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 );

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 the IWbemClassObject points to a CIM class definition, Put will either create or update the property value. When the 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(
  [in] BSTR strName,
  [in] LONG lFlags,
  [in] VARIANT *pVal,
  [in] CIMTYPE vtType
);

Parameters

strName
Must point to a valid BSTR containing the property name. The pointer is treated as read-only. This cannot be NULL.
lFlags
Reserved. It must be zero.
pVal
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
Type of VARIANT pointed to by pVal.

Note 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 pointer is treated as read-only. The caller is responsible for invoking VariantClear after this call is complete.

vtType
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

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 exists in the superclass, its default value is changed unless it is a type mismatch. 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, it might be necessary 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.

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);


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(
  [in] BSTR strName
);

Parameters

strName
The property name to delete. This must point to a valid BSTR. It is treated as read-only.

Return Values

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_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.

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(
  [in] BSTR strQualifierName,
  [in] LONG lFlags,
  [in] VARIANT *pQualifierValue,
  [out] SAFEARRAY (BSTR) *pstrNames
);

Parameters

strQualifierName
Can be NULL. If not NULL, it must point to a valid BSTR specifying a qualifier name which acts as part of a filter. This is treated as read-only. See Remarks.
lFlags
See Remarks.
pQualifierValue
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
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

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.

See Also

IWbemClassObject::Get, System Properties, IWbemClassObject::BeginEnumeration


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(
  [in] LONG lEnumFlags
);

Parameters

lEnumFlags
A combination of flags described in Remarks.

Return Values

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 with out 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.

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(
  [in] LONG lFlags,
  [out, OPTIONAL] BSTR *pstrName,
  [out, OPTIONAL] VARIANT *pVal,
  [out, OPTIONAL] CIMTYPE *pvtType,
  [out, OPTIONAL] LONG *plFlavor
);

Parameters

lFlags
Reserved. It must be zero.
pstrName
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
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
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
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

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.

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

WBEM_E_FAILED | There has been a general failure.
WBEM_S_NO_ERROR | The call succeeded.

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(
  [in] BSTR strProperty,
  [out] IWbemQualifierSet **ppQualSet
);

Parameters

strProperty
The property for which the qualifier set is requested. This must point to a valid BSTR, 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
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

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.

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(
  [out] IWbemClassObject **ppCopy
);

Parameters

ppCopy
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

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.


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(
  [in] LONG lFlags,
  [out] BSTR *pstrObjectText
);

Parameters

lFlags
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 an class or instance declaration will be omitted from the MOF text. These flags may be combined.
pstrObjectText
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

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.

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(
  [in] LONG lFlags,
  [out] IWbemClassObject **ppNewClass
);

Parameters

lFlags
Reserved. It must be zero.
ppNewClass
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

WBEM_E_FAILED | There has been a general failure.
WBEM_E_ILLEGAL_OPERATION | An illegal 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.

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 not supported.

HRESULT IWbemClassObject::SpawnInstance(
  [in] LONG lFlags,
  [out] IWbemClassObject **ppNewInstance
);

Parameters

lFlags
Reserved. It must be zero.
ppNewInstance
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

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.

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(
  [in] LONG lFlags,
  [in] IWbemClassObject *pCompareTo
);

Parameters

lFlags
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
The object in comparison. This pointer must point to a valid IWbemClassObject instance. It cannot be NULL.

Return Values

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.

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(
  [in] BSTR strName,
  [out] BSTR *pstrClassName
);

Parameters

strName
The property name for which the owning class name is desired. This must point to a valid BSTR, which is treated as read-only.
pstrClassName
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

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.

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(
  [in] BSTR strAncestor
);

Parameters

strAncestor
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 BSTR, which is treated as read-only.

Return Values

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.

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(
  [in] BSTR Name,
  [in] LONG lFlags,
  [out] IWbemClassObject **ppInSignature,
  [out] IWbemClassObject **ppOutSignature
);

Parameters

Name
The CIM method name. Must point to a valid BSTR, which is treated as read-only.
lFlags
Reserved. It must be zero.
ppInSignature
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. See Notes.
ppOutSignature
Receives an IWbemClassObject pointer which describes the out-parameters to the method. This parameter will be ignored if set to NULL.

Return Values

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 a single property containing Parm3.

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.

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(
  [in] BSTR Name,
  [in] LONG lFlags,
  [in] IWbemClassObject *pInSignature,
  [in] IWbemClassObject *pOutSignature
);

Parameters

Name
The method name which is being created.
lFlags
Reserved. It must be zero.
pInSignature
Points to an IWbemClassObject containing the in-parameters for the method. This parameter will be ignored if set to NULL.
pOutSignature
Points to an IWbemClassObject containing the out-parameters for the object. This parameter will be ignored if set to NULL.

Return Values

WBEM_S_NO_ERROR | The call was successful.
WBEM_E_INVALID_PARAMETER | One or more parameters was invalid.
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.

Note The caller is responsible for calling IWbemClassObject::Release on the ppInSignature and ppOutSignature pointers when these objects are no longer needed.

See Also

IWbemClassObject::GetMethod


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(
  [in] BSTR Name
);

Parameters

Name
The method name to be removed from the class definition.

Return Values

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.

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(
  [in] LONG lEnumFlags
);

Parameters

lEnumFlags
Reserved. It must be zero.

Return Values

WBEM_E_INVALID_PARAMETER | A non-zero flag value was used.
WBEM_S_NO_ERROR | The call succeeded.

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(
  [in] LONG lFlags,
  [out, OPTIONAL] BSTR *pName,
  [out, OPTIONAL] IWbemClassObject **ppInSignature,
  [out, OPTIONAL] IWbemClassObject **ppOutSignature
);

Parameters

lFlags
Reserved. It must be zero.
pName
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
Receives a pointer to an IWbemClassObject containing the in-parameters for the method.
ppOutSignature
Receives a pointer to an IWbemClassObject containing the out-parameters for the method.

Return Values

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.


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

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.


IWbemClassObject::GetMethodQualifierSet

This is used to terminate 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(
  [in] BSTR Method,
  [out] IWbemQualifierSet **ppQualSet
);

Parameters

Method
Must point to a valid BSTR containing the method name.
ppQualSet
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

WBEM_E_NOT_FOUND | The method did not exist.
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.


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(
  [in] BSTR strMethodName,
  [out] BSTR *pstrClassName
);

Parameters

strMethodName
The name of the method for the object whose owning class is being requested.
pstrClassName
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

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.


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 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.

Methods in Vtable Order

IUnknown Methods | Description
QueryInterface | Determines if the current object supports a given interface.
AddRef | Increases the object's reference count by 1.
Release | Decrements the object's reference count, and frees the object when the reference count is zero.

IWbemContext Methods | Description
Clone | Makes a complete copy of the current IWbemContext object.
GetNames | Retrieves the names of all of the context values available.
BeginEnumeration | Begins an enumeration of all context values in the IwbemContext object.
Next | Retrieves the next value in an enumeration of all context values beginning with BeginEnumeration.
EndEnumeration | Ends an enumeration begun with BeginEnumeration and Next.
SetValue | Sets a specific named context value.
GetValue | Retrieves the specified context value by name.
DeleteValue | Removes the specified context value.
DeleteAll | Removes all context values, making the IWbemContext object empty.


IWbemContext::QueryInterface

The IWbemContext::QueryInterface method determines if the object supports a particular COM interface. If it does, the system increases the object's reference count, and the application can use that interface immediately. The QueryInterface method allows the extension of objects without interfering with the existing or future functionality of the objects

HRESULT IWbemContext::QueryInterface(
  [in] REFIID riid,
  [out] LPVOID *ppv
);

Parameters

riid
The COM interface identifier of the requested interface.
ppv
Address of a pointer that will be filled with the interface pointer if the query succeeds.

Return Values

Returns standard COM error codes for QueryInterface. It returns WBEM_S_NO_ERROR if the call succeeds. If the call fails because the requested interface was not supported, the method returns E_NOINTERFACE.

Remarks

This method will return a pointer to the requested interface if it is supported. You must call the Release method to free the resources associated with this interface when it is no longer needed. This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemContext::AddRef

The IWbemContext::AddRef method increases the object's reference count by 1.

ULONG AddRef( );

Parameters

None.

Return Values

Returns the new reference count.

Remarks

When the object is created, its reference count is set to 1. Every time an application obtains an interface to the object or calls the AddRef method, the object's reference count is increased by 1. Use the Release method to decrease the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For a complete discussion of IUnknown methods, see IUnknown Programming Basics Interface.

For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemContext::Release

The IWbemContext::Release method decreases the object's reference count by 1.

ULONG Release( );

Parameters

None.

Return Values

Returns the new reference count.

Remarks

The object deallocates itself when its reference count reaches zero. Use the AddRef method to increase the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


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(
  [out] IWbemContext **ppNewCopy
);

Parameters

ppNewCopy
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 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

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.


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(
  [in] LONG lFlags,
  [out] SAFEARRAY (BSTR) *pNames
);

Parameters

lFlags
Reserved. It must be zero.
pNames
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

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.

See Also

IWbemContext::GetValue, IWbemContext::BeginEnumeration


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(
  [in] LONG lFlags
);

Parameters

lFlags
Reserved. It must be zero.

Return Values

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 with out an intervening call to IWbemContext::EndEnumeration
WBEM_E_FAILED | There has been a general failure.

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(
  [in] LONG lFlags,
  [out] BSTR *pstrName,
  [out] VARIANT *pValue
);

Parameters

lFlags
Reserved. It must be zero.
pstrName
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
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

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.

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

WBEM_S_NO_ERROR | The call succeeded.
WBEM_E_UNEXPECTED | This call was made without a corresponding call to IwbemContext::BeginEnumeration.

See Also

IWbemContext::BeginEnumeration, IWbemContext::Next


IWbemContext::SetValue

The IWbemContext::SetValue method creates or overwrites a named context value.

HRESULT SetValue(
  [in] BSTR strName,
  [in] LONG lFlags,
  [in] VARIANT *pValue
);

Parameters

strName
Cannot be NULL. It is a read-only pointer to a valid BSTR indicating the context value name.
lFlags
Reserved. It must be zero.
pValue
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.

Return Values

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.

See Also

IWbemContext::GetValue


IWbemContext::GetValue

The IWbemContext::GetValue method is used to retrieve a specific named context value by name.

HRESULT GetValue(
  [in] BSTR strName,
  [in] LONG lFlags,
  [out] VARIANT *pValue
);

Parameters

strName
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
Reserved. It must be zero.
pValue
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

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.

See Also

IWbemContext::SetValue


IWbemContext::DeleteValue

The IWbemContext::DeleteValue method deletes a named context value created by IWbemContext::SetValue.

HRESULT DeleteValue(
  [in] BSTR strName,
  [in] LONG lFlags
);

Parameters

strName
A pointer to a valid BSTR containing the named context value to delete. The pointer is treated as read-only.
lFlags
Reserved. It must be zero.

Return Values

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.

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

WBEM_E_FAILED | There has been a general failure.
WBEM_S_NO_ERROR | The call succeeded.

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.

Methods in Vtable Order

IUnknown Methods | Description
QueryInterface | Determines if the current object supports a given interface.
AddRef | Increases the object's reference count by 1.
Release | Decrements the object's reference count and frees the object when the reference count is zero.

IWbemEventConsumer Provider Methods | Description
FindConsumer | Called by Windows Management to retrieve an IwbemUnboundObjectSink for a particular logical consumer.


IWbemEventConsumerProvider::QueryInterface

The IWbemEventConsumerProvider::QueryInterface method determines if the object supports a particular COM interface. If it does, the system increases the object's reference count, and the application can use that interface immediately. The QueryInterface method allows the extension of objects without interfering with the existing or future functionality of the objects.

HRESULT IWbemEventConsumerProvider::QueryInterface(
  [in] REFIID riid,
  [out] LPVOID *ppv
);

Parameters

riid
The COM interface identifier of the requested interface.
ppv
Address of a pointer that will be filled with the interface pointer if the query succeeds.

Return Values

Returns standard COM error codes for QueryInterface. It returns WBEM_S_NO_ERROR if the call succeeds. If the call fails because the requested interface was not supported, the method returns E_NOINTERFACE.

Remarks

This method will return a pointer to the requested interface if it is supported. You must call the Release method to free the resources associated with this interface when it is no longer needed. This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemEventConsumerProvider::AddRef

The IWbemEventConsumerProvider::AddRef method increases the object's reference count by 1.

ULONG AddRef( );

Parameters

None.

Return Values

Returns the new reference count.

Remarks

When the object is created, its reference count is set to 1. Every time an application obtains an interface to the object or calls the AddRef method, the object's reference count is increased by 1. Use the Release method to decrease the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For a complete discussion of IUnknown methods, see IUnknown Programming Basics.

For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemEventConsumerProvider::Release

The IWbemEventConsumerProvider::Release method decreases the object's reference count by 1.

ULONG IWbemEventProvider::Release( );

Parameters

None.

Return Values

Returns the new reference count.

Remarks

The object deallocates itself when its reference count reaches zero. Use the AddRef method to increase the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


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(
  [in] IWbemClassObject *pLogicalConsumer,
  [out] IWbemUnboundObjectSink **ppConsumer
);

Parameters

pLogicalConsumer
A pointer to the logical consumer object to which the event objects are to be delivered.
ppConsumer
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 timeout, Windows Management will call Release for the pointer.

Return Values

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 IWbemClassObjects 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.

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.

Methods in Vtable Order

Iunknown Methods | Description
QueryInterface | Determines if the current object supports a given interface.
AddRef | Increases the object's reference count by 1.
Release | Decrements the object's reference count, and frees the object when the reference count is zero.

IWbemEventProvider Methods | Description
ProvideEvents | Called by WMI to command the provider to start delivering its events to WMI.


IWbemEventProvider::QueryInterface

The IWbemEventProvider::QueryInterface method determines if the object supports a particular COM interface. If it does, the system increases the object's reference count, and the application can use that interface immediately. The QueryInterface method allows the extension of objects without interfering with the existing or future functionality of the objects.

HRESULT IWbemEventProvider::QueryInterface(
  [in] REFIID riid,
  [out] LPVOID *ppv
);

Parameters

riid
The COM interface identifier of the requested interface.
ppv
Address of a pointer that will be filled with the interface pointer if the query succeeds.

Return Values

Returns standard COM error codes for QueryInterface. It returns WBEM_S_NO_ERROR if the call succeeds. If the call fails because the requested interface was not supported, the method returns E_NOINTERFACE.

Remarks

This method will return a pointer to the requested interface if it is supported. You must call the Release method to free the resources associated with this interface when it is no longer needed. This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemEventProvider::AddRef

The IWbemEventProvider::AddRef method increases the object's reference count by 1.

ULONG AddRef( );

Parameters

None.

Return Values

Returns the new reference count.

Remarks

When the object is created, its reference count is set to 1. Every time an application obtains an interface to the object or calls the AddRef method, the object's reference count is increased by 1. Use the Release method to decrease the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For a complete discussion of IUnknown methods, see IUnknown Programming Basics.

For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemEventProvider::Release

The IWbemEventProvider::Release method decreases the object's reference count by 1.

ULONG IWbemEventProvider::Release( );

Parameters

None.

Return Values

Returns the new reference count.

Remarks

The object deallocates itself when its reference count reaches zero. Use the AddRef method to increase the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemEventProvider::ProvideEvents

Windows Management calls this method to signal an event provider to begin delivery of its events.

HRESULT IWbemEventProvider::ProvideEvents(
  [in] IWbemObjectSink *pSink,
  [in] long lFlags
);

Parameters

pSink
A pointer to the object sink to which the provider will deliver its events.
lFlags
Reserved. It must be zero.

Return Values

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.


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.

Methods in Vtable Order

Iunknown Methods | Description
QueryInterface | Determines if the current object supports a given interface.
AddRef | Increases the object's reference count by 1.
Release | Decrements the object's reference count, and frees the object when the reference count is zero.

IWbemEventProviderQuerySink Methods | Description
NewQuery | Called whenever a new consumer query is registered with WMI.
CancelQuery | Called whenever a consumer query is canceled or unregistered.


IWbemEventProviderQuerySink::QueryInterface

The IWbemEventProviderQuerySink::QueryInterface method determines if the object supports a particular COM interface. If it does, the system increases the object's reference count, which means the application can use that interface immediately. The QueryInterface method allows the extension of objects without interfering with the existing or future functionality of the objects.

HRESULT IWbemEventProviderQuerySink::QueryInterface(
  [in] REFIID riid,
  [out] LPVOID *ppv
);

Parameters

riid
The COM interface identifier of the requested interface.
ppv
Address of a pointer that will be filled with the interface pointer if the query succeeds.

Return Values

Returns standard COM error codes for QueryInterface. It returns WBEM_S_NO_ERROR if the call succeeds. If the call fails because the requested interface was not supported, the method returns E_NOINTERFACE.

Remarks

This method will return a pointer to the requested interface if it is supported. You must call the Release method to free the resources associated with this interface when it is no longer needed. This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemEventProviderQuerySink::AddRef

The IWbemEventProviderQuerySink::AddRef method increases the object's reference count by 1.

ULONG AddRef( );

Parameters

None.

Return Values

Returns the new reference count.

Remarks

When the object is created, its reference count is set to 1. Every time an application obtains an interface to the object or calls the AddRef method, the object's reference count is increased by 1. Use the Release method to decrease the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For a complete discussion of IUnknown methods, see IUnknown Programming Basics.

For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemEventProviderQuerySink::Release

The IWbemEventProviderQuerySink::Release method decreases the object's reference count by 1.

ULONG IWbemEventProviderQuerySink::Release( );

Parameters

None.

Return Values

Returns the new reference count.

Remarks

The object deallocates itself when its reference count reaches zero. Use the AddRef method to increase the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemEventProviderQuerySink::NewQuery

Call this method whenever a logical event consumer registers a relevant event query filter with Windows Management.

HRESULT IWbemEventProviderQuerySink::NewQuery(
  [in] unsigned long dwId,
  [in] WBEM_WSTR wszQueryLanguage,
  [in] WBEM_WSTR wszQuery
);

Parameters

dwId
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
The language of the following query filter. For this version of WMI, it will always be "WQL."
wszQuery
The text of the event query filter, which was registered by a logical consumer.

Return Values

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."

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(
  [in] unsigned long dwId
);

Parameters

dwId
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

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.

See Also

IWbemEventProviderQuerySink::NewQuery


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.

Methods in Vtable Order

IUnknown Methods | Description
QueryInterface | Determines if the current object supports a given interface.
AddRef | Increases the object's reference count by 1.
Release | Decrements the object's reference count, and frees the object when the reference count is zero.

IWbemLocator Methods | Description
ConnectServer | Connects to Windows Management on the specified machine.


IWbemLocator::QueryInterface

The IWbemLocator::QueryInterface method determines if the object supports a particular COM interface. If it does, the system increases the object's reference count, and the application can use that interface immediately. The QueryInterface method allows the extension of objects without interfering with the existing or future functionality of the objects.

HRESULT IWbemLocator::QueryInterface(
  [in] REFIID riid,
  [out] LPVOID *ppv
);

Parameters

riid
The COM interface identifier of the requested interface.
ppv
Address of a pointer that will be filled with the interface pointer if the query succeeds.

Return Values

Returns standard COM error codes for QueryInterface. It returns WBEM_S_NO_ERROR if the call succeeds. If the call fails because the requested interface was not supported, the method returns E_NOINTERFACE.

Remarks

This method will return a pointer to the requested interface if it is supported. You must call the Release method to free the resources associated with this interface when it is no longer needed. This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemLocator::AddRef

The IWbemLocator::AddRef method increases the object's reference count by 1.

ULONG AddRef( );

Parameters

None.

Return Values

Returns the new reference count.

Remarks

When the object is created, its reference count is set to 1. Every time an application obtains an interface to the object or calls the AddRef method, the object's reference count is increased by 1. Use the Release method to decrease the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For a complete discussion of IUnknown methods, see IUnknown Programming Basics.

For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemLocator::Release

The IWbemLocator::Release method decreases the object's reference count by 1.

ULONG Release( );

Parameters

None.

Return Values

Returns the new reference count.

Remarks

The object deallocates itself when its reference count reaches zero. Use the AddRef method to increase the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemLocator::ConnectServer

The IWbemLocator::ConnectServer method connects to Windows Management on the machine specified in the strNetworkResource parameter. This is typically a Microsoft® Windows NT®/Windows® 2000 machine, or a Microsoft® Windows® 95/98 target with WMI installed.

HRESULT IWbemLocator::ConnectServer(
  [in] const BSTR strNetworkResource,
  [in] const BSTR strUser,
  [in] const BSTR strPassword,
  [in] const BSTR strLocale,
  [in] LONG lSecurityFlags,
  [in] const BSTR strAuthority,
  [in] IWbemContext *pCtx,
  [out] IWbemServices **ppNamespace
);

Parameters

strNetworkResource
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
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");

strPassword
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, i.e. "", specifies a valid zero length password.
strLocale
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\\0x409" (C++ requires two backslashes because the first is considered an escape character).

The string format is required since WMI accommodates other localization schemes besides Microsoft 32-bit LCIDs, such as ISO 639 or RFC 1766.

lSecurityFlags
Reserved. This must be zero.
strAuthority
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: NTLMDOMAIN:<domain name>.
pCtx
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
Receives a pointer to an IWbemServices object bound to the specified namespace. This pointer has a positive reference count. The caller must call 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

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_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.

Note These error return codes are defined in the wbemcli.h file in the WMI SDK Include folder.

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.

See Also

IWbemServices


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.

Methods in Vtable Order

IUnknown Methods | Description
QueryInterface | Determines if the current object supports a given interface.
AddRef | Increases the object's reference count by 1.
Release | Decrements the object's reference count, and frees the object when the reference count is zero.

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;
}


IWbemObjectSink::QueryInterface

The IWbemObjectSink::QueryInterface method determines if the object supports a particular COM interface. If it does, the system increases the object's reference count, and the application can use that interface immediately. The QueryInterface method allows the extension of objects without interfering with the existing or future functionality of the objects.

HRESULT IWbemObjectSink::QueryInterface(
  [in] REFIID riid,
  [out] LPVOID *ppv
);

Parameters

riid
The COM interface identifier of the requested interface.
ppv
Address of a pointer that will be filled with the interface pointer if the query succeeds.

Return Values

Returns standard COM error codes for QueryInterface. It returns WBEM_S_NO_ERROR if the call succeeds. If the call fails because the requested interface was not supported, the method returns E_NOINTERFACE.

Remarks

This method will return a pointer to the requested interface if it is supported. You must call the Release method to free the resources associated with this interface when it is no longer needed. This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemObjectSink::AddRef

The IWbemObjectSink::AddRef method increases the object's reference count by 1.

ULONG AddRef( );

Parameters

None.

Return Values

Returns the new reference count.

Remarks

When the object is created, its reference count is set to 1. Every time an application obtains an interface to the object or calls the AddRef method, the object's reference count is increased by 1. Use the Release method to decrease the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For a complete discussion of IUnknown methods, see IUnknown Programming Basics.

For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemObjectSink::Release

The IWbemObjectSink::Release method decreases the object's reference count by 1.

ULONG Release( );

Parameters

None.

Return Values

Returns the new reference count.

Remarks

The object deallocates itself when its reference count reaches zero. Use the AddRef method to increase the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


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(
  [in] LONG lObjectCount,
  [in, size_is(lObjectCount)] IWbemClassObject **ppObjArray
);

Parameters

lObjectCount
The number of objects in the following array of pointers.
ppObjArray
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

WBEM_E_FAILED | The receiver was not able to process the notification properly.
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.


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(
  [in] LONG lFlags,
  [in] HRESULT hResult,
  [in] BSTR strParam,
  [in] IWbemClassObject *pObjParam
);

Parameters

lFlags
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
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
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 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

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.


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.

Methods in Vtable Order

IUnknown Methods | Description
QueryInterface | Determines if the current object supports a given interface.
AddRef | Increases the object's reference count by 1.
Release | Decrements the object's reference count and frees the object when the reference count is zero.

IWbemPropertyProvider Methods | Description
GetProperty | Called by Windows Management to retrieve a property value.
PutProperty | Called by Windows Management to write a property value.


IWbemPropertyProvider::QueryInterface

The IWbemPropertyProvider::QueryInterface method determines if the object supports a particular COM interface. If it does, the system increases the object's reference count, and the application can use that interface immediately. The QueryInterface method allows the extension of objects without interfering with the existing or future functionality of the objects.

HRESULT IWbemPropertyProvider::QueryInterface(
  [in] REFIID riid,
  [out] LPVOID *ppv
);

Parameters

riid
The COM interface identifier of the requested interface.
ppv
Address of a pointer that will be filled with the interface pointer if the query succeeds.

Return Values

Returns standard COM error codes for QueryInterface. It returns WBEM_S_NO_ERROR if the call succeeds. If the call fails because the requested interface was not supported, the method returns E_NOINTERFACE.

Remarks

This method will return a pointer to the requested interface if it is supported. You must call the Release method to free the resources associated with this interface when it is no longer needed. This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemPropertyProvider::AddRef

The IWbemPropertyProvider::AddRef method increases the object's reference count by 1.

ULONG AddRef( );

Parameters

None.

Return Values

Returns the new reference count.

Remarks

When the object is created, its reference count is set to 1. Every time an application obtains an interface to the object or calls the AddRef method, the object's reference count is increased by 1. Use the Release method to decrease the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For a complete discussion of IUnknown methods, see IUnknown Programming Basics.

For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemPropertyProvider::Release

The IWbemPropertyProvider::Release method decreases the object's reference count by 1.

ULONG Release( );

Parameters

None.

Return Values

Returns the new reference count.

Remarks

The object deallocates itself when its reference count reaches zero. Use the AddRef method to increase the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemPropertyProvider::GetProperty

The IWbemPropertyProvider::GetProperty method is called by Windows Management to retrieve an individual property value.

HRESULT IWbemPropertyProvider::GetProperty(
  [in] long lFlags,
  [in] const BSTR strLocale,
  [in] const BSTR strClassMapping,
  [in] const BSTR strInstMapping,
  [in] const BSTR strPropMapping,
  [out] VARIANT *pvValue
);

Parameters

lFlags
Reserved. It must be zero.
strLocale
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
A string identifying the class to which the property belongs. This must point to a valid BSTR, which is treated as read-only.
strInstMapping
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.
strPropMapping
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.
pvValue
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.

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(
  [in] long lFlags,
  [in] const BSTR strLocale,
  [in] const BSTR strClassMapping,
  [in] const BSTR strInstMapping,
  [in] const BSTR strPropMapping,
  [in] VARIANT *pvValue
);

Parameters

lFlags
Reserved. It must be zero.
strLocale
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
A string indicating the CIM class to which the property to be written belongs. It must point to a valid BSTR, which is treated as read-only.
strInstMapping
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.
strPropMapping
A literal copy of the value of the PROPERTYCONTEXT qualifier for the property. It will point to a valid BSTR, which must be treated as read-only.
pvValue
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.

See Also

GetProperty


IWbemProviderInit

The IWbemProviderInit interface is called by Windows Management to initialize providers. All providers are required to implement IWbemProviderInit.

Methods in Vtable Order

IUnknown Methods | Description
QueryInterface | Determines if the current object supports a given interface.
Addref | Increases the object's reference count by 1.
Release | Decrements the object's reference count by 1, and frees the object when the reference count is zero.

IWbemProviderInit Methods | Description
Initialize | Called by Windows Management to initialize a provider.


IWbemProviderInit::QueryInterface

The IWbemProviderInit::QueryInterface method determines if the object supports a particular COM interface. If it does, the system increases the object's reference count, and the application can use that interface immediately. The QueryInterface method allows the extension of objects without interfering with the existing or future functionality of the objects.

HRESULT IWbemProviderInit::QueryInterface(
  [in] REFIID riid,
  [out] LPVOID *ppv
);

Parameters

riid
The COM interface identifier of the requested interface.
ppv
Address of a pointer that will be filled with the interface pointer if the query succeeds.

Return Values

Returns standard COM error codes for QueryInterface. It returns WBEM_S_NO_ERROR if the call succeeds. If the call fails because the requested interface was not supported, the method returns E_NOINTERFACE.

Remarks

This method will return a pointer to the requested interface if it is supported. You must call the Release method to free the resources associated with this interface when it is no longer needed. This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK..

See Also

IUnknown Interface Basics


IWbemProviderInit::AddRef

The IWbemProviderInit::AddRef method increases the object's reference count by 1.

ULONG AddRef( );

Parameters

None.

Return Values

Returns the new reference count.

Remarks

When the object is created, its reference count is set to 1. Every time an application obtains an interface to the object or calls the AddRef method, the object's reference count is increased by 1. Use the Release method to decrease the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For a complete discussion of IUnknown methods, see IUnknown Programming Basics.

For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemProviderInit::Release

The IWbemProviderInit::Release method decreases the object's reference count by 1.

ULONG IWbemProviderInit::Release( );

Parameters

None.

Return Values

Returns the new reference count.

Remarks

The object deallocates itself when its reference count reaches zero. Use the AddRef method to increase the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


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(
  [in, unique, string] LPWSTR wszUser,
  [in] LONG lFlags,
  [in, string] LPWSTR wszNamespace,
  [in, unique, string] LPWSTR wszLocale,
  [in] IWbemServices *pNamespace,
  [in] IWbemContext *pCtx,
  [in] IWbemProviderInitSink *pInitSink
);

Parameters

wszUser
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
Reserved. It must be zero.
wszNamespace
The namespace name for which the provider is being initialized.
wszLocale
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\\0x409"

pNamespace
An IWbemServices pointer back into Windows Management. This pointer is capable of servicing any requests made by the provider. The provider should use the AddRef method on this pointer if it is going to need to call back into Windows Management during its execution.
pCtx
An IWbemContext pointer associated with initialization. If the provider needs to make requests back into Windows Management before completing initialization, it should use the AddRef method on this pointer. This pointer must be passed by the provider in all future IWbemServices calls that it makes to Windows Management. For more information, see Making Calls to WMI.
pInitSink
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 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.

See Also

Initializing a Provider


IWbemProviderInitSink

The IWbemProviderInitSink interface is exported by Windows Management and called by the provider during the initialization sequence.

Methods in Vtable Order

IUnknown Methods | Description
QueryInterface | Determines if the current object supports a given interface.
Addref | Increases the object's reference count by 1.
Release | Decrements the object's reference count by 1, and frees the object when the reference count is zero.

IWbemProviderInitSink Methods | Description
SetStatus | Called by the provider to indicate success or failure of initialization.


IWbemProviderInitSink::QueryInterface

The IWbemProviderInitSink::QueryInterface method determines if the object supports a particular COM interface. If it does, the system increases the object's reference count, and the application can use that interface immediately. The QueryInterface method allows the extension of objects without interfering with the existing or future functionality of the objects.

HRESULT IWbemProviderInitSink::QueryInterface(
  [in] REFIID riid,
  [out] LPVOID *ppv
);

Parameters

riid
The COM interface identifier of the requested interface.
ppv
Address of a pointer that will be filled with the interface pointer if the query succeeds.

Return Values

Returns standard COM error codes for QueryInterface. It returns WBEM_S_NO_ERROR if the call succeeds. If the call fails because the requested interface was not supported, the method returns E_NOINTERFACE.

Remarks

This method will return a pointer to the requested interface if it is supported. You must call the Release method to free the resources associated with this interface when it is no longer needed. This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemProviderInitSink::AddRef

The IWbemProviderInitSink::AddRef method increases the object's reference count by 1.

ULONG AddRef( );

Parameters

None.

Return Values

Returns the new reference count.

Remarks

When the object is created, its reference count is set to 1. Every time an application obtains an interface to the object or calls the AddRef method, the object's reference count is increased by 1. Use the Release method to decrease the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For a complete discussion of IUnknown methods, see IUnknown Programming Basics.

For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemProviderInitSink::Release

The IWbemProviderInitSink::Release method decreases the object's reference count by 1.

ULONG IWbemProviderInitSink::Release( );

Parameters

None.

Return Values

Returns the new reference count.

Remarks

The object deallocates itself when its reference count reaches zero. Use the AddRef method to increase the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemProviderInitSink::SetStatus

The IWbemProviderInitSink::SetStatus method indicates to Windows Management whether a provider is fully or partially initialized.

HRESULT IWbemProviderInitSink::SetStatus(
  [in] LONG lStatus,
  [in] LONG lFlags
);

Parameters

lStatus
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
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.

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.

Methods in Vtable Order

Iunknown Methods | Description
QueryInterface | Determines if the current object supports a given interface.
AddRef | Increases the object's reference count by 1.
Release | Decrements the reference count by 1 and frees the object when the reference count is zero.

IWbemQualifierSet Methods | Description
Get | Reads a particular named qualifier.
Put | Writes a particular named qualifier.
Delete | Deletes the specified named qualifier.
GetNames | Gets the names of qualifiers subject to certain filters.
BeginEnumeration | Resets prior to an enumeration of all qualifiers.
Next | Gets the next qualifier during an enumeration of all qualifiers.
EndEnumeration | Ends an enumeration of qualifiers.


IWbemQualifierSet::QueryInterface

The IWbemQualifierSet::QueryInterface method determines if the object supports a particular COM interface. If it does, the system increases the object's reference count, and the application can use that interface immediately. The QueryInterface method allows the extension of objects without interfering with the existing or future functionality of the objects.

HRESULT IWbemQualifierSet::QueryInterface(
  [in] REFIID riid,
  [out] LPVOID *ppv
);

Parameters

riid
The COM interface identifier of the requested interface.
ppv
Address of a pointer to be filled with the interface pointer if the query succeeds.

Return Values

Returns standard COM error codes for QueryInterface. It returns WBEM_S_NO_ERROR if the call succeeds. If the call fails because the requested interface is not supported, the method returns E_NOINTERFACE.

Remarks

This method will return a pointer to the requested interface if it is supported. You must call the Release method to free the resources associated with this interface when it is no longer needed. This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK.SDK.

See Also

IUnknown Interface Basics


IWbemQualifierSet::AddRef

The IWbemQualifierSet::AddRef method increases the object's reference count by 1.

ULONG AddRef( );

Parameters

None.

Return Values

Returns the new reference count.

Remarks

When the object is created, its reference count is set to 1. Every time an application obtains an interface to the object or calls the AddRef method, the object's reference count is increased by 1. Use the Release method to decrease the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For a complete discussion of IUnknown methods, see IUnknown Programming Basics.

For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemQualifierSet::Release

The IWbemQualifierSet::Release method decreases the object's reference count by 1.

ULONG IWbemQualifierSet::Release( );

Parameters

None.

Return Values

Returns the new reference count.

Remarks

The object deallocates itself when its reference count reaches zero. Use the AddRef method to increase the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemQualifierSet::Get

The IWbemQualifierSet::Get method gets the specified named qualifier, if found.

HRESULT IWbemQualifierSet::Get(
  [in] BSTR strName,
  [in] LONG lFlags,
  [out, OPTIONAL] VARIANT *pVal,
  [out, OPTIONAL] LONG *plFlavor
);

Parameters

strName
The qualifier name for which the value is being requested. This must point to a valid BSTR. The pointer is treated as read-only.
lFlags
Reserved. It must be zero.
pVal
When successful, the 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
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

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.

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(
  [in] BSTR strName,
  [in] VARIANT *pVal,
  [in] LONG lFlavor
);

Parameters

strName
The name of the qualifier that is being written. This must point to a valid BSTR. The pointer is treated as read-only.
pVal
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
The desired qualifier flavor for this qualifier. See Qualifier Flavors.

Not required if the qualifier is the key qualifier.

Return Values

WBEM_E_CANNOT_BE_KEY | 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_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.

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.

See Qualifier Flavors.

HRESULT IWbemQualifierSet::Delete(
  [in] BSTR strName
);

Parameters

strName
The name of the qualifier to delete. This must be a valid BSTR. The pointer is treated as read-only.

Return Values

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.

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(
  [in] LONG lFlags,
  [out] SAFEARRAY (BSTR) *pstrNames
);

Parameters

lFlags
One of the following constants:
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
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

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.

See Also

IWbemQualifierSet::Get, IWbemQualifierSet::BeginEnumeration


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(
  [in] LONG lFlags
);

Parameters

lFlags
Specifies the qualifiers to include in the enumeration. It must be one of the following constants:
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

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 with out an intervening call to IWbemQualifierSet::EndEnumeration
WBEM_S_NO_ERROR | The call succeeded.

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(
  [in] LONG lFlags,
  [out, OPTIONAL] BSTR *pstrName,
  [out, OPTIONAL] VARIANT *pVal,
  [out, OPTIONAL] LONG *plFlavor
);

Parameters

lFlags
Reserved. It must be zero.
pstrName
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
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
If not NULL, the value pointed to is set to the qualifier flavor. See Qualifier Flavors.

Return Values

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.

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. We recommend this call, but it is not required. It immediately releases resources associated with the enumeration.

HRESULT IWbemQualifierSet::EndEnumeration( );

Parameters

None.

Return Values

WBEM_S_NO_ERROR The call succeeded.

See Also

IWbemQualifierSet::BeginEnumeration, IWbemQualifierSet::Next


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);

Methods in Vtable Order

IUnknown Methods | Description
QueryInterface | Determines if the current object supports a given interface.
Addref | Increases the object's reference count by 1.
Release | Decrements the reference count by 1 and frees the object when the reference count is zero.

IWbemServices Methods | Description
OpenNamespace | Opens a particular child namespace for operations.
CancelAsyncCall | Cancels a currently executing asynchronous call.
QueryObjectSink | Allows the caller to obtain a notification handler sink.
GetObject | Retrieves an object, whether an instance or class definition.
GetObjectAsync | Asynchronously retrieves an object (an instance or class definition).
PutClass | Creates or updates a class definition.
PutClassAsync | Asynchronously creates or updates a class definition.
DeleteClass | Deletes a class.
DeleteClassAsync | Deletes a class and receives confirmation asynchronously.
CreateClassEnum | Creates a class enumerator.
CreateClassEnumAsync | Creates a class enumerator that executes asynchronously.
PutInstance | Creates or updates an instance of a particular class.
PutInstanceAsync | Asynchronously creates or updates an instance of a particular class.
DeleteInstance | Deletes a particular instance of a class.
DeleteInstanceAsync | Deletes an instance and provides confirmation asynchronously.
CreateInstanceEnum | Creates an instance enumerator.
CreateInstanceEnumAsync | Creates an instance enumerator that executes asynchronously.
ExecQuery | Executes a query to retrieve classes or instances.
ExecQueryAsync | Executes a query to retrieve classes or instances asynchronously.
ExecNotificationQuery | Executes a query to receive events.
ExecNotificationQueryAsync | Executes a query to receive events asynchronously.
ExecMethod | Executes an object method.
ExecMethodAsync | Executes an object method asynchronously.


IWbemServices::QueryInterface

The IWbemServices::QueryInterface method determines whether the object supports a particular COM interface. If it does, the system increases the object's reference count, and the application can use that interface immediately. The QueryInterface method allows the extension of objects without interfering with the existing or future functionality of the objects.

HRESULT IWbemServices::QueryInterface(
  [in] REFIID riid,
  [out] LPVOID *ppv
);

Parameters

riid
The COM interface identifier of the requested interface.
ppv
Address of a pointer that is filled with the interface pointer if the query succeeds.

Return Values

Returns standard COM error codes for QueryInterface. It returns WBEM_S_NO_ERROR if the call succeeds. If the call fails because there is no support for the requested interface, 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.

Remarks

This method will return a pointer to the requested interface if it is supported. You must call the Release method to free the resources associated with this interface when it is no longer needed. This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemServices::AddRef

The IWbemServices::AddRef method increases the object's reference count by 1.

ULONG AddRef( );

Parameters

None.

Return Values

Returns the new reference count.

Remarks

When the object is created, its reference count is set to 1. Every time an application obtains an interface to the object or calls the AddRef method, the object's reference count is increased by 1. Use the Release method to decrease the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For a complete discussion of IUnknown methods, see IUnknown Interface Basics .

For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

QueryInterface, Release, IUnknown Interface Basics


IWbemServices::Release

The IWbemServices::Release method decreases the object's reference count by 1.

ULONG Release( );

Return Values

Returns the new reference count.

Remarks

The object deallocates itself when its reference count reaches zero. Use the AddRef method to increase the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics, Addref, QueryInterface


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(
  [in] const BSTR strNamespace,
  [in] LONG lFlags,
  [in] IWbemContext *pCtx,
  [out, OPTIONAL] IWbemServices **ppWorkingNamespace,
  [out, OPTIONAL] IWbemCallResult **ppResult
);

Parameters

strNamespace
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
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
Reserved. It must be NULL.
ppWorkingNamespace
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
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

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.

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.

HRESULT IWbemServices::CancelAsyncCall(
  [in] IWbemObjectSink *pSink
);

Parameters

pSink
The pointer to the IWbemObjectSink implementation provided by the client to any of the asynchronous methods of IWbemServices.

Return Values

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.

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(
  [in] LONG lFlags,
  [out] IWbemObjectSink **ppResponseHandler
);

Parameters

lFlags
Reserved. It must be zero.
ppResponseHandler
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 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

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.

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(
  [in] const BSTR strObjectPath,
  [in] LONG lFlags,
  [in] IWbemContext *pCtx,
  [out, OPTIONAL] IWbemClassObject **ppObject,
  [out, OPTIONAL] IWbemCallResult **ppCallResult
);

Parameters

strObjectPath
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
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
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
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
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

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.

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(
  [in] const BSTR strObjectPath,
  [in] LONG lFlags,
  [in] IWbemContext *pCtx,
  [in] IWbemObjectSink *pResponseHandler
);

Parameters

strObjectPath
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
WBEM_FLAG_SEND_STATUS registers with Windows Management a request to receive intermediate status reports through the clients implementation of IWbemObjectSink::SetStatus.
pCtx
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
Points to the caller's implementation of IWbemObjectSink. This handler receives the requested object when it becomes available through the IWbemObjectSink::SetStatus 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

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.

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(
  [in] IWbemClassObject *pObject,
  [in] LONG lFlags,
  [in] IWbemContext *pCtx,
  [out, OPTIONAL] IWbemCallResult **ppCallResult
);

Parameters

pObject
Must point to a valid class definition. The reference count is not changed.
lFlags
The following flags affect the behavior of this method.
Flag | Description
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 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 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 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.
WBEM_FLAG_
UPDATE_FORCE_MODE 		This flag forces updates of classes when conflicting child classes exist. An example of an update in 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 it conflicts 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.

pCtx
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
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

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.

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(
  [in] IWbemClassObject *pObject,
  [in] LONG lFlags,
  [in] IWbemContext *pCtx,
  [in] IWbemObjectSink *pResponseHandler
);

Parameters

pObject
Points to the object containing the class definition.
lFlags
Flag | Description
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 | 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 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 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.
WBEM_FLAG_UPDATE_
FORCE_MODE 		This flag forces updates of classes when conflicting child classes exist. An example of an update in 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 it conflicts 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.

pCtx
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
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

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.

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(
  [in] const BSTR strClass,
  [in] LONG lFlags,
  [in] IWbemContext *pCtx,
  [out, OPTIONAL] IWbemCallResult **ppCallResult
);

Parameters

strClass
The name of the class targeted for deletion.
lFlags
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
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
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

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.

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(
  [in] const BSTR strClass,
  [in] LONG lFlags,
  [in] IWbemContext *pCtx,
  [in] IWbemObjectSink *pResponseHandler
);

Parameters

strClass
The name of the class targeted for deletion.
lFlags
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
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
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

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.

See Also

Error Handling for Applications, Asynchronous Methods, 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(
  [in] const BSTR strSuperclass,
  [in] LONG lFlags,
  [in] IWbemContext *pCtx,
  [out] IEnumWbemClassObject **ppEnum
);

Parameters

strSuperclass
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
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_DEEP | This flag forces the enumeration to include all of class 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.

pCtx
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
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

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.

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(
  [in] const BSTR strSuperclass,
  [in] LONG lFlags,
  [in] IWbemContext *pCtx,
  [in]IWbemObjectSink *pResponseHandler
);

Parameters

strSuperclass
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
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_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
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
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

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.

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(
  [in] IWbemClassObject *pInst,
  [in] LONG lFlags,
  [in] IWbemContext *pCtx,
  [out, OPTIONAL] IWbemCallResult **ppCallResult
);

Parameters

pInst
Points to the instance to be written. The caller cannot make assumptions about the reference count at the completion of this call.
lFlags
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
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
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

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 a key, 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.

See Also

Error Handling for Applications, IWbemCallResult, IWbemServices::PutInstanceAsync, Instance Creation and Modification Rules


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(
  [in] IWbemClassObject *pInst,
  [in] LONG lFlags,
  [in] IWbemContext *pCtx,
  [in] IWbemObjectSink *pResponseHandler
);

Parameters

pInst
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
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
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
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

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.

See Also

Asynchronous Methods, IWbemContext, Instance Creation and Modification Rules


IWbemServices::DeleteInstance

The IWbemServices::DeleteInstance method deletes an instance of an existing class in the current namespace.

HRESULT IWbemServices::DeleteInstance(
  [in] const BSTR strObjectPath,
  [in] LONG lFlags,
  [in] IWbemContext *pCtx,
  [out, OPTIONAL] IWbemCallResult **ppCallResult
);

Parameters

strObjectPath
A valid BSTR containing the object path to the instance to be deleted.
lFlags
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
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
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

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. This will be attempting to delete a class object.
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 operations 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.

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(
  [in] const BSTR strObjectPath,
  [in] LONG lFlags,
  [in] IWbemContext *pCtx,
  [in] IWbemObjectSink *pResponseHandler
);

Parameters

strObjectPath
A valid BSTR containing the object path of the object to be deleted.
lFlags
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.

pCtx
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
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

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.

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(
  [in] const BSTR strClass,
  [in] LONG lFlags,
  [in] IWbemContext *pCtx,
  [out] IEnumWbemClassObject **ppEnum
);

Parameters

strClass
A valid BSTR containing the name of the class for which instances are desired. This parameter cannot be NULL.
lFlags
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_DEEP | This flag forces the enumeration to include all of class 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.

pCtx
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
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

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.

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(
  [in] const BSTR strClass,
  [in] LONG lFlags,
  [in] IWbemContext *pCtx,
  [in] IWbemObjectSink *pResponseHandler
);

Parameters

strClass
A valid BSTR containing the name of the class for which instances are desired. This parameter cannot be NULL.
lFlags
Flag | Description
WBEM_FLAG_DEEP | This flag forces the enumeration to include all of class 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.

pCtx
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
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

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.

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(
  [in] const BSTR strQueryLanguage,
  [in] const BSTR strQuery,
  [in] LONG lFlags,
  [in] IWbemContext *pCtx,
  [out] IEnumWbemClassObject **ppEnum
);

Parameters

strQueryLanguage
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
A valid BSTR containing the text of the query. This parameter cannot be NULL.
lFlags
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_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.

pCtx
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
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

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_LANGUAGE | 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.

See Also

IWbemServices::ExecQueryAsync, WMI Query Language (WQL), Data Queries, Event Queries, Schema Queries


IWbemServices::ExecQueryAsync

The IWbemServices::ExecQueryAsync method The IWbemServices::ExecQuery method executes a query to retrieve objects asynchronously.

HRESULT IWbemServices::ExecQueryAsync(
  [in] const BSTR strQueryLanguage,
  [in] const BSTR strQuery,
  [in] long lFlags,
  [in] IWbemContext *pCtx,
  [in] IWbemObjectSink *pResponseHandler
);

Parameters

strQueryLanguage
A valid BSTR containing one of the query languages supported by Windows Management. This must be WQL.
strQuery
A valid BSTR containing the text of the query. This cannot be NULL.
lFlags
Flag | Description
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 clients 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.

pCtx
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
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

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.

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(
  [in] const BSTR strQueryLanguage,
  [in] const BSTR strQuery,
  [in] long lFlags,
  [in] IWbemContext *pCtx,
  [out] IEnumWbemClassObject **ppEnum
);

Parameters

strQueryLanguage
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
A valid BSTR containing the text of the event-related query. This cannot be NULL.
lFlags
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
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
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

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_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_LANGUAGE | 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_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.

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(
  [in] const BSTR strQueryLanguage,
  [in] const BSTR strQuery,
  [in] long lFlags,
  [in] IWbemContext *pCtx,
  [in] IWbemObjectSink *pResponseHandler
);

Parameters

strQueryLanguage
A valid BSTR containing one of the query languages supported by Windows Management. This must be WQL.
strQuery
A valid BSTR containing the text of the event-related query. This cannot be NULL.
lFlags
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..

pCtx
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
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

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_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_LANGUAGE | 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_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.

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(
  [in] const BSTR strObjectPath,
  [in] const BSTR MethodName,
  [in] long lFlags,
  [in] IWbemContext *pCtx,
  [in] IWbemClassObject *pInParams,
  [out, OPTIONAL] IWbemClassObject **ppOutParams,
  [out, OPTIONAL] IWbemCallResult **ppCallResult
);

Parameters

strObjectPath
A valid BSTR containing the object path of the object for which the method is executed.
MethodName
The name of the method for the object.
lFlags
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
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
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
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
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

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 | The supplied pInParams object was determined by the provider to be 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.

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(
  [in] const BSTR strObjectPath,
  [in] const BSTR strMethodName,
  [in] LONG lFlags,
  [in] IWbemContext *pCtx,
  [in] IWbemClassObject *pInParams,
  [in] IWbemObjectSink *pResponseHandler
);

Parameters

strObjectPath
A valid BSTR containing the object path of the object for which the method is to be executed.
strMethodName
The name of the method for the object.
lFlags
WBEM_FLAG_SEND_STATUS registers with Windows Management a request to receive intermediate status reports through the clients implementation of IWbemObjectSink::SetStatus.
pCtx
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
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
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

WBEM_E_FAILED | This indicates other unspecified errors.
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.

See Also

Making an Asynchronous Call, IWbemServices::ExecMethod


IWbemUnboundObjectSink

The IWbemUnboundObjectSink interface is implemented by all logical event consumers. It is a simple sink interface that accepts delivery of event objects.

Methods in Vtable Order

Iunknown Methods | Properties
QueryInterface | Determines if the current object supports a given interface.
AddRef | Increases the object's reference count by 1.
Release | Decrements the object's reference count, and frees the object when the reference count is zero.

IWbemUnboundObjectSink Methods | Properties
IndicateToConsumer | This is called by Windows Management to actually deliver events to a consumer.


IWbemUnboundObjectSink::QueryInterface

The IWbemUnboundObjectSink::QueryInterface method determines if the object supports a particular COM interface. If it does, the system increases the object's reference count, and the application can use that interface immediately. The QueryInterface method allows the extension of objects without interfering with the existing or future functionality of the objects.

HRESULT IWbemUnboundObjectSink::QueryInterface(
  [in] REFIID riid,
  [out] LPVOID *ppv
);

Parameters

riid
The COM interface identifier of the requested interface.
ppv
Address of a pointer that will be filled with the interface pointer if the query succeeds.

Return Values

Returns standard COM error codes for QueryInterface. It returns WBEM_S_NO_ERROR if the call succeeds. If the call fails because the requested interface was not supported, the method returns E_NOINTERFACE.

Remarks

This method will return a pointer to the requested interface if it is supported. You must call the Release method to free the resources associated with this interface when it is no longer needed. This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemUnboundObjectSink::AddRef

The IWbemUnboundObjectSink::AddRef method increases the object's reference count by 1.

ULONG AddRef( );

Parameters

None.

Return Values

Returns the new reference count.

Remarks

When the object is created, its reference count is set to 1. Every time an application obtains an interface to the object or calls the AddRef method, the object's reference count is increased by 1. Use the Release method to decrease the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For a complete discussion of IUnknown methods, see IUnknown Programming Basics.

For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemUnboundObjectSink::Release

The IWbemUnboundObjectSink::Release method decreases the object's reference count by 1.

ULONG IWbemUnboundObjectSink::Release( );

Parameters

None.

Return Values

Returns the new reference count.

Remarks

The object deallocates itself when its reference count reaches zero. Use the AddRef method to increase the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IWbemUnboundObjectSink::IndicateToConsumer

This is called by Windows Management to actually deliver events to a consumer.

HRESULT IWbemUnboundObjectSink::IndicateToConsumer(
  [in] IWbemClassObject *pLogicalConsumer,
  [in] long lNumObjects,
  [in, size_is(lNumObjects)] IWbemClassObject **apObjects
);

Parameters

pLogicalConsumer
A pointer to the logical consumer object for which this set of objects is delivered.
lNumObjects
The number of objects delivered in the array that follows.
apObjects
A pointer to an array of IWbemClassObject instances which represent the events delivered.

Return Values

WBEM_S_NO_ERROR. The implementation should always return this.

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.

See Also

IWbemEventConsumerProvider, Constructing Event Consumers


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).

Methods in Vtable Order

Iunknown Methods | Properties
QueryInterface | Determines if the current object supports a given interface.
AddRef | Increases the object's reference count by 1.
Release | Decrements the object's reference count, and frees the object when the reference count is zero.

IUnsecuredApartment Methods | Properties
CreateObjectStub | Creates an object stub to assist making asynchronous calls from a client process.


IUnsecuredApartment::QueryInterface

The IUnsecuredApartment::QueryInterface method determines if the object supports a particular COM interface. If it does, the system increases the object's reference count, and the application can use that interface immediately. The QueryInterface method allows the extension of objects without interfering with the existing or future functionality of the objects.

HRESULT IUnsecuredApartment::QueryInterface(
  [in] REFIID riid,
  [out] LPVOID *ppv
);

Parameters

riid
The COM interface identifier of the requested interface.
ppv
Address of a pointer that will be filled with the interface pointer if the query succeeds.

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.

Remarks

This method will return a pointer to the requested interface if it is supported. You must call the Release method to free the resources associated with this interface when it is no longer needed. This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IUnsecuredApartment::AddRef

The IUnsecuredApartment::AddRef method increases the object's reference count by 1.

ULONG AddRef( );

Parameters

None.

Return Values

Returns the new reference count.

Remarks

When the object is created, its reference count is set to 1. Every time an application obtains an interface to the object or calls the AddRef method, the object's reference count is increased by 1. Use the Release method to decrease the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For a complete discussion of IUnknown methods, see IUnknown Programming Basics.

For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


IUnsecuredApartment::Release

The IUnsecuredApartment::Release method decreases the object's reference count by 1.

ULONG IUnsecuredApartment::Release( );

Parameters

None.

Return Values

Returns the new reference count.

Remarks

The object deallocates itself when its reference count reaches zero. Use the AddRef method to increase the object's reference count by 1.

This method is part of the IUnknown interface inherited by the object. For more information about this method, see the COM documentation in the Microsoft Platform SDK.

See Also

IUnknown Interface Basics


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(
  [in] IUnknown *pObject,
  [out] IUnknown **ppStub
);

Parameters

pObject
A pointer to the client's in-process implementation of IWbemObjectSink.
ppStub
Receives a pointer to a substitute object to be used in asynchronous IWbemServices calls. The user receives an IUnknown pointer and must do a 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.

See Also

IWbemObjectSink, Making an Asynchronous Call


Scripting API for WMI

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®, Microsoft® Visual Basic for Applications, Microsoft® Visual Basic® Scripting Edition, 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 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 Common Information Model (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.


SWbemEventSource

You can use the NextEvent method of the SWbemEventSource object to retrieve events from an event query. You will 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

Method | Description
NextEvent | Used to retrieve an event in conjunction with SWbemServices.ExecNotificationQuery.

Properties

Property | Description
Security_ | Used to read or change the security settings.


SWbemEventSource.NextEvent

The NextEvent method of the SWbemEventSource object retrieves an event, if available, from an event query.

The following syntax is language neutral. For an explanation of this syntax, see Document Conventions.

Syntax

objObject = objwbemEventsource.NextEvent(
[iTimeoutMs = wbemTimeoutInfinite]
)

Parameters

iTimeoutMs
Optional. This parameter is the 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 this call to wait indefinitely.

Return Values

If successful, an object of type SWbemObject containing the requested event returns. If the call times out, the returned object will be NULL and an error code 0x80043001 will be returned.

Error Codes

The NextEvent method can return the following error code.

Error | Meaning
wbemErrTimedOut 0x80043001 | The requested event did not arrive in the amount of time that was specified in the iTimeoutMs parameter.

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 is used to read or set the security settings for an SWbemEventSource 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 = 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

Security Issues When Writing Scripts For WMI, Object Creation and Monikers


SWbemLastError

You can use the methods and properties of the SWbemLastError object to contain and manipulate error objects. You can create an SWbemLastError error object to inspect the extended error information associated with a previous method call. If there is no error information 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.

The methods and properties of this interface are exactly the same as those of the SWbemObject.

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.
SWbemLastError.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).
ExecMethod_ | Executes a method on the object.
ExecMethodAsync_ | Asynchronously executes a method on the object.

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.


SWbemLastError.Associators_

The Associators_ method of the SWbemLastError 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 Statement 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=""],
[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
0 		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
0 		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, SWbemLastError.References_


SWbemLastError.AssociatorsAsync_

The AssociatorsAsync_ method of the SWbemLastError 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 Statement 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=""],
[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 classnames 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
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
0 		This flag causes WMI to retain pointers to objects of the enumeration until the client releases the enumerator.
wbemFlagSendStatus
0x80 		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

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, 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
0 		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
2 		The source of the objects, namely the server and the namespace they came from, are ignored in comparison to other objects.
wbemComparisonFlagIgnoreQualifiers
1 		All qualifiers (including "key" and "dynamic") should be ignored in comparison.
wbemComparisonFlagIgnoreDefaultValues
4 		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
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.

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_ method 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
0 		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_(
strMethodName,
[objWbemSink],
[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
0 		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.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
0 		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
0 		This flag causes the class or instance to be created if it does not exist or overwritten if it exists already.
wbemChangeFlagCreateOnly
2 		This flag is used for creation only. The call will fail if the class or instance already exists.
wbemChangeFlagUpdateOnly
1 		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
0 		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
0 		This flag causes the class or instance to be created if it does not exist or overwritten if it exists already.
wbemChangeFlagCreateOnly
2 		This flag is used for creation only. The call will fail if the class or instance already exists.
wbemChangeFlagUpdateOnly
1 		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
0 		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
0 		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 classnames 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
0 		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
0 		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 classnames 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
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
0 		This flag causes WMI to retain pointers to objects of the enumeration until the client releases the enumerator.
wbemFlagSendStatus
0x80 		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

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

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
1 		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
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 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_(
[iFlags= 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
1 		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
0 		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.
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.
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\0x409"

Since WMI accommodates other localization schemes besides Microsoft 32-bit LCIDs, you need to use this string format. Other schemes are ISO 639 and RFC 1766.

strAuthority
Optional. It can be a NT LAN Manager (NTLM) domain name. Otherwise, it should be left blank.
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 not 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).
ExecMethod_ | Executes a method on the object.
ExecMethodAsync_ | Asynchronously executes a method on the object.

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=""],
[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 classnames 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
0 		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
0 		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=""],
[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 classnames 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
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
0 		This flag causes WMI to retain pointers to objects of the enumeration until the client releases the enumerator.
wbemFlagSendStatus
0x80 		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

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
0 		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
2 		The source of the objects, namely the server and the namespace they came from, are ignored in comparison to other objects.
wbemComparisonFlagIgnoreQualifiers
1 		All qualifiers (including "key" and "dynamic") should be ignored in comparison.
wbemComparisonFlagIgnoreDefaultValues
4 		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
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.

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
0 		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
0 		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
0 		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 SWbemObjectPath 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 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
0 		This flag causes the class or instance to be created if it does not exist or overwritten if it exists already.
wbemChangeFlagCreateOnly
2 		This flag is used for creation only. The call will fail if the class or instance already exists.
wbemChangeFlagUpdateOnly
1 		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
0 		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
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 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
0 		This flag causes the class or instance to be created if it does not exist or overwritten if it exists already.
wbemChangeFlagCreateOnly
2 		This flag is used for creation only. The call will fail if the class or instance already exists.
wbemChangeFlagUpdateOnly
1 		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
0 		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
0 		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


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 classnames 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
0 		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
0 		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 classnames 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
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
0 		This flag causes WMI to retain pointers to objects of the enumeration until the client releases the enumerator.
wbemFlagSendStatus
0x80 		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

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 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_


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

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
1 		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
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 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
1 		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
0 		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
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.
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.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
objwbemObjectPath.IsSingleton = bIsSingleton

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.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.

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

Security Issues When Writing Scripts For WMI, 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.

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.

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
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.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.
strOverridable
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.

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 string 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 string 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 a string 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

sAuthenticationlevel = objWbemSecurity.AuthenticationLevel
objWbemSecurity.AuthenticationLevel = sAuthenticationlevel

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 objinstanc = 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 a string 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 set this property, the default DCOM authentication level for your system will be used. 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

sImpersonationLevel  = objWbemSecurity.ImpersonationLevel
objWbemSecurity.ImpersonationLevel = sImpersonationLevel

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 objinstanc = 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.Add "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
0 		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
0 		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
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
0 		This flag causes WMI to retain pointers to objects of the enumeration until the client releases the enumerator.
wbemFlagSendStatus
0x80 		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

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(
strObjectPath,
[ObjWbemSink = null],
[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
0 		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
0 		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+wbemFlagForwardOnly)],
[objwbemNamedValueSet=null]
)

Parameters

strQuery
Required. This is a string containing the text of the event-related query. This cannot be blank.
strQueryLanguage
Optional. This is a string containing one of the query languages supported by WMI. This must be "WQL".
iFlags
Optional. This is an integer that determines the behavior of the query. The default value is wbemFlagForwardOnly combined with 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
0 		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
0 		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=(wbemFlagReturnImmediately+wbemFlagForwardOnly)],
[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 is a string containing one of the query languages supported by WMI. This must be "WQL".
iFlags
Optional. This is an integer that determines the behavior of the query. The default value is wbemFlagForwardOnly. This parameter can be set to the following values.
Value Meaning
wbemFlagBidirectional
0 		This flag causes WMI to retain pointers to objects of the enumeration until the client releases the enumerator.
wbemFlagSendStatus
0x80 		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

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 one of the query languages supported by WMI. 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
0 		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
0 		This flag causes this call to block until the query has completed.
wbemQueryFlagPrototype
2 		This flag is used for prototyping. It stops the query from happening and instead returns an object that looks like a typical result object.

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.

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

strQuery
Required. This is a string containing the text of the query. This parameter cannot be blank.
ObjWbemSink
Optional. This is the object sink that will execute the query asynchronously.
strQueryLanguage
Optional. This parameter is a string containing one of the query languages supported by WMI. 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
wbemFlagBidirectional
0 		This flag causes WMI to retain pointers to objects of the enumeration until the client releases the enumerator.
wbemFlagSendStatus
0x80 		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
wbemQueryFlagPrototype
2 		This flag is used for prototyping. It stops the query from happening and instead returns an object that looks like a typical result object.

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.

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 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.

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
0 		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 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
0 		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
0 		This flag causes this call to block until the query has completed.
wbemQueryFlagShallow
1 		This flag forces the enumeration to include only immediate subclasses of the specified superclass.
wbemQueryFlagDeep
0 		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
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
0 		This flag causes WMI to retain pointers to objects of the enumeration until the client releases the enumerator.
wbemQueryFlagShallow
1 		This flag forces the enumeration to include only immediate subclasses of the specified superclass.
wbemQueryFlagDeep
0 		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
0 		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
0 		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
0 		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
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
0 		This flag causes WMI to retain pointers to objects of the enumeration until the client releases the enumerator.
wbemFlagSendStatus
0x80 		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

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

Security Issues When Writing Scripts For WMI, 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
1 		It forces the enumeration to include only immediate subclasses of the specified superclass.
wbemQueryFlagDeep
0 		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
1 		This flag forces the enumeration to include only immediate subclasses of the specified superclass.
wbemQueryFlagDeep
0 		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
0 		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 Error! Bookmark not defined. 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 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

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 (Hex) | Description
wbemChangeFlagCreateOrUpdate | 0x0 | This flag causes the class or instance to be created if it does not exist or overwritten if it exists already.
wbemChangeFlagUpdateOnly | 0x1 | This flag causes the call to update. The class or instance must exist for the call to be successful.
wbemChangeFlagCreateOnly | 0x2 | This flag is used for creation only. The call will fail if the class or instance already exists.
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). If the class has instances the update will fail. This flag is used for compatibility with previous versions of WMI.
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. 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 (Hex) | Description
wbemFlagReturnImmediately | 0x10 | 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 | 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.
wbemFlagNoErrorObject | 0x40 | 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 | 0x80 | 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.


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 (Hex) | 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 (Hex) | Description
wbemTextFlagNoFlavors | 0x1 | Excludes qualifier flavors from the object text.


WbemComparisonFlagEnum

WbemComparisonFlagEnum defines the settings for object comparison. These flags are used by SWbemObject.CompareTo_.

Constant | Value (Hex) | Description
wbemComparisonFlagIncludeAll | 0 | Use this flag to compare all properties, qualifiers, and flavors.
wbemComparisonFlagIgnoreQualifiers | 0x1 | All qualifiers (including "key" and "dynamic") should be ignored in comparison.
wbemComparisonFlagIgnoreObjectSource | 0x2 | The source of the objects, namely the server and the namespace they came from, are ignored in comparison to other objects.
wbemComparisonFlagIgnoreDefaultValues | 0x4 | Default values of properties should be ignored. This flag is only meaningful when comparing classes.
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.
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.
wbemComparisonFlagIgnoreFlavor | 0x20 | 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 (Hex) | Description
wbemCimtypeSint8 | 0x10 | Signed 8 bit integer
wbemCimtypeUint8 | 0x11 | Unsigned 8 bit integer
wbemCimtypeSint16 | 0x2 | Signed 16 bit integer
wbemCimtypeUint16 | 0x12 | Unsigned 16 bit integer
wbemCimtypeSint32 | 0x3 | Signed 32 bit integer
wbemCimtypeUint32 | 0x13 | Unsigned 32 bit integer
wbemCimtypeSint64 | 0x14 | Signed 64 bit integer
wbemCimtypeUint64 | 0x15 | Unsigned 64 bit integer
wbemCimtypeReal32 | 0x4 | 32 bit real number
wbemCimtypeReal64 | 0x5 | 64 bit real number
wbemCimtypeBoolean | 0xB | Boolean value
wbemCimtypeString | 0x8 | String
wbemCimtypeDatetime | 0x65 | Date/Time value
wbemCimtypeChar16 | 0x67 | 16 bit character
wbemCimtypeObject | 0xD | Cim Object


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 (Hex) | Description
wbemAuthenticationLevelDefault | 0x0 | WMI will use the default Windows Authentication setting,
wbemAuthenticationLevelNone | 0x1 | Use no authentication.
wbemAuthenticationLevelConnect | 0x2 | Authenticates the credentials of the client only when the client establishes a relationship with the server.
wbemAuthenticationLevelCall | 0x3 | Authenticates only at the beginning of each call when the server receives the request.
wbemAuthenticationLevelPkt | 0x4 | Authenticates that all data received is from the expected client.
wbemAuthenticationLevelPktIntegrity | 0x5 | Authenticates and verifies that none of the data transferred between client and server has been modified.
wbemAuthenticationLevelPktPrivacy | 0x6 | 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 (Hex) | Description
wbemImpersonationLevelAnonymous | 0x1 | This impersonation hides the credentials of the caller and is specified with the WMI constant.
wbemImpersonationLevelIdentify | 0x2 | This impersonation allows objects to query the credentials of the caller.
wbemImpersonationLevelImpersonate | 0x3 | This impersonation allows objects to use the credentials of the caller.
wbemImpersonationLevelDelegate | 0x4 | 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.

Constant | Value (Hex) | Description
wbemPrivilegeCreateToken | 0x1 | Required to create a primary token.
wbemPrivilegePrimaryToken | 0x2 | Required to assign the primary token of a process.
wbemPrivilegeLockMemory | 0x3 | Required to lock physical pages in memory.
wbemPrivilegeIncreaseQuota | 0x4 | Required to increase the quota assigned to a process.
wbemPrivilegeMachineAccount | 0x5 | Required to create a machine account.
wbemPrivilegeTcb | 0x6 | 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 | 0x7 | 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 | 0x8 | 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 | 0x9 | Required to load or unload a device driver.
wbemPrivilegeSystemProfile | 0x10 | Required to gather profiling information for the entire system.
wbemPrivilegeSystemtime | 0x11 | Required to modify the system time.
wbemPrivilegeProfileSingleProcess | 0x12 | Required to gather profiling information for a single process.
wbemPrivilegeIncreaseBasePriority | 0x13 | Required to increase the base priority of a process.
wbemPrivilegeCreatePagefile | 0x14 | Required to create a paging file.
wbemPrivilegeCreatePermanent | 0x15 | Required to create a permanent object.
wbemPrivilegeBackup | 0x10 | Required to perform backup operations.
wbemPrivilegeRestore | 0x11 | Required to perform restore operations. This privilege enables you to set any valid user or group SID as the owner of an object.
wbemPrivilegeShutdown | 0x12 | Required to shut down a local system.
wbemPrivilegeDebug | 0x13 | Required to debug a process.
wbemPrivilegeAudit | 0x14 | Required to generate audit-log entries.
wbemPrivilegeSystemEnvironment | 0x15 | Required to modify the nonvolatile RAM of systems that use this type of memory to store configuration information.
wbemPrivilegeChangeNotify | 0x16 | 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 | 0x17 | Required to shut down a system using a network request.


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 (Hex) | Description
SeCreateTokenPrivilege | wbemPrivilegeCreateToken | 0x1 | Required to create a primary token.
SeAssignPrimaryTokenPrivilege | wbemPrivilegePrimaryToken | 0x2 | Required to assign the primary token of a process.
SeLockMemoryPrivilege | wbemPrivilegeLockMemory | 0x3 | Required to lock physical pages in memory.
SeIncreaseQuotaPrivilege | wbemPrivilegeIncreaseQuota | 0x4 | Required to increase the quota assigned to a process.
SeMachineAccountPrivilege | wbemPrivilegeMachineAccount | 0x5 | Required to create a machine account.
SeTcbPrivilege | wbemPrivilegeTcb | 0x6 | 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 | 0x7 | 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 | 0x8 | 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 | 0x9 | Required to load or unload a device driver.
SeSystemProfilePrivilege | wbemPrivilegeSystemProfile | 0x10 | Required to gather profiling information for the entire system.
SeSystemtimePrivilege | wbemPrivilegeSystemtime | 0x11 | Required to modify the system time.
SeProfileSingleProcessPrivilege | wbemPrivilegeProfileSingleProcess | 0x12 | Required to gather profiling information for a single process.
SeIncreaseBasePriorityPrivilege | wbemPrivilegeIncreaseBasePriority | 0x13 | Required to increase the base priority of a process.
SeCreatePagefilePrivilege | wbemPrivilegeCreatePagefile | 0x14 | Required to create a paging file.
SeCreatePermanentPrivilege | wbemPrivilegeCreatePermanent | 0x15 | Required to create a permanent object.
SeBackupPrivilege | wbemPrivilegeBackup | 0x10 | Required to perform backup operations.
SeRestorePrivilege | wbemPrivilegeRestore | 0x11 | 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 | 0x12 | Required to shut down a local system.
SeDebugPrivilege | wbemPrivilegeDebug | 0x13 | Required to debug a process.
SeAuditPrivilege | wbemPrivilegeAudit | 0x14 | Required to generate audit-log entries.
SeSystemEnvironmentPrivilege | wbemPrivilegeSystemEnvironment | 0x15 | Required to modify the nonvolatile RAM of systems that use this type of memory to store configuration information.
SeChangeNotifyPrivilege | wbemPrivilegeChangeNotify | 0x16 | 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 | 0x17 | Required to shut down a system using a network request.


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 graphical user interface (GUI) components that form the WBEM Object Browser and WBEM 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
WBEM Class Navigator | Displays a tree view of the class structure in a namespace of the Common Information Model (CIM) repository.
WBEM Provider Wizard | Generates C++ provider framework code for specified objects.
WBEM EventList | Displays events that are forwarded to it.
WBEM Event Registration | Displays event filters, event consumers, and their bindings.
WBEM MOF Compiler Wizard | Compiles a specified Managed Object Format (MOF) file.
WBEM MOF Generator Wizard | Generates a MOF file for specified objects.
WBEM Multiple Instances Viewer | Displays the details for one or more objects in a table format.
WBEM Namespace Picker | Allows users to browse and select namespaces.
WBEM Instance Navigator | Displays the associations between objects in a namespace in the CIM repository.
WBEM Login | Provides login services for the WMI ActiveX controls.
WBEM Object Viewer | Displays the details for a specified object.
WBEM Object Viewer Container | Provides navigation features for the WBEM Object Viewer and the WBEM Multiple Instances Viewer.


WBEM Class Navigator

The WBEM Class Navigator ActiveX control displays a tree view of the class structure of the Common Information Model (CIM) repository. In the WBEM CIM Studio application, this control occupies the left pane.

The Namespace property represents the namespace to which the control is currently connected. Setting it connects the control to the newly specified namespace.

Selecting a class in the tree initiates an EditExistingClass event, which notifies the container that the user has selected a class. In WBEM 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 WBEM Login. Successful opening of the namespace triggers the NotifyOpenNameSpace, which in turn notifies the container.

The method GetExtendedSelection returns an array containing the current namespace and the full paths to all classes selected in the extended selection. 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 WBEM CIM Studio as the input to the WBEM 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 WBEM Provider Wizard, or the WBEM 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, NotifyOpenNameSpace


Properties (WBEM Class Navigator)

This section contains properties for the WBEM Class Navigator control.


NameSpace (WBEM Class Navigator)

Definition

BSTR NameSpace

Description

Returns the namespace currently displayed in the control or sets a new namespace. The NameSpace property 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.


Methods (WBEM Class Navigator)

This section contains methods for the WBEM Class Navigator control.


GetExtendedSelection (WBEM Class Navigator)

Description

Returns the namespace and full paths to all classes selected using extended selection.

Syntax

VARIANT GetExtendedSelection();

Parameters

None.

Return Values

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 (WBEM Class Navigator)

Description

The GetSingleSelection method returns the full path to the selected class.

Syntax

BSTR GetSingleSelection();

Parameters

None.

Return Values

Full path to the selected class. A path is always returned because a tree node is always selected.


MofCompiled (WBEM Class Navigator)

Description

Calling 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.

Syntax

void MofCompiled(
  BSTR lpctstrNamespace
);

Parameters

lpctstrNamespace
The namespace to refresh.

Return Values

Nothing.


OnReadySignal (WBEM Class Navigator)

Description

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.

Syntax

void OnReadySignal();

Parameters

None.

Return Values

Nothing.


Events (WBEM Class Navigator)

This section contains events for the WBEM Class Navigator control.


EditExistingClass (WBEM Class Navigator)

Description

Asynchronously notifies the container that a class has been selected.

Syntax

void EditExistingClass(
  VARIANT vExistingClass
);

Parameters

vExistingClass
A variant of type VT_BSTR containing a class path or an empty string.


GetIWbemServices (WBEM Class Navigator)

Description

Occurs when the control wants to connect to a namespace. This event retrieves an IWbemServices pointer for the current namespace and object path.

Syntax

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


NotifyOpenNameSpace (WBEM Class Navigator)

Description

Asynchronously notifies the container that the specified namespace has been successfully opened.

Syntax

void NotifyOpenNameSpace(
  BSTR lpcstrNameSpace
);

Parameters

lpcstrNameSpace
The namespace that was successfully opened.


WBEM Provider Wizard

The WBEM Provider Wizard ActiveX control generates C++ provider code, which is based on the provider framework, for specified objects. The Windows Management Instrumentation (WMI) SDK uses it as a component of WBEM 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


Properties (WBEM Provider Wizard)

This section contains the property for the WBEM Provider Wizard control.


CPPTargets (WBEM Provider Wizard)

Definition

VARIANT CPPTargets

Description

Specifies or returns the classes for which the provider framework code will be generated. This property 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.


Events (WBEM Provider Wizard)

This section contains events for the WBEM Provider Wizard control.


GenerateCPPs (WBEM Provider Wizard)

Description

Signals that the control would like 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 WBEM Provider Wizard becomes visible.

Syntax

void GenerateCPPs();

Parameters

None.


GetIWbemServices (WBEM Provider Wizard)

Description

Occurs when the control wants to connect to a namespace. This event retrieves an IWbemServices pointer for the current namespace and object path.

Syntax

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


WBEM EventList

The WBEM EventList ActiveX control displays the events that a registered consumer forwards to it. It is used, for example, in the WBEM Event Viewer application. The Event Viewer event consumer registers its event consumer with Windows Management Instrumentation (WMI). It forwards events received by its provider. 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 WBEM EventList control then displays the event in the events list. The WBEM 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 "Msgbox" icons

Severity | Displayed
1 | error icon
2 | warning icon
3 or higher | info icon

The Clearmethod clears the events list, while the DoDetails method launches the WBEM 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


Properties (WBEM EventList)

This section contains properties for the WBEM EventList control.


MaxItems (WBEM EventList)

Definition

long maxItems

Description

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 this number, events are purged from the control according to their age; older events are purged first.


ItemCount (WBEM EventList)

Definition

long ItemCount

Description

You set this property to contain a large number of items. It contains the current number of events displayed by the control.


Methods (WBEM EventList)

This section contains methods for the WBEM EventList control.


AddWbemEvent (WBEM EventList)

Description

Adds an event to the consumer.

Syntax

long AddWbemEvent(
  IUnknown *LogicalConsumer,
  IUnknown *Event
);

Parameters

If the following parameters are null or invalid, the control returns an error.

LogicalConsumer
The logical consumer name. It must be an instance of EventViewerConsumer or an instance of a class derived from EventViewerConsumer.
Event
The event being added to the consumer.

Return Values

The value returned is S_OK if the operation succeeds. Otherwise, a failure code is returned if the parameters are incorrect.


Clear (WBEM EventList)

Description

Clears items in the event selection list. The item to delete is passed as a parameter. If the item is not currently selected then an OnSelChanged event fires. Another item is not automatically selected.

Syntax

long Clear(
  long item
);

Parameters

item
Contains the item number to delete. If item is -1, then all items are deleted.

Return Values

Returns S_OK if the instance is created; otherwise, it returns a failure code.


DoDetails (WBEM EventList)

Description

Launches the WBEM Object Viewer to display the selected object's information.

Syntax

void DoDetails();

Parameters

None.

Return Values

Nothing.

See Also

WBEM Object Viewer


Events (WBEM EventList)

This section contains the event for the WBEM EventList control.


OnSelChanged (WBEM EventList)

Description

The OnSelChanged event is fired whenever the item selection in a control changes. The parameter corresponds to a is zero-based index and refers to the item's row in the list control. Resorting the list control changes an item's index.

The event is fired with a value of -1 to indicate that an item was not selected when the Clear method was called.

Syntax

void OnSelChanged(
  long selected
);

Parameters

selected
Value indicates the item currently selected. A value of -1 is sent if no item is selected.


WBEM Event Registration

The WBEM Event Registration ActiveX control provides a simple user interface for defining WBEM event filters and consumers, and for binding them to each other. The control displays listings, by class, of currently defined event filters and event consumers. It also lists timer instructions. In the Windows Management Instrumentation (WMI) SDK, it is a component of the WBEM Event Registration application.

The control's GetIWbemServices event fires when the control seeks to connect to a namespace. It 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.

Getting or setting the RootFilterClass property returns or changes the current root filter class. This property also can control a displayed filter's scope, specifying that it be of a particular filter class or derived from a particular filter class. Finally, 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 WBEM events and consumers, see Event Notification.

Properties

NameSpace, RootConsumerClass, RootFilterClass, ViewMode

Methods

None.

Events

GetIWbemServices


Properties (WBEM Event Registration)

This section contains properties for the WBEM Event Registration control.


NameSpace (WBEM Event Registration)

Definition

BSTR NameSpace

Description

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.


RootConsumerClass (WBEM Event Registration)

Syntax

BSTR RootConsumerClass

Description

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.


RootFilterClass (WBEM Event Registration)

Syntax

BSTR RootFilterClass

Description

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.


ViewMode (WBEM Event Registration)

Syntax

BSTR ViewMode

Description

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.


Events (WBEM Event Registration)

This section contains the event for the WBEM Event Registration control.


GetIWbemServices (WBEM Event Registration)

Description

Occurs when the control wants to connect to a namespace. This event retrieves an IWbemServices pointer for the current namespace and object path.

Syntax

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


WBEM MOF Compiler Wizard

The WBEM MOF Compiler Wizard ActiveX control provides a user interface (UI) from which the user can select some options for compiling a specified Managed Object Format (MOF) file. The Windows Management Instrumentation (WMI) SDK uses it as a component of WBEM CIM Studio. It connects to a namespace using the GetIWbemServices event, which retrieves an IWbemServices pointer to the current namespace and object path. The WBEM Login typically obtains this pointer. A handler for GetIWbemServices would typically invoke the WBEM 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.

Properties

None

Methods

None.

Events

GetIWbemServices, ModifiedNamespace


Properties (WBEM MOF Compiler Wizard)

This section contains the property for the WBEM MOF Compiler Wizard control.


Events (WBEM MOF Compiler Wizard)

This section contains events for the WBEM MOF Compiler Wizard control.


GetIWbemServices (WBEM MOF Compiler Wizard)

Description

Occurs when the control wants to connect to a namespace. This event retrieves an IWbemServices pointer for the current namespace and object path.

Syntax

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


ModifiedNamespace (WBEM MOF Compiler Wizard)

Description

Indicates which namespace has been modified through the compilation of a MOF file.

Syntax

void ModifiedNamespace(
  BSTR lpcstrNamespace
);

Parameters

lpcstrNamespace
Specifies the modified namespace.


WBEM MOF Generator Wizard

The WBEM 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 WBEM 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.

Properties

MOFTargets

Methods

None.

Events

GenerateMOFs, GetIWbemServices


Properties (WBEM MOF Generator Wizard)

This section contains the property for the WBEM MOF Generator Wizard control.


MOFTargets (WBEM MOF Generator Wizard)

Definition

VARIANT MOFTargets

Description

Specifies or returns the objects for which the MOF file will be generated. This property is an array of BSTRs (a VARIANT of type VT_ARRAY | VT_BSTR).

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. Setting this value starts the MOF file generation process.

To get 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.


Events (WBEM MOF Generator Wizard)

This section contains events for the WBEM MOF Generator Wizard control.


GenerateMOFs (WBEM MOF Generator Wizard)

Description

Signals that the control would like to receive a list of classes (and a namespace) to generate code for. The event handler should respond 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.

Syntax

void GenerateMOFs();

Parameters

None.


GetIWbemServices (WBEM MOF Generator Wizard)

Description

Occurs when the control wants to connect to a namespace. This event retrieves an IWbemServices pointer for the current namespace and object path.

Syntax

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


WBEM Multiple Instances Viewer

The WBEM Multiple Instances Viewer ActiveX control displays the details for one or more objects in a table format. The NameSpace property, which defaults to NULL, returns the current namespace, or sets a new namespace. 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.

This control supports three different ways to specify which instances it 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


Properties (WBEM Multiple Instances Viewer)

This section contains properties for the WBEM Multiple Instances Viewer control.


NameSpace (WBEM Multiple Instances Viewer)

Definition

BSTR NameSpace

Description

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.


PropertyFilter (WBEM Multiple Instances Viewer)

Definition

long PropertyFilter

Description

Indicates whether the control is displaying all of a control's properties, or only a subset.

Return Values

The PropertyFilter property can have one of the following 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.


Methods (WBEM Multiple Instances Viewer)

This section contains methods for the WBEM Multiple Instances Viewer control.


AddContextRef (WBEM Multiple Instances Viewer)

Description

Increments the reference count for the specified context handle.

Syntax

long AddContextRef(
  long lCtxtHandle
);

Parameters

lCtxtHandle
The context handle. If this parameter is null or invalid, the control returns an error.

Return Values

Returns S_OK if the reference count is incremented; otherwise, it returns an error.


DeleteInstance (WBEM Multiple Instances Viewer)

Description

Deletes the current instance.

Syntax

long DeleteInstance();

Parameters

None.

Return Values

Returns S_OK if the instance is successfully deleted; otherwise, it returns a failure code.


ExternInstanceCreated (WBEM Multiple Instances Viewer)

Description

Notifies the control when a WMI object instance is created

Syntax

void ExternInstanceCreated(
  BSTR szObjectPath
);

Parameters

szObjectPath
The full path of the WMI class object.

Return Values

Nothing.


ExternInstanceDeleted (WBEM Multiple Instances Viewer)

Description

Notifies the control when the WMI object instance is deleted. This allows a custom view to reflect the non-existence of a specified object.

Syntax

void ExternInstanceDeleted(
  BSTR szObjectPath
);

Parameters

szObjectPath
The full path of the WMI class object.

Return Values

Nothing.


GetContext (WBEM Multiple Instances Viewer)

Description

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.

Syntax

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

Returns S_OK if the context is successfully returned; otherwise, it returns a failure code.


GetEditMode (WBEM Multiple Instances Viewer)

Description

Returns the current state of the edit mode flag.

Syntax

long GetEditMode();

Parameters

None.

Return Values

Returns 1 (true) if the view's data can be edited. Returns 0 (false) if the view's data is for browsing only.

See Also

IWbemServices


GetObjectPath (WBEM Multiple Instances Viewer)

Description

Returns the object path at the given object position.

Syntax

BSTR GetObjectPath(
  [in] long lPosition
);

Parameters

lPosition
The object position in the current view.

For the WBEM Object Viewer, 0 is the only valid lPosition value. Any other value returns an error.

Return Values

Returns the object's path, if an object exists at the specified position. Returns null, if no object exists at the specified position.


GetObjectTitle (WBEM Multiple Instances Viewer)

Description

Returns a title for the specified object that is suitable for display to the user. The title is not necessarily the object path.

Syntax

BSTR GetObjectTitle(
  long lPosition
);

Parameters

lPosition
The object position in the current view. This parameter must be 0.

Return Values

If lPosition is 0, returns the title of the current object. Otherwise, it returns an empty string.


GetTitle (WBEM Multiple Instances Viewer)

Description

Obtains the title and icon to display in the title bar.

Syntax

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. This parameter should be null if no icon should be displayed. If this parameter is invalid, the control returns an error.

Return Values

Returns S_OK if the title and icon are returned; otherwise, it returns E_FAIL.


GetViewTitle (WBEM Multiple Instances Viewer)

Description

Obtains the title of the view at the specified position. There is no view title for this control.

Syntax

BSTR GetViewTitle(
  long lPosition
);

Parameters

lPosition
Specifies the position of the view to be retrieved. Can be one of the following:

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

An empty string, indicating there is no view title.


NextObject (WBEM Multiple Instances Viewer)

Description

Returns the position of the next object in the current view.

Syntax

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 successful, returns the position of the next object; otherwise, it returns an error.

See Also

PrevObject, StartObjectEnumeration


NextViewTitle (WBEM Multiple Instances Viewer)

Description

Obtains the title of the view at the next position.

Syntax

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

Returns the value -1, indicating there is no next view title.

See Also

PrevViewTitle, StartViewEnumeration


PrevObject (WBEM Multiple Instances Viewer)

Description

Returns the position of the previous object in the current view.

Syntax

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 successful, returns the position of the previous object; otherwise, it returns an error.

See Also

NextObject, StartObjectEnumeration


PrevViewTitle (WBEM Multiple Instances Viewer)

Description

Obtains the title of the view at the previous position.

Syntax

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
Receives the view title.

Return Values

Returns the value -1, indicating there is no previous view title.

See Also

NextViewTitle, StartViewEnumeration


QueryCanDeleteInstance (WBEM Multiple Instances Viewer)

Description

Determines whether to call DeleteInstance to delete the current instance. If this method is not called prior to calling DeleteInstance, the control returns an error.

Syntax

long QueryCanDeleteInstance();

Parameters

None.

Return Values

Returns True if the current instance can be deleted; returns False if the current instance cannot be deleted or if there is no current instance to delete.

See Also

DeleteInstance


QueryNeedsSave (WBEM Multiple Instances Viewer)

Description

Determines whether the current object has been modified and must be saved.

Syntax

long QueryNeedsSave();

Parameters

None.

Return Values

Returns False.


QueryObjectSelected (WBEM Multiple Instances Viewer)

Description

Determines whether the object is selected.

Syntax

long QueryObjectSelected();

Parameters

None.

Return Values

Returns True if object is selected; otherwise, it returns False.


QueryViewInstances (WBEM Multiple Instances Viewer)

Description

Displays the instances returned by a query.

Syntax

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.


RefreshView (WBEM Multiple Instances Viewer)

Description

Reloads the contents of the current view from the Common Information Model (CIM) repository.

Syntax

long RefreshView();

Parameters

None.

Return Values

Returns S_OK if the reload is successful; otherwise, it returns a failure code.


ReleaseContext (WBEM Multiple Instances Viewer)

Description

Decrements the reference count for the specified context handle.

Syntax

long ReleaseContext(
  long lCtxtHandle
);

Parameters

lCtxtHandle
The context handle. If this parameter is null or invalid, the control returns an error.

Return Values

Returns S_OK if the reference count is decremented; otherwise, it returns a failure code.


RestoreContext (WBEM Multiple Instances Viewer)

Description

Restores the state of the control to the previously-saved context.

Syntax

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

Returns S_OK if the view's context could be restored; otherwise, it returns a failure code.


SelectObjectByPath (WBEM Multiple Instances Viewer)

Description

Selects the specified object using the object path. The object path must be an absolute path.

Syntax

long SelectObjectByPath(
  BSTR szObjectPath
);

Parameters

szObjectPath
The WMI object path. If this parameter is null or invalid, the control returns an error.

Return Values

Returns S_OK if the object is selected; otherwise, it returns an error.


SelectObjectByPosition (WBEM Multiple Instances Viewer)

Description

Selects an object in the current view 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.

Syntax

long SelectObjectByPosition(
  long lPosition
);

Parameters

lPosition
The object position in the current view.

Return Values

Returns S_OK if the object selection succeeds; otherwise, it returns a failure code.


SetEditMode (WBEM Multiple Instances Viewer)

Description

Sets the view's edit mode flag.

Syntax

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

Nothing.


StartObjectEnumeration (WBEM Multiple Instances Viewer)

Description

Starts the enumeration of objects.

Syntax

long StartObjectEnumeration(
  long lWhere
);

Parameters

lWhere
Identifies the position of the object. Can be one of:

0 = Current object

1 = First object

2 = Last object

Any other value returns an error.

Return Values

Returns S_OK if the object selection is successful; otherwise, it returns E_FAILED.


StartViewEnumeration (WBEM Multiple Instances Viewer)

Description

Starts the enumeration of custom views.

Syntax

long StartViewEnumeration(
  [in] long lWhere
);

Parameters

lWhere
Specifies the view from which to start enumerating. It can be one of the following:

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

Returns -1, indicating there are no alternate views.


ViewClassInstances (WBEM Multiple Instances Viewer)

Description

Obtains the instance enumeration of the specified class and displays the instances.

Syntax

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

Nothing.


ViewInstances (WBEM Multiple Instances Viewer)

Description

Displays instances.

Syntax

long ViewInstances(
  BSTR szTitle,
  VARIANT varPathArray
);

Parameters

szTitle
The view title. If this parameter is null or invalid, the control returns an error.
varPathArray
Expects a variant that contains 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

Nothing.


Events (WBEM Multiple Instances Viewer)

This section contains events for the WBEM Multiple Instances Viewer control.


GetIWbemServices (WBEM Multiple Instances Viewer)

Description

Occurs when the control wants to connect to a namespace. This event retrieves an IWbemServices pointer for the current namespace and object path.

Syntax

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


NotifySelectionChanged (WBEM Multiple Instances Viewer)

Description

The event notifies the container that a new object is selected in a custom view. This event is fired when the user clicks selects an instance in the viewer usng the left mouse button.

Syntax

void NotifySelectionChanged();

Parameters

None.


NotifyViewObjectSelected (WBEM Multiple Instances Viewer)

Description

Occurs when an object is double clicked.

Syntax

void NotifyViewObjectSelected(
  BSTR szObjectPath
);

Parameters

szObjectPath
Path of the selected object.


RequestUIActive (WBEM Multiple Instances Viewer)

Description

Occurs when the control wants to go UI active and may be embedded in an ActiveX control.

Syntax

void RequestUIActive();

Parameters

None.


WBEM Namespace Picker

The WBEM Namespace Picker ActiveX control allows users to 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 WBEM 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


Properties (WBEM Namespace Picker)

This section contains the property for the WBEM Namespace Picker control.


NameSpace (WBEM Namespace Picker)

Definition

BSTR NameSpace

Description

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.


Methods (WBEM Namespace Picker)

This section contains methods for the WBEM Namespace Picker control.


ClearNamespaceText (WBEM Namespace Picker)

Description

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.

Syntax

void ClearNamespaceText(
  BSTR lpctstrNamespace
);

Parameters

lpctstrNamespace
The namespace currently displayed in the control.

Return Values

Nothing.


ClearOnLoseFocus (WBEM Namespace Picker)

Description

The ClearOnLoseFocus method sets a flag that tells the control to clear the text from the edit box when the control loses focus.

Syntax

void ClearOnLoseFocus(
  long lClearOnLoseFocus
);

Parameters

lClearOnLoseFocus
Sets 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

Nothing.


GetNameSpaceText (WBEM Namespace Picker)

Description

Returns the namespace text which can be a valid namespace or can be dirty text.

Syntax

BSTR GetNameSpaceText();

Parameters

None.

Return Values

The namespace text.


IsTextValid (WBEM Namespace Picker)

Description

Determines whether the namespace text contains a valid namespace.

Syntax

long IsTextValid();

Parameters

None.

Return Values

Returns a non-zero value if the namespace text contains a valid namespace. Otherwise, it returns 0.


OpenNamespace (WBEM Namespace Picker)

Description

Opens the specified namespace.

Syntax

long OpenNamespace(
  BSTR bstrNamespace,
  long longNoFireEvent
);

Parameters

If these parameters are null or invalid, the control returns an error.

bstrNamespace
Namespace to open.
longNoFireEvent
Indicates the result of the attempt to open the specified namespace. If False, the NotifyNameSpaceChanged event fires. If True, the NotifyNameSpaceChanged event does not fire.

Return Values

Returns S_OK if the namespace is opened; otherwise, it returns an error.

See Also

NotifyNameSpaceChanged


SetNamespaceText (WBEM Namespace Picker)

Description

Sets the text in the control to the specified namespace and the text color to blue.

Syntax

void SetNamespaceText(
  BSTR lpctstrNamespace
);

Parameters

lpctstrNamespace
The namespace that displays in the control.

Return Values

Nothing.


SetFocusToEdit (WBEM Namespace Picker)

Description

Sets the input focus to the edit control in the combo box. This allows containing controls or clients to notify the WBEM 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

Syntax

void SetFocusToEdit();

Parameters

None.

Return Values

Nothing.


Events (WBEM Namespace Picker)

This section contains events for the WBEM Namespace Picker control.


GetIWbemServices (WBEM Namespace Picker)

Description

Occurs when the control wants to connect to a namespace. This event retrieves an IWbemServices pointer for the current namespace and object path.

Syntax

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


NameSpaceEntryRedrawn (WBEM Namespace Picker)

Description

Notifies the container that the control has redrawn itself.

Syntax

void NameSpaceEntryRedrawn();

Parameters

None.


NotifyNameSpaceChanged (WBEM Namespace Picker)

Description

Notifies the container when the specified namespace opens.

Syntax

void NotifyNameSpaceChanged(
  BSTR bstrNewNameSpace,
  long longValid
);

Parameters

bstrNewNameSpace
The namespace being opened.
longValid
This parameter always has a value of True.


RequestUIActive (WBEM Namespace Picker)

Description

Occurs when the control wants to go UI active and may be embedded in an ActiveX control.

Syntax

void RequestUIActive();

Parameters

None.


WBEM Instance Navigator

The WBEM Instance Navigator ActiveX control displays a tree of objects in the currently selected namespace in the Common Information Model (CIM) repository. It 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 together 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 QueryViewInstancesevent 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


Properties (WBEM Instance Navigator)

This section contains properties for the WBEM Instance Navigator control.


NameSpace (WBEM Instance Navigator)

Definition

BSTR NameSpace

Description

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.


Methods (WBEM Instance Navigator)

This section contains methods for the WBEM Instance Navigator control.


OnReadySignal (WBEM Instance Navigator)

Description

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.

Syntax

void OnReadySignal();

Parameters

None.

Return Values

Nothing.


ChangeRootOrNamespace (WBEM Instance Navigator)

Description

This method is used by the WBEM Object Viewer Container to synchronize the tree with the view in that control.

Syntax

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 to open.
lFireEvents
If lFireEvents is TRUE, events appropriate to the completed operations will be fired.

Return Values

If lpctstrRootOrNamespace parameter is an instance path it is made the tree root. If it 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 on opening the namespace.


Events (WBEM Instance Navigator)

This section contains events for the WBEM Instance Navigator control.


GetIWbemServices (WBEM Instance Navigator)

Description

Occurs when the control wants to connect to a namespace. This event retrieves an IWbemServices pointer for the current namespace and object path.

Syntax

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


NotifyOpenNameSpace (WBEM Instance Navigator)

Description

Asynchronously notifies the container that the specified namespace has been successfully opened.

Syntax

void NotifyOpenNameSpace(
  BSTR lpcstrNameSpace
);

Parameters

lpcstrNameSpace
The namespace that was successfully opened.


QueryViewInstances (WBEM Instance Navigator)

Description

The event is fired when an association role node or object group node is selected.

Syntax

void QueryViewInstances(
  BSTR pLabel,
  BSTR pQueryType,
  BSTR pQuery,
  BSTR pClass
);

Parameters

pLabel
Query label; used for display purposes.
pQueryType
The type of query (WQL OR SQL).
pQuery
The query to be performed.
pClass
Optional. The class in which the query should be performed.


ViewObject (WBEM Instance Navigator)

Description

Occurs when an instance is selected in the tree control or when an association is displayed.

Syntax

void ViewObject(
  BSTR bstrPath
);

Parameters

bstrPath
The path to an association class. If this parameter is null or invalid, the control returns an error.


WBEM Login

The Login ActiveX control provides login services for the Windows Management Instrumentation (WMI) ActiveX controls. Each of the other ActiveX controls, except the Managed Object Format (MOF) Compiler controlling this section, require this control in order 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. This text string will be displayed by the control in the caption of the login dialog so that the user knows which application requires a login by the user. A client wanting to obtain 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 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.

Properties

LoginComponent

Methods

GetIWbemServices, PageUnloading

Events

None.


Properties (WBEM Login)

This section contains the property for the WBEM Login control.


LoginComponent (WBEM Login)

Definition

BSTR LoginComponent

Description

Used in calls to the exported function in LoginDlg.dll to indicate the WMI component to log into. Setting this property simply sets the title of the login dialog box.


Methods (WBEM Login)

This section contains methods for the WBEM Login control.


GetIWbemServices (WBEM Login)

Description

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.

Syntax

void GetIWbemServices(
  BSTR lpctstrNamespace,
  VARIANT *pvarUpdatePointer,
  VARIANT *pvarServices,
  VARIANT *pvarSC,
  VARIANT *pvarUserCancel
);

Parameters

lpctstrNamespace
Namespace to connect to.
pvarUpdatePointer
Requests new pointer from DLL.
pvarServices
Services pointer 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.


PageUnloading (WBEM Login)

Description

Uncaches all service pointers by calling the exported function in LoginDlg.dll.

Syntax

void PageUnloading();

Parameters

None.

Return Values

Nothing.


WBEM Object Viewer

The WBEM Object Viewer ActiveX control displays the details of a specified object, including a tab that displays the object's properties, a tab about 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 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 transition to the next ready state. This event is used during the loading of asynchronous (datapath) 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. As a result, it receives an IWbemServices pointer for the requested namespace. When the user selects the context-menu options "Make Root" or "Go To Namespace" in the associations tab for a displayed object, the NOTIFYChangeRootOrNamespace event notifies the container. In the case of a namespace change, the container can then change the current namespace to be the one specified in the event. When used in conjunction with the instance navigator, it can request the 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 it 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 WBEM 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, StartViewEnumeration

Events

GetIWbemServices, JumpToMultipleInstanceView, NOTIFYChangeRootOrNamespace,
NotifyContextChanged, NotifyInstanceCreated, NotifySaveRequired, NotifySelectionChanged, NotifyViewModified, RequestUIActive


Properties (WBEM Object Viewer)

This section contains properties for the WBEM Object Viewer control.


NameSpace (WBEM Object Viewer)

Definition

BSTR NameSpace

Description

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.


PropertyFilter (WBEM Object Viewer)

Definition

long PropertyFilter

Description

Indicates whether the control is displaying all of a control's properties, or only a subset. 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.


ReadyState (WBEM Object Viewer)

Definition

long ReadyState

Description

Indicates the current state of readiness of a control during a potentially asynchronous download process. This property cannot be set.

Values

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.


Methods (WBEM Object Viewer)

This section contains methods for the WBEM Object Viewer control.


AddContextRef (WBEM Object Viewer)

Description

Increments the reference count for the specified context handle.

Syntax

long AddContextRef(
  long lCtxtHandle
);

Parameters

lCtxtHandle
The context handle. If this parameter is null or invalid, the control returns an error.

Return Values

Returns S_OK if the reference count is incremented; otherwise, it returns an error.


CreateInstance (WBEM Object Viewer)

Description

Creates an instance of the specified class and makes this instance the current object.

Syntax

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

Returns S_OK if the instance is created; otherwise, it returns a failure code.


CreateInstanceOfCurrentClass (WBEM Object Viewer)

Description

Creates an instance of the current class.

Syntax

long CreateInstanceOfCurrentClass();

Parameters

None.

Return Values

Returns S_OK if the instance is successfully created; otherwise, it returns a failure code.


DeleteInstance (WBEM Object Viewer)

Description

Deletes the current instance.

Syntax

long DeleteInstance();

Parameters

None.

Return Values

Returns S_OK if the instance is successfully deleted; otherwise, it returns a failure code.


ExternInstanceCreated (WBEM Object Viewer)

Description

Notifies the control when a WMI object instance is created

Syntax

void ExternInstanceCreated(
  BSTR szObjectPath
);

Parameters

szObjectPath
The full path of the WMI class object.

Return Values

Nothing.


ExternInstanceDeleted (WBEM Object Viewer)

Description

Notifies the control when the WMI object instance is deleted. This allows a custom view to reflect the non-existence of a specified object.

Syntax

void ExternInstanceDeleted(
  BSTR szObjectPath
);

Parameters

szObjectPath
The full path of the WMI class object.

Return Values

Nothing.


GetContext (WBEM Object Viewer)

Description

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.

Syntax

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

Returns S_OK if the context is successfully returned; otherwise, it returns a failure code.


GetEditMode (WBEM Object Viewer)

Description

Returns the current state of the edit mode flag.

Syntax

long GetEditMode();

Parameters

None.

Return Values

Returns 1 (true) if the view's data can be edited. Returns 0 (false) if the view's data is for browsing only.


GetObjectPath (WBEM Object Viewer)

Description

Returns the object path at the given object position.

Syntax

BSTR GetObjectPath(
  [in] long lPosition
);

Parameters

lPosition
Identifies the position of the object. Can be one of:

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 WBEM Object Viewer, 0 is the only valid lPosition value. Any other value returns an error.

Return Values

Returns the object's path, if an object exists at the specified position. Returns null, if no object exists at the specified position.


GetObjectTitle (WBEM Object Viewer)

Description

Returns a title for the specified object that is suitable for display to the user. The title is not necessarily the object path.

Syntax

BSTR GetObjectTitle(
  long lPosition
);

Parameters

lPosition
Position of the current object. This parameter must be 0.

Return Values

If lPosition is 0, returns the title of the current object. Otherwise, it returns an error.


GetPropertyFilter (WBEM Object Viewer)

Description

Obtains the property filter.

Syntax

long GetPropertyFilter();

Parameters

None.

Return Values

Returns the PropertyFilter flags.

See Also

PropertyFilter, SetPropertyFilter


GetTitle (WBEM Object Viewer)

Description

Obtains the title and icon to display in the title bar.

Syntax

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. This parameter should be null if no icon should be displayed. If this parameter is invalid, the control returns an error.

Return Values

Returns S_OK if the title and icon are returned; otherwise, it returns E_FAIL.


GetViewTitle (WBEM Object Viewer)

Description

Obtains 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.

Syntax

BSTR GetViewTitle(
  long lPosition
);

Parameters

lPosition
Specifies the position of the view to be retrieved.

Return Values

The view title.


NextObject (WBEM Object Viewer)

Description

Returns the position of the next object in the current view.

Syntax

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 successful, returns the position of the next object; otherwise, it returns an error.

Remarks

Not yet implemented. Returns only minus one.

See Also

PrevObject, StartObjectEnumeration


NextViewTitle (WBEM Object Viewer)

Description

Obtains the title of the view at the next position.

Syntax

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

The position of the view title is returned. The value -1 is returned if there is no next view.

See Also

PrevViewTitle, StartViewEnumeration


PrevObject (WBEM Object Viewer)

Description

Returns the position of the previous object in the current view.

Syntax

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 successful, returns the position of the previous object; otherwise, it returns an error.

Remarks

Not yet implemented. Returns only minus one.

See Also

NextObject, StartObjectEnumeration


PrevViewTitle (WBEM Object Viewer)

Description

Obtains the title of the view at the previous position. This method is useful when enumerating view titles.

Syntax

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
Receives the view title.

Return Values

Returns the position of the view title. The value -1 is returned if there is no previous view.

See Also

NextViewTitle, StartViewEnumeration


QueryCanCreateInstance (WBEM Object Viewer)

Description

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.

Syntax

long QueryCanCreateInstance();

Parameters

None.

Return Values

Returns True if a new class instance can be created; otherwise, it returns False. When used in the WBEM Multiple Instances Viewer, this method should only return False; any other value returns an error.

See Also

CreateInstance


QueryCanDeleteInstance (WBEM Object Viewer)

Description

Determines whether to call DeleteInstance to delete the current instance. If this method is not called prior to calling DeleteInstance, the control returns an error.

Syntax

long QueryCanDeleteInstance();

Parameters

None.

Return Values

Returns True if the current instance can be deleted; returns False if the current instance cannot be deleted or if there is no current instance to delete.

See Also

DeleteInstance


QueryNeedsSave (WBEM Object Viewer)

Description

Determines whether the current object has been modified and must be saved. The modified object can be saved by calling SaveData.

Syntax

long QueryNeedsSave();

Parameters

None.

Return Values

Returns True if the current object has been modified and must be saved; otherwise, it returns False. When used in the WBEM Multiple Instances Viewer, this method should only return False; any other value returns an error.

See Also

SaveData


QueryObjectSelected (WBEM Object Viewer)

Description

Determines whether the object is selected.

Syntax

long QueryObjectSelected();

Parameters

None.

Return Values

Returns True if object is selected; otherwise, it returns False.

Remarks

Not yet implemented. Returns only TRUE.


RefreshView (WBEM Object Viewer)

Description

Reloads the contents of the current view from the Common Information Model (CIM) repository.

Syntax

long RefreshView();

Parameters

None.

Return Values

Returns S_OK if the reload is successful; otherwise, it returns a failure code.


ReleaseContext (WBEM Object Viewer)

Description

Decrements the reference count for the specified context handle.

Syntax

long ReleaseContext(
  long lCtxtHandle
);

Parameters

lCtxtHandle
The context handle. If this parameter is null or invalid, the control returns an error.

Return Values

Returns S_OK if the reference count is decremented; otherwise, it returns a failure code.


RestoreContext (WBEM Object Viewer)

Description

Restores the state of the control to the previously-saved context.

Syntax

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

Returns S_OK if the view's context could be restored; otherwise, it returns a failure code.


SaveData (WBEM Object Viewer)

Description

Saves changes to the current object.

Syntax

long SaveData();

Parameters

None.

Return Values

Returns S_OK if the changes are saved; otherwise, it returns a failure code.


SelectObjectByPath (WBEM Object Viewer)

Description

Selects the specified object using the object path. The object path must be an absolute path.

Syntax

long SelectObjectByPath(
  BSTR szObjectPath
);

Parameters

szObjectPath
The WMI object path. If this parameter is null or invalid, the control returns an error.

Return Values

Returns S_OK if the object is selected; otherwise, it returns an error.


SelectObjectByPointer (WBEM Object Viewer)

Description

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.

Syntax

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

Returns S_OK if the object is selected; otherwise, it returns an error.

See Also

IWbemClassObject


SelectObjectByPosition (WBEM Object Viewer)

Description

Selects an object in the current view 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.

Syntax

long SelectObjectByPosition(
  long lPosition
);

Parameters

lPosition
The object position in the current view.

Return Values

Returns S_OK if the object selection succeeds; otherwise, it returns a failure code.

Remarks

Not yet implemented. Returns only S_OK.


SelectView (WBEM Object Viewer)

Description

Selects the specified view.

Syntax

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

Returns S_OK if the view selection succeeds; otherwise, it returns an error.

See Also

NextViewTitle, PrevViewTitle, StartViewEnumeration


SetEditMode (WBEM Object Viewer)

Description

Sets the view's edit mode flag.

Syntax

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

Nothing.


SetPropertyFilter (WBEM Object Viewer)

Description

Sets the property filter.

Syntax

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

Sets the PropertyFilter flags.

See Also

PropertyFilter, GetPropertyFilter


StartObjectEnumeration (WBEM Object Viewer)

Description

Starts the enumeration of objects.

Syntax

long StartObjectEnumeration(
  long lWhere
);

Parameters

lWhere
Expects 0 which is the current object. Any other value returns an error.

Return Values

Returns S_OK if the object selection is successful; otherwise, it returns E_FAILED.

Remarks

Not yet implemented. Returns only zero.


StartViewEnumeration (WBEM Object Viewer)

Description

Starts the enumeration of custom views.

Syntax

long StartViewEnumeration(
  [in] long lWhere
);

Parameters

lWhere
Specifies the view from which to start enumerating. It can be one of the following:

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 view position is the value returned. If this value is -1, there are no alternate views.


Events (WBEM Object Viewer)

This section contains events for the WBEM Object Viewer control.


GetIWbemServices (WBEM Object Viewer)

Description

Occurs when the control wants to connect to a namespace. This event retrieves an IWbemServices pointer for the current namespace and object path.

Syntax

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


JumpToMultipleInstanceView (WBEM Object Viewer)

Description

Requests the display of a multiple-instance view of an array of objects.

Syntax

void JumpToMultipleInstanceView(
  BSTR szTitle,
  VARIANT varPathArray
);

Parameters

If any of the following parameters is null or invalid, the control returns an error.

szTitle
The title to be displayed for the multiple instances.
varPathArray
An array of WMI object paths.


NOTIFYChangeRootOrNamespace (WBEM Object Viewer)

Description

Notifies the container when the user has changed the root or the namespace.

Syntax

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 WBEM Object Viewer, this contains the value True.


NotifyContextChanged (WBEM Object Viewer)

Description

Notifies the container when the current context changes.

Syntax

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, this value is True. Otherwise, this value is False. If this parameter is null or invalid, the control returns an error.


NotifyInstanceCreated (WBEM Object Viewer)

Description

Notifies the container when a new WMI object instance is created.

Syntax

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 (WBEM Object Viewer)

Description

Notifies the container when the current object is modified and must be saved.

Syntax

void NotifySaveRequired();

Parameters

None.


NotifySelectionChanged (WBEM Object Viewer)

Description

The event notifies the container that a new object is selected in a custom view. This event is fired when the user clicks selects an instance in the viewer usng the left mouse button.

Syntax

void NotifySelectionChanged();

Parameters

None.


NotifyViewModified (WBEM Object Viewer)

Description

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.

Syntax

void NotifyViewModified();

Parameters

None.


RequestUIActive (WBEM Object Viewer)

Description

Occurs when the control wants to go UI active and may be embedded in an ActiveX control.

Syntax

void RequestUIActive();

Parameters

None.


WBEM Object Viewer Container

The WBEM Object Viewer Container ActiveX control provides navigation features for the WBEM Object Viewer and the WBEM 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


Properties (WBEM Object Viewer Container)

This section contains properties for the WBEM Object Viewer Container control.


NameSpace (WBEM Object Viewer Container)

Definition

BSTR NameSpace

Description

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.


ObjectPath (WBEM Object Viewer Container)

Definition

VARIANT ObjectPath

Description

Returns or sets the WMI object path of the object or class you want to view. This property 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 parameter is null or invalid, the control returns an error.


ReadyState (WBEM Object Viewer Container)

Definition

long ReadyState

Description

Indicates the current state of readiness of a control during a potentially asynchronous download process. This property cannot be set.

Values

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 (WBEM Object Viewer Container)

Syntax

long StatusCode

Description

Stores the most recent status code when an object path is selected.


StudioModeEnabled (WBEM Object Viewer Container)

Syntax

long StudioModeEnabled

Description

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 parameter is null or invalid, the control returns an error.


Methods (WBEM Object Viewer Container)

This section contains methods for the WBEM Object Viewer Container control.


QueryViewInstances (WBEM Object Viewer Container)

Description

Displays the instances returned by a query.

Syntax

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 (WBEM Object Viewer Container)

Description

Saves any WMI objects that have been modified.

Syntax

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 (WBEM Object Viewer Container)

Description

Shows a multiple instance view of the instances specified by the array of object paths.

Syntax

void ShowInstances(
  BSTR szTitle,
  VARIANT varPathArray
);

Parameters

If any of these parameters is null or invalid, the control returns an error.

szTitle
The view title.
varPathArray
The WMI paths to the instances.

Return Values

Nothing.


Events (WBEM Object Viewer Container)

This section contains events for the WBEM Object Viewer Container control.


GetIWbemServices (WBEM Object Viewer Container)

Description

Occurs when the control wants to connect to a namespace. This event retrieves an IWbemServices pointer for the current namespace and object path.

Syntax

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 (WBEM Object Viewer Container)

Description

Notifies the container when the user has changed the root or the namespace.

Syntax

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 WBEM Object Viewer, this contains the value True.


RequestUIActive (WBEM Object Viewer Container)

Description

Occurs when the control wants to go UI active and may be embedded in an ActiveX control.

Syntax

void RequestUIActive();

Parameters

None.


SQL for WMI

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 ODBC 2.0 Programmer's Reference and SDK Guide.


ODBC Minimum SQL Grammar

The adapter supports a subset of the ODBC Minimum SQL Grammar. It does not support data definition language (DDL) constructs and writable 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.

SELECT Statement Grammar (Minimum Level ODBC SQL Conformance)

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 post-fix 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.

The Level 1 Provider SQL Grammar

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. Functions that require extensive descriptions have their own topics, as noted in the Description column.

ODBC Function | Description
SQLAllocConnect | This is a standard ODBC function that allocates memory for a connection handle.
SQLAllocEnv | This is a standard ODBC function that allocates memory for an environment handle.
SQLAllocStmt | Modified to support inclusion of table qualifiers.
SQLBindCol | Supported.
SQLBindParameter | Supported.
SQLCancel | Used to cancel a function executing asynchronously on a statement handle that needs data.
SQLColAttributes | See SQLColAttributes_Core_.
SQLColumns | See SQLColumns_Extended_Level_1_..
SQLConnect | The user of SQLConnect must only specify a data source name.
SQLDataSources | Implemented in the Adapter Manager.
SQLDescribeCol | Similar to SQLColumns attributes. Imposes no requirements upon the property qualifiers in the WMI class objects beyond those specified in SQLColumns.
SQLDisconnect | Supported.
SQLDriverConnect | See SQLDriverConnect_Extension_Level_1_.
SQLDrivers | Implemented in the Adapter Manager.
SQLError | See SQLError_Core_.
SQLExecDirect | Supported.
SQLExecute | Supported.
SQLExtendedFetch | Clients usually only need SQLFetch. However, SQLExtendedFetch returns rowset data in array form for each bound column, and it can scroll through the data.
SQLFetch | Supported.
SQLFreeConnect | Supported.
SQLFreeEnv | Supported.
SQLFreeStmt | Supported.
SQLGetConnectOption | See SQLGetConnectOption_Extension_Level_1_.
SQLGetCursorName | See ODBC 2.0 Programmer's Reference and SDK Guide.
SQLGetData | See ODBC 2.0 Programmer's Reference and SDK Guide.
SQLGetFunctions | See SQLGetFunctions_Extension_Level_1_.
SQLGetInfo | See SQLGetInfo_Extension_Level_1_
SQLGetStatementOption | See SQLGetStatementOption_Extension_Level_1_
SQLGetTypeInfo | See SQLGetTypeInfo_Extension_Level_1_
SQLMoreResults | Supported.
SQLNumResultCols | Supported.
SQLParamData | Supported.
SQLPrepare | Supported.
SQLPutData | Supported.
SQLRowCount | Supported.
SQLSetConnectOption | See SQLGetConnectOption for a discussion of the options and what they mean for the adapter.
SQLSetCursorName | Supported.
SQLSetScrollOptions | Superseded by SQLSetStmtOption in ODBC 2.0. ODBC 2.0 Extension Level 2 adapters should implement SQLSetScrollOptions for backward compatibility with ODBC 1.0 applications.
SQLSetStmtOption | See SQLGetStatementOption .
SQLSpecialColumns | Only fColType equal to SQL_BEST_ROWID is supported.
SQLStatistics | Supported.
SQLTables | See SQLTables_Extension_Level_1_.


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. See SQLColumns for a description of how this information is retrieved. 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, which is a label that utilities can use to describe a column. For use with the 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 (hstmt, "DatabaseName", SQL_NTS,  // qualifier
NULL, 0,                                     // owner
"TcpConnectionTable", SQL_NTS,               // table
"%",SQL_NTS);                                // all columns

The following table shows what information is returned in a rowset.

Column Name | Data Type | Description
TABLE_QUALIFIER_NAME | Varchar (128) | The table qualifier. This corresponds to the database name.
TABLE_OWNER | Varchar (128) | Not used.
COLUMN_NAME | VarChar (128) | The 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 | The precision of the column in the SMIR.
LENGTH | Integer | The length of the column.
SCALE | SmallInt | The scale of the column.
RADIX | SmallInt | The radii of the column.
NULLABLE | SmallInt, not NULLable | Indicates whether the column is nullable.
REMARKS | Varchar (254) | A description of the column.
ATTRIBUTES | Longvarchar (16384) | The 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. 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)

You can use the SQLDriverConnect function to connect an application to a data source.

In the connection string to SQLDriverConnect, the caller specifies either:

  • "DSN=dataSourceName" (it can optionally include the correlation keywords as described below), or
  • "DRIVER=driverName" (it can optionally include the correlation keywords as described below).

In addition to the standard data source name, user name, and password, the adapter uses the following attribute-keywords: NAMESPACES, DBQ, HOME, SERVER, SYSPROPS. AUTHORITY, LOCALE, UIDPWDDEFINED and IMPERSONATE, PASSTHROUGHONLY.

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 is not SQL_NO_PROMPT), then a 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. The bitmap image looks like a check box with a folder.

Clicking within the area of the check box or folder selects or clears the selection of the namespace. If the namespace tree control item has not been expanded (a PLUS SIGN is seen on the left), then the selection or cancellation of the selection, depending on its current state, occurs recursively. If the item is already expanded (or has no child tree items), then only the tree control item is affected.

The state of each tree control item is represented as follows:

  • Clear Unchecked Checkbox. Item is not selected and no child items (if any) are selected.
  • Gray Unchecked Checkbox. Item is not selected. However, at least one child item is selected.
  • Clear Checked Checkbox. Item is selected but no child items (if any) are selected.
  • Gray Checked Checkbox. Item is selected and at least one child item is selected.

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.

If you click the Browse button, a new Server Selection dialog box is displayed. This presents information similar to the Network Neighborhood. The dialog box initially displays the network resources on the LAN. There is also a link to view the entire network (represented by a globe). If you double-click on an image that does not represent a server, then the current display is cleared and the contents of the chosen network resource are displayed.

The dialog box also has three bitmap buttons:

  • You can use the Folder button to go back to the previous network resource selection.
  • The Link view button displays all the network resources as a list.
  • The Report view button displays all the network resources as a report.


SQLError (Core)

The 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 readily discoverable 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.

Option | Possible Values
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 | YES
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 | 'Y' Can select on all tables returned by SQLTables.
SQL_ACTIVE_ CONNECTIONS | 0 Maximum number of active connections that the adapter can support (0 means no limit).
SQL_ACTIVE_ STATEMENTS | 0 Maximum number of active statements on a given connection (0 means no limit).
SQL_ALTER_TABLE | 0X0000 A bitmask indicating how the columns of a table can be altered.
SQL_BOOKMARK_ PERSISTENCE | 0x0000 A bitmask indicating persistence of bookmarks. The adapter does not support bookmarks.
SQL_COLUMN_ALIAS | 'N' The adapter does not support column aliasing.
SQL_CONCAT_ NULL_BEHAVIOR | SQL_CB_NON_NULL The result is the concatenation of non-null valued columns.
SQL_CONVERT_ XXXXXXXXX | 0X0000 The adapter does not support the Convert Scalar Function.
SQL_CONVERT_ FUNCTIONS | 0X0000 The adapter does not support the Convert Scalar Functions.
SQL_CORRELATION_NAME | SQL_CN_ANY The correlation name can be any user-defined name.
SQL_CURSOR_ COMMIT_BEHAVIOR | SQL_CB_CLOSE Close cursor after a commit operation. Cursors are unsupported.
SQL_CURSOR_ COMMIT_BEHAVIOR | SQL_CB_CLOSE Close cursor after a rollback operation. Cursors are unsupported.
SQL_DATA_ SOURCE_NAME | The data source name.
SQL_DATA_ SOURCE_READONLY | '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 the version number of the MO Server. This can be obtained from a standard WMI class.
SQL_DEFAULT_ TXN_ISOLATION | 0x0000 The adapter does not support transactions.
SQL_DRIVER_HDBC | Implemented by the Adapter Manager. It returns the adapter's connection handle.
SQL_DRIVER_HENV | Implemented by the Adapter Manager. It returns the adapter's environment handle.
SQL_DRIVER_HLIB | Implemented by the Adapter Manager. The library handle returned to the Adapter Manager when the Adapter Manager loaded the adapter library.
SQL_DRIVER_HSTMT | Implemented by the Adapter Manager. It returns the adapter's statement handle.
SQL_DRIVER_NAME | WBEM DR32.DLL
SQL_DRIVER_ ODBC_VERSION | "02.10.0000".
SQL_EXPRESSION_ IN_ORDERBY | "n" The adapter does not support expressions in the ORDER BY clause.
SQL_FETCH_DIRECTION | 0x0000 The adapter does not support cursors.
SQL_FILE_USAGE | SQL_FILE_NOT_SUPPORTED - The adapter is not a single-tier adapter.
SQL_GETDATA_ EXTENSIONS | SQL_GD_ANY_COLUMN | SQLGD_ANY_ORDER | SQL_GD_BOUND.
SQL_GROUP_BY | SQL_GROUP_BY_NOT_SUPPORTED. The core SQL grammar does not require support for GROUP BY.
SQL_IDENTIFIER_CASE | SQL_IC_MIXED This means 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 | "\"".
SQL_KEYWORDS | "" No data source-specific keywords.
SQL_LOCK_TYPES | 0x0000.
SQL_MAX_BINARY_ LITERAL_LEN | 0L No limit on a binary literal in a SQL statement.
SQL_MAX_CHAR_ LITERAL_LEN | Set to 255.
SQL_MAX_COLUMN_NAME_LEN | 0 No limit.
SQL_MAX_COLUMNS_ IN GROUP_BY | 0 No limit.
SQL_MAX_COLUMNS_ IN_INDEX | 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 | 0 No limit on the number of columns in a select.
SQL_MAX_COLUMNS_ IN_TABLE | 0 No limit on the number of columns in a table.
SQL_MAX_CURSOR_ NAME_LEN | Set to 19.
SQL_MAXINDEX_SIZE | 0 No limit.
SQL_MAX_OWNER_ NAME_LEN | 0 No limit.
SQL_MAX_PROCEDURE_ NAME_LEN | 0 No limit. The limit does not matter because the adapter does not support procedures.
SQL_MAX_QUALIFIER_ NAME_LEN | 0 No limit.
SQL_MAX_ROW_SIZE | 0 No limit.
SQL_MAX_ROW_SIZE_ INCLUDES_LONG | "Y" The maximum row size returned by SQL_MAX_ROW_SIZE includes the length of SQL_LONG_VARCHAR and SQL_LONGVARBINARY.
SQL_MAX_ STATEMENT_LEN | 0L No limit on the size of a SQL statement.
SQL_MAX_ TABLE_NAME_LEN | 128.
SQL_MAX_ TABLES_IN_SELECT | 0 No limit on the number of tables in select statement.
SQL_MAX_ USER_NAME_LEN | Set to 63.
SQL_MULT_ RESULT_SETS | "N" The adapter does not support multiple result sets.
SQL_MULTIPLE_ ACTIVE_TXN | "N" Does not matter, as transactions are not supported.
SQL_NEED_LONG_ DATA_LEN | "N"
SQL_NON_ NULLABLE_COLUMNS | SQL_NNC_NON_NULL
SQL_NULL_COLLATION | SQL_NC_LOW NULLs are sorted at the low end of a list.
SQL_NUMERIC_FUNCTIONS | 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 | SQL_OAC_LEVEL
SQL_ODBC_SAG_ CLI_CONFORMANCE | SQL_OSCC_COMPLIANT
SQL_ODBC_ SQL_CONFORMANCE | SQL_OSC_MINIMUM
SQL_ODBC_ OPT_IEF | "N" The adapter does not support Integrity Enhancement Facility.
SQL_DRIVER_VER | "01.00.0000".
SQL_ORDER_BY_ COLUMNS_IN_SELECT | "N" The columns in the ORDER BY clause do not need to be in the select list.
SQL_OUTER_JOINS | "Y"
SQL_OWNER_TERM | "" Character string with the data source vendor's name for an owner.
SQL_OWNER_USAGE | 0x0000 The owner is not supported in any statements.
SQL_POS_OPERATIONS | 0x0000 The adapter does not have cursors.
SQL_POSITIONED_ STATEMENTS | 0x0000 The adapter does not have cursors.
SQL_PROCEDURE_TERM | "" The adapter does not support procedures.
SQL_PROCEDURES | "N" The adapter does not support procedures.
SQL_QUALIFIER_LOCATION | SQL_QL_START The qualifier comes first in a qualified table name; for example, Wellfleet.TcpConnectionTable, and not TcpConnectionTable.Wellfleet.
SQL_QUALIFIER_ NAME_SEPARATOR | ".".
SQL_QUALIFIER_TERM | "Namespace".
SQL_QUALIFIER_USAGE | 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 since the adapter does not support procedures, table creation, or indexes, these items are not relevant.
SQL_QUOTED_ IDENTIFIER_CASE | SQL_IC_MIXED Quoted identifiers are case-insensitive and are stored in mixed case.
SQL_ROW_UPDATES | "N" The adapter does not support scrollable cursors.
SQL_SCROLL_CONCURRENCY | 0x0000 The adapter does not support scrollable cursors.
SQL_SCROLL_OPTIONS | 0x0000 The adapter does not support scrollable cursors.
SQL_SEARCH_ PATTERN_ESCAPE | "\" is a search pattern escape character for % and _.
SQL_SERVER_NAME | "" Unnecessary
SQL_SPECIAL_CHARACTERS | "" This 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 | 0x0000 The adapter does not support cursors.
SQL_STRING_FUNCTIONS | 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 | 0x0000 The adapter does not support sub-queries in predicates.
SQL_SYSTEM_FUNCTIONS | SQL_FN_SYS_DBNAME | SQL_FN_SYS_IFNULL | SQL_FN_SYS_USERNAME
SQL_TABLE_TERM | "Class".
SQL_TIMEDATE_ ADD_INTERVALS | 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 | 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 | 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 | SQL_TC_NONE The adapter does not support transactions.
SQL_TXN_ ISOLATION_OPTION | 0x0000 The adapter does not support transactions.
SQL_UNION | 0x0000 The data source does not support the UNION clause.
SQL_USER_NAME | "" 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 | The adapter does not support SQLExtendedFetch, so calling the function with this option returns an error.
SQL_CONCURRENCY | The 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_CURSOR_TYPE | The 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 | The 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 The adapter scans statements for escape clauses.
SQL_QUERY_TIMEOUT | The number of seconds to wait for a query to execute without returning to the caller.
SQL_RETRIEVE_DATA | The 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 | The 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 | The 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 | The 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 ODBC adapter must support are the variant types. In addition, WMI defines the Cimtype attribute 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]
    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

-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.
-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.
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, some qualifier flavors are not 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> <opt_where>;
<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>;
<trailing_prop_expr2> ::= OPEN_PAREN <property_name> CLOSE_PAREN;
<trailing_prop_expr2> ::= <>;

<leading_ident_expr> ::= OPEN_PAREN <unknown_func_expr>;
<leading_ident_expr> ::= <comp_operator> <trailing_const_expr>;
<leading_ident_expr> ::= <equiv_operator> <trailing_or_null>;
<leading_ident_expr> ::= <is_operator> NULL;

<unknown_func_expr> ::= <property_name> CLOSE_PAREN <rel_operator> <trailing_const_expr>;
<unknown_func_expr> ::= <typed_constant> CLOSE_PAREN <rel_operator> <trailing_prop_expr>;

<trailing_or_null> ::= NULL;
<trailing_or_null> ::= <trailing_const_expr>;

<trailing_const_expr> ::= <typed_constant>;
<trailing_const_expr> ::= <property_name> OPEN_PAREN <typed_constant> CLOSE_PAREN;

<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;  // <=, >=, <, >
<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


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


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 compiled language for defining classes and instances. The MOF compiler offers a textual means of adding data to the CIM repository. MOF eliminates the need to write code, thus providing a simple and fast technique for modifying 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 Desktop 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.


Starting the Windows Management Service

With the winmgmt command, you can use the switch /exe, /regserver, or /unregserver to start Windows Management Service.

Note The Windows Management Service starts automatically on computers running Microsoft® Windows NT®/Windows® 2000, but not on computers running Microsoft® Windows® 95/98. 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 Windows Management Service, click the Start button and point to Run. The Run dialog box opens. In the Open box, use the following syntax.

winmgmt [/exe] [/regserver] [/unregserver]
/exe
Causes the Windows Management Service to run as an application rather than as a Windows NT/Windows 2000 service. Use this switch only with Windows 95/98. When you run Winmgmt.exe with the /exe switch, the application displays the Windows Management Service icon while running.
/regserver
Registers the Windows Management Service, adding entries to the operating system registry.
/unregserver
Removes registry entries added through the self-registration process.


Halting the Windows Management Service

  • Computers Running Microsoft® Windows NT®/Windows® 2000
  • Computers Running Microsoft® Windows® 95/98


Computers Running Microsoft® WindowsNT®/Windows®2000

WMI SDK

Computers Running Microsoft® Windows NT®/Windows® 2000

To stop the Windows Management Service, run the winmgmt command with the /kill switch, as described following.

To stop the Windows Management Service on computers running Microsoft® Windows NT®/Windows® 2000 or Microsoft® Windows® 95/98, click the Start button and point to Run. The Run dialog box opens. In the Open box, use the following syntax.

winmgmt /kill
/kill
Causes all running copies of the Windows Management Service to stop, whether the copy is an application or a Windows NT/Windows 2000 service.


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\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\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
/S | Displays information about this instance or class, or all subclasses.
/S2 | Displays information about all namespaces, or all namespaces within namespaces.
/E | Shows system classes and properties.
/E1 | Shows system classes and properties except __SERVER or __PATH properties.
/E2 | Shows command lines for dumping instances.
/D | Hides properties.
/G | Enumerated instances are returned by the Getobject call.
/M | Gets Class Managed Object Formats (MOF) instead of data values.
/M2 | Gets Instance MOFs instead of data values.
/M3 | Produces instance template.
/B:<num> | Produces CreateEnum flags (SemiSync=16; Forward=32).
/W | Prompts to continue on warning errors.
/WY | Prints warnings and continue.
/H:<name>:<value> | Specifies context object value.
/CQV:<name>[:value] | Specifies a class qualifier or qualifier value by which you can filter.
/T | Prints execution times for /Q queries.
/O:<file> | Files name for output (creates Unicode file).
/C:<file> | Contains command file with multiple WBEMDUMP command lines. The same namespace must be used for each of the command lines.
/U:<UserID> | Connects UserID with (default: NULL).
/P:<Password> | Password to use when connecting to WMI (default: NULL)
/A:<Authority> | Sets authority to use when connecting to WMI .
/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.

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 /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 /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 /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 /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 /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 /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 /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.


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 /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 /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:' "

(WQL) SELECT DeviceId FROM Win32_logicaldisk WHERE deviceID='C:'

ExecQuery 0.1100 seconds.

DeviceID (CIM_STRING/string)* = "C:"

ShowInstances 0.0630 seconds.


Wbemdump /O:<file>

This is the file name for output (creates Unicode file).


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 /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 /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 /A:<Authority>

This switch causes the command to connect using the authority that you specify with the parameter Authority.


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


WMI Appendix

The Windows Management Instrumentation (WMI) SDK Appendix includes the following topics:

  • WMI Schema
  • Getting Help from Microsoft Technical Support


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.

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


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, 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 Region
    Microsoft Taiwan Region 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


Computers Running Microsoft® Windows® 95/98

WMI SDK

Computers Running Microsoft® Windows® 95/98


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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


WMI SDK

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."


WMI SDK

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."


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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."


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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."


WMI SDK

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.


WMI SDK

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."


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

Fatal Error 1451

<1451, Fatal>: "Could not connect to the SMIR"
SMIR interaction error.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

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.


WMI SDK

Fatal Error 108

<108, Fatal>: "No command argument specified"
Command-line syntax error. Some action must be specified on the command line.


WMI SDK

Fatal Error 109

<109, Fatal>: "Module name missing"
Command-line syntax error.


WMI SDK

Warning 230

<230, Warning>: "<fileName>:<line#>: '<the wrong token>' used. Assuming '::=' "
The token ":=", "::", or "=" has been used instead of "::=".


WMI SDK

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.


WMI SDK

Information Message 211

<211, Information>: "Skipping TRAP-TYPE <identifier>"
Any errors in the TRAP-TYPE definition generate this message.


WMI SDK

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.


WMI SDK

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.


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.