Microsoft Windows Management Instrumentation Scripting

 

Microsoft Corporation

April 1999

Summary: Presents brief overviews of the Common Information Model (CIM) and the Windows Management Instrumentation (WMI) architecture. Includes an in-depth discussion on the WMI scripting API. Covers:

Introduction
Common Information Model Overview
WMI Architecture Overview
WMI Scripting Interface
WMI Scripts Usage
Conclusion
For More Information

Introduction

The Windows® Management Instrumentation (WMI) technology is an implementation of the Desktop Management Task Force's (DMTF) Web-Based Enterprise Management (WBEM) initiative for Microsoft® Windows platforms that extends the Common Information Model (CIM) to represent management objects in Windows management environments. The Common Information Model, also a DMTF standard, is an extensible data model for logically organizing management objects in a consistent, unified manner in a managed environment.

Based on the Common Information Model, WBEM is a DMTF initiative and technology that provides a standardized way to access management information in an enterprise environment. With WBEM, developers can create tools and technologies that reduce the complexity and costs of enterprise management. By providing such standards, WBEM contributes to the industry-wide efforts to lower Total Cost of Ownership (TCO). TCO refers to the administrative costs associated with computer hardware and software purchases, deployment and configuration, hardware and software updates, training, maintenance, and technical support.

WBEM provides a point of integration through which data from management sources can be accessed, and it complements and extends existing management protocols and instrumentation such as Simple Network Management Protocol (SNMP), Desktop Management Interface (DMI), and Common Management Information Protocol (CMIP).

The WBEM initiative results from the cooperative efforts of BMC Software Inc., Cisco Systems Inc., Compaq Computer Corp., Intel Corp., and Microsoft Corp., as well as many other companies active in the DMTF.

Windows Management Instrumentation Technology

The Windows Management Instrumentation (WMI) technology, Microsoft's implementation of WBEM, is a management infrastructure that supports the syntax of CIM, the Managed Object Format (MOF), and a common programming interface. The Managed Object Format is used to define the structure and contents of the CIM schema in human and machine-readable form. Windows Management Instrumentation offers a powerful set of services, including query-based information retrieval and event notification. These services and the management data are accessed through a Component Object Model (COM) programming interface. The WMI scripting interface also provides scripting support.

The WMI technology provides:

  • Access to monitor, command and control any entity through a common, unifying set of interfaces, regardless of the underlying instrumentation mechanism. WMI is an access mechanism.
  • A consistent model of Microsoft Windows® 2000 operating system operation, configuration, and status.
  • A COM application programming interface (API) that supplies a single point of access for all management information.
  • Interoperability with other Windows 2000 management services. This approach can simplify the process of creating integrated, well-architected management solutions.
  • A flexible, extensible architecture. Developers can extend the information model to cover new devices, applications, and so on, by writing code modules called WMI Providers, described later in this document.
  • Extensions to the Windows Driver Model (WDM) to capture instrumentation data and events from device drivers and kernel side componentry.
  • A powerful event architecture. This allows management information changes to be identified, aggregated, compared, and associated with other management information. These changes can also be forwarded to local or remote management applications.
  • A rich query language that enables detailed queries of the information model.
  • A scriptable API that developers can use to create management applications. The scripting API supports several languages, including Microsoft Visual Basic®; Visual Basic for Applications (VBA); Visual Basic, Scripting Edition (VBSript); Microsoft JScript® development software. Besides VBScript and JScript, developers can use any scripting language implementation that supports Microsoft's ActiveX® Scripting technologies with this API (for example, a Perl scripting engine). Additionally, you can use the Windows Script Host or Microsoft Internet Explorer to write scripts utilizing this interface. Windows Script Host, like Internet Explorer, serves as a controller engine of ActiveX scripting engines. Windows Script Host supports scripts written in VBScript, and JScript. The scripting API is the focus of this document.

Common Information Model Overview

The Common Information Model, created by the DMTF as part of the WBEM initiative, is an approach to system, software, networks, device, and user management that is based on the object-oriented paradigm. CIM provides a standard, unified conceptual framework for describing physical and logical objects in a managed environment. To provide a common framework, CIM defines a series of objects with respect to a basic set of classes, and classifications and associations.

CIM includes the following information models:

  • A core model—incorporates notions applicable to all management domains.
  • Common models—incorporate notions common to specific management domains, independent of particular technologies or implementations. Common domains include systems, applications, devices, users, and networks. These models provide a basis for the development of management applications, and include a set of base classes for extension into technology-specific areas.
  • Extension models—these represent technology-specific extensions of the common models. These models are specific to environments, such as operating systems (for example, UNIX or the Microsoft Windows operating system).

Object-Oriented Design and Constructs

Using an object-oriented approach provides:

  • Object abstraction and classification—to decrease the complexity of managed domains, managed objects are defined and grouped into classes based on common properties, associations with other classes, and methods. Managed objects are either physical or logical enterprise components that are modeled using CIM. For example, a managed object can be hardware such as a cable or system chassis, software such as a database application, or other logical entities such as computer systems, files, and devices.
  • Object inheritance—by creating subclasses from the high-level, fundamental objects, developers can add the appropriate level of detail and complexity to the model. Subclasses inherit all the properties, methods, and associations of their higher-level parent objects.
  • Ability to model dependencies, component, and connection associations—using the object-oriented paradigm, the relationships between objects and their associations can be modeled directly. The ways in which such relationships are named and defined describe the semantics of the object associations. Properties of the associations can be used to provide additional semantics and information. Previously, before CIM, management standards had to capture relationships between managed objects in multidimensional arrays or in cross-referenced data tables.
  • Standard inheritable methods—defining standard object methods (behavior), provides another level of abstraction. These methods, in turn, can be bundled with an object's data to provide encapsulation, providing additional flexibility. By way of illustration, consider the possibilities of a standard able to invoke a Reboot method when a computer hangs, regardless of the hardware, operating system, or device.

CIM aims to model all aspects of managed environments. By defining objects, and their properties, methods, and associations in a uniform manner, information from networks, devices, systems, and applications can be accessed more easily by management applications, and more powerful management capabilities can be implemented.

The next section describes the Windows Management Instrumentation technology architecture.

WMI Architecture Overview

The WMI technology architecture consists of the following:

  • A management infrastructure. This includes the CIM Object Manager, which provides applications with uniform access to management data and a central storage area for management data called the CIMOM object repository.
  • WMI Providers. These function as intermediaries between the CIM Object Manager and managed objects. Using the WMI APIs, Providers supply the CIM Object Manager with data from managed objects, handle requests on behalf of management applications, and generate event notifications.

The management infrastructure consists of CIM Object Manager and the CIMOM object repository. Applications depend on the Object Manager to handle the interface between management applications and data Providers. WMI facilitates these communications by providing a common programming interface, using COM, to Windows Management Services. This COM API supplies event notification and query processing services and can be used in several programming language environments, such as C and C++. Windows Management Instrumentation also supports Automation scripting in Visual Basic, VBScript, and JScript. Developers can also use any scripting language implementation that supports Microsoft's Active Scripting technologies with this API (such as a Perl scripting engine). The CIMOM repository holds the CIM and extension schemas, and data information or data source details. CIM Object Manager uses the schema data in this repository when servicing requests from management applications for managed objects.

Managed objects are either physical or logical enterprise components that are modeled using CIM. For example, a managed object can be hardware such as a cable, or software such as a database application. Management applications can access managed objects through CIM Object Manager.

Management applications are applications or Windows NT services that use or process information originating from managed objects. Management applications can access managed object information by making a request to CIMOM through one of the methods in the WMI API.

Using WMI technology, you can create management applications that implement numerous features, such as displaying system information, generating an inventory of network resources, and processing and responding to events. WMI supports various strategies to create management applications. For example, applications can use the WMI APIs to access CIM Object Manager directly, or they can access CIM Object Manager indirectly by using the following method:

  • Microsoft Open Database Connectivity (ODBC) driver—Your database applications can use the ODBC driver to combine the ODBC database capabilities with the management capabilities of WMI. This driver enables an application to use various ODBC-based reporting packages and tools, including Microsoft Excel and Microsoft Access.

WMI Providers are standard COM and DCOM (Distributed Component Object Model) servers that function as mediators between managed objects and CIM Object Manager. If CIM Object Manager receives a request from a management application for data that is not available from the CIMOM object repository or for event notifications that are not supported by CIM Object Manager, it forwards the request to a WMI Provider. Providers supply data and event notifications for managed objects that are specific to their particular domain.

To implement a Provider, you should use one of the following supported server types:

  • In-process dynamic-link libraries (DLLs).
  • Microsoft Windows NT services, local or remote.
  • Standard executables (.exe files), local or remote.

The WMI Software Development Kit (previously called the WBEM SDK) includes several built-in ** Providers. These built-in Providers (or standard providers) supply data from sources such as the system registry. The built-in Providers include:

  • Performance Monitor Provider—provides access to Windows NT Performance Monitor data.
  • Registry Provider—provides access to system registry data.
  • Registry Event Provider—sends events when changes occur to registry keys, values, or trees.
  • SNMP Provider—provides access to events and data from SNMP devices.
  • Windows NT Event Log Provider—provides access to data and event notifications from the Windows NT Event Log.
  • Win32® Provider—provides access to data from the Win32 API subsystem.
  • WDM Provider—provides access to data and events from device drivers that conform to the Windows Management Instrumentation interface.

The WMI technology also provides support for third-party custom Providers. Custom Providers can be used to service requests related to managed objects that are environment-specific. Providers typically use the MOF language to define and create classes. Providers use the WMI API to access the CIMOM object repository, and to respond to CIM Object Manager requests made initially by applications.

Additional technical papers on WMI will be available at the following URL: https://www.microsoft.com/ntserver/techresources/default.asp.

The next sections present an overview of the WMI scripting interfaces.

WMI Scripting Interface

The WMI SDK includes a scripting API that you use to create scripts and Visual Basic-based applications to interact with the CIM Object Manager. It supports the following languages:

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

Additionally, you can also use any scripting language implementation that supports Microsoft's Active Scripting technologies with this API (such as a Perl scripting engine).

With the WMI scripting capabilities, you can create scripts for:

  • Server, workstation, and system management. You can write scripts to manage computers, services, drivers, devices, file systems, DNS and DHCP servers, and Windows NT Event Logs. You can also create scripts for network configuration tasks. For example, you can create scripts to start and stop system services, list and monitor system drivers, list records in the Windows NT Event Logs, and so on.
  • Security and user management. For example, you can write scripts to list account information pertaining to a specific domain user or domain group, or to list directory permissions, and so on.
  • Network management. For example, you could write a script to list the configuration of network adapter cards on a specific computer.
  • Printer management. For example, you could write scripts to monitor for printer status or printer tray empty events on a specific printer, or to display the configuration of all locally connected printers, and so on.
  • System health monitoring. For example, you can create scripts to monitor and display the Windows NT Event Log entries added to the local event log files, or to monitor the Windows NT System Monitor log files.

Advantages of Using WMI Scripting

Using WMI for scripting provides the following advantages:

  • Data-driven approach based on the Common Information Model. A single interface is used for manipulating disparate management information, and applications can be isolated from the complexity of various data sources.
  • Rich coverage of system, network, device, and application information. The WMI SDK includes Providers for Win32, SNMP, Registry, Performance Monitor, Windows NT Event Log, and ADSI. Third-party custom Providers can be created to cover vendor-specific instrumentation (for system, applications, devices, and so on). Additionally, Providers will be available for the Microsoft Windows Installer, SQL Server Administration, COM+ Catalog, and SNA Server.
  • Extensible Providers instrumentation. The WMI SDK provides tools, samples, and an extensible Provider architecture. The development of new Providers is supported by the industry.
  • Uses existing technologies. The WMI scripting API uses many of the built-in features of VBScript for Automation such as collections, exception information-passing, and so on.
  • Exposure of CIM properties and methods directly as Automation properties and methods, making it easy to write scripts in a natural and intuitive style.

Scripting Object Model

The following diagram 1 illustrates the principal objects and their relationships within the WMI Scripting Object Model. The boxes represent objects in the scripting model. The boxes with a heavy border represent the objects that the API can create directly, while shaded boxes represent Automation collection objects. An arrow from object A to object B signifies that A can obtain B by calling A using the scripting API relationship. A collection is a standard Automation concept that provides a uniform interface to a set of objects over which iteration can be performed. To manipulate collections using a specific programming language, you use the native features of that language.

Features

The WMI SDK supports the following features to leverage the capabilities of the scripting languages:

  • Object Creation. You can create objects directly using the specified ProgID for these WMI interfaces: SWbemLocator, SWbemObjectPath, SWbemLastError, SwbemSink and SWbemNamedValueSet. The method for creating objects depends on the programming language you use. The WMI scripting model objects are described in the next section.
  • Collections. Several standard Automation collection interfaces are provided in the WMI API. You can manipulate collections by using the native features of each scripting language.
  • Monikers. A Moniker is a COM standard mechanism for encapsulating the location and binding of another COM object. The textual representation of a Moniker is called a Display Name. With the WMI scripting API, you can create SWbemObject and SWbemServices objects in a concise manner using the concept of Moniker Display Names.
  • Direct Access. This feature allows you to access the CIM properties of a CIM or WMI class or instance directly on an SWbemObject, rather than through the Properties_y collection of that object. You can also execute methods on that object in the native style of the programming language, rather than using the SWbemServices.ExecMethod or SWbemObject.ExecMethod_ calls. In other words, the API allows you to treat CIM methods and properties as if they were Automation methods properties of SWbemObject.
  • Error Handling. If an error occurs as a result of a call to the CIM Object Manager through the WMI scripting API, the error information can be accessed using the native error mechanisms of the scripting language.
  • Optional Parameters. Many of the WMI scripting API parameters are optional and provide default values, allowing you to omit them when appropriate to streamline development.

WMI Scripting Model Objects

The next sections describe the scripting model objects. The SWbemLocator object is created using conventional methods for creating coclasses; other objects can be created using Moniker display names.

SWbemLocator object

This object represents a WMI locator. You can create this object directly as a coclass. It supports one method, ConnectServer, which you use to obtain a SWbemServices object. It has no properties.

SWbemSink object

This object represents a sink for WMI events; it is used for asynchronous API calls. You can create this object directly as a coclass. It supports the Cancel method, which cancels all outstanding asynchronous calls bound to this object instance.

The sink supports the following events:

  • OnObjectReady. This is called when a CIM Object is returned from an asynchronous call.
  • OnCompleted. This is called when an asynchronous call completes.
  • OnProgress. This is called to report the progress of an asynchronous call.
  • OnPut. This is called when a CIM Object is saved following an asynchronous Put call.

SWbemServices object

This object represents an authenticated connection to a namespace. It has a single Automation property called Security_, of type SWbemSecurity, which returns the SWbemSecurity object for this SWbemServices object. It has read/write access.

The Service object supports the following Automation methods, in both synchronous and asynchronous form:

  • Get. Retrieves a CIM Class or Instance.
  • Delete. Deletes a CIM Class or Instance.
  • SubclassesOf. Enumerates subclasses of a CIM Class.
  • InstancesOf. Enumerates instances of a CIM Class.
  • ExecQuery. Executes a WQL query.
  • ExecNotificationQuery. Executes a WQL notification query, and returns an SWbemEventSource.
  • ExecMethod. Executes a method on a CIM instance or class.
  • AssociatorsOf. Retrieves associators of a CIM instance or class.
  • ReferencesTo. Retrieves references to a CIM instance or class.

SWbemEventSource object

This object represents a source of events obtained from WMI; it is returned by the ExecNotificationQuery method of the SWbemServices object. It supports the Security_ Automation property, which returns the SWbemSecurity object for this SWbemEvent Source object.

It supports the NextEvent method, which is used to Get the next event from the source (or timeout).

SWbemObject Path object

This is a helper object that can be used to construct WMI object paths (without the user being required to know the details of the Object Path syntax).

This object supports the following Automation properties:

  • Path (DEFAULT). Represents the full WMI path. Type is BSTR, and access is read/write.

    Note Throughout this article, the term DEFAULT is applied to a property or method to indicate it is the Dispatch Default property/method on an Automation object. This means the property name can be omitted.

  • RelPath. The relative (to namespace) path. Type is BSTR, and access is read/write.

  • Server. The server name. Type is BSTR, and access is read/write.

  • Namespace. The namespace path. Type is BSTR, and access is read/write.

  • ParentNamespace. The parent namespace. Type is BSTR, and access is read-only.

  • DisplayName. The moniker-style display name. Type is BSTR, and access is read/write.

  • Class. The name of the class. Type is BSTR, and access is read/write.

  • IsClass. Indicates whether the path addresses a class. Type is Boolean, and access is read-only.

  • IsSingleton. Indicates whether the path addresses a singleton instance. Type is Boolean, and access is read-only.

  • Key. The set of key value bindings for this path. Type is SWbemNamedValueSet, and access is read-only.

The SWbemObject Path Object supports the following methods:

  • SetAsClass. Coerces the path to address a class.
  • SetAsSingleton. Coerces the path to address a singleton instance.

SWbemNamedValue object

This object is used to model a named value, which is a combination of a name and a VARIANT value. Named values are collected in a SWbemNamedValueSet collection object.

The SWbemNamedValue object supports the following Automation properties:

  • Name. The name of the value. Type is BSTR, and access is read-only.
  • Value. The value. Type is VARIANT, and access is read/write.

SWbemNamedValueSet collection

This is a collection object composed of SWbemNamedValue objects. It is used to model a collection of named values that may be passed as additional information to a method of the SWbemServices, SwbemObject, or SWbemLocator objects.

SWbemNamedValueSet supports the collection properties Count and _NewEnum. It also supports the standard collection methods, Add, Item, and Remove. The Item implementation allows the use of the value name as the indexing mechanism for the collection.

SWbemNamedValueSet also supports the DeleteAll method, which removes all named values from the collection.

SWbemObject

This object is used to represent a single CIM instance or class.

CIM properties (those which would appear in a MOF, but not WMI system properties) and methods are exposed in one of two ways:

  • Directly via the "dot" notation as Automation methods and properties of this interface. This is extremely convenient for scripts written to manipulate specific CIM objects.
  • Indirectly via the property and method collections available from this object. This is required for schema browser type scripts which deal with objects generically.

The SWbemObject supports the following Automation properties:

  • Derivation_. An array of class names (possibly empty) describing the derivation hierarchy. The first, lowest-index, member of the array is the __SUPERCLASS, and the last is the __DYNASTY. Type is SAFEARRAY of VARIANT, and access is read-only.
  • Path_. Contains location and naming information for the CIM Object. Type is SWbemObjectPath object, and access is read-only (with the single exception that the Class property of the object path is read/write).
  • Qualifiers_. Represents a collection of object-level qualifiers. Type is SWbemQualifierSet, and access is read-only.
  • Properties_. Represents a collection of object properties. Type is SWbemPropertySet, and access is read-only.
  • Methods_. Represents a collection of object methods. Type is SWbemMethodSet, and access is read-only.
  • Security_. Returns the Security object for this object. Type is SWbemSecurity.

Note that system properties are exposed in the scripting API as Automation properties of the CIM object, rather than true CIM properties. In addition, the __PROPERTY_COUNT system property is exposed as the standard collection Count property of the SWbemPropertySet Collection object.

The SWbemObject supports the following methods (those methods marked with an asterisk have additional asynchronous equivalents):

  • Clone_. Creates a copy of this object.
  • GetObjectText_. Retrieves MOF representation of this object.
  • SpawnDerivedClass_. Creates a subclass object.
  • SpawnInstance_. Creates an instance object.
  • CompareTo_. Compares with another object.
  • Put_*. Submits the object to CIM Object Manager.
  • Delete_*. Deletes the object from CIM Object Manager.
  • ExecMethod_*. Executes a method on the object.
  • Instances_*. Enumerates instances of the object (object must be a class).
  • Subclasses_*. Enumerates subclasses of the object (object must be a class).
  • Associators_*. Enumerates associators of the object.
  • References_*. Enumerates references to the object.

SWbemObjectSet collection

This is a collection object that is composed of SWbemObjects. It is used to model the result set associated with an enumeration or query.

SWbemObjectSet supports the collection properties _NewEnum and Count. It also supports the collection method Item, where the index supplied is the relative path of the object.

SWbemObjectSet supports the Security_ property, which returns the SWbemSecurity object for the collection.

SWbemObjectSet does not support the optional collection methods Add and Remove. This object also supports the WMI Clone method.

SWbemLastError object

This object (which is an SWbemObject) must be created directly and may be used to return the last WMI extended error object (if any) generated on the current thread. The object has read-once semantics (meaning it is cleared after reading).

The SWbemLastError object is used to provide similar functionality to the GetLastError call in the Win32 API.

SWbemQualifier object

This object represents a qualifier. It has the following Automation properties:

  • Name. Represents the Qualifier name. Type is BSTR, and access is read-only.
  • Value (DEFAULT). The Qualifier value. Type is Variant, and access is read/write.
  • IsLocal. Specifies whether the qualifier is local to the owning object, or has been propagated. Type is BOOL, and access is read-only.
  • PropagatesToSubclass. Controls the propagation behavior to subclasses. Type is BOOL, and access is read/write.
  • PropagatesToInstance. Controls the propagation behavior to instances. Type is BOOL, and access is read/write.
  • IsOverridable. Determines whether the Qualifier may be overridden when propagated. Type is BOOL, and access is read/write.
  • Origin. Represents the originating class name. Type is BSTR, and access is read-only.

SWbemQualifierSet collection

This is a collection object that is composed of SWbemQualifier Objects. It represents the set of qualifiers attached to a CIM element (class, instance, property, method, or method parameter).

SWbemQualifierSet supports the standard collection methods (Add, Item, and Remove), and the standard collection properties (Count and _NewEnum). The Item implementation allows the use of the qualifier name as the indexing mechanism for the collection.

SWbemProperty object

This object represents a property. It has the following Automation properties:

  • Name. Represents the property name. Type is BSTR, and access is read-only.
  • Value (DEFAULT). The property value. Type is VARIANT, and access is read/write.
  • IsLocal. Specifies whether the property is local to the owning object, or has been propagated. Type is BOOL, and access is read-only.
  • Origin. The name of the originating class. Type is BSTR, and access is read-only
  • Qualifiers_. Represents property qualifiers. Type is Collection, and access is read-only.
  • CIMtype. CIM type of property (not including the "array"-ness). Type is WbemCimtypeEnum, and access is read-only.
  • IsArray. Determines whether the property is an array type. Type is BOOL, and access is read-only.

The Qualifiers_ collection is a SWbemQualifierSet Collection object (the trailing underscore has been retained for consistency with the SWbemObject naming of the analogous Automation property).

SWbemPropertySet Collection

This is a collection object composed of SWbemProperty Objects. It represents the set of properties attached to a CIM element (class or instance).

The SWbemPropertySet object supports the standard collection methods (Add, Item, and Remove), and the standard collection properties (Count and _NewEnum). The Item implementation allows the use of the property name as the indexing mechanism for the collection.

SWbemMethod object

This object represents a method. It has the following Automation properties:

  • Name. Represents to the method name. Type is BSTR, and access is read-only.
  • Origin. The name of the originating class. Type is BSTR, and access is read-only.
  • Qualifiers_. Represents method qualifiers. Type is SWbemQualifier, and access is read-only.
  • InParameters. The In parameters definition. Type is SWbemObject, and access is read-only.
  • OutParameters. The Out parameters definition. Type is SWbemObject, and access is read-only.

SWbemMethod collection

This is a collection object that is composed of SWbemMethod Objects. It represents the set of methods attached to a CIM element (class or instance).

SWbemMethodSet supports the standard collection method Item. The Item implementation allows the use of the method name as the indexing mechanism for the collection. The Add and Remove methods are not supported, as this is essentially a read-only collection.

The standard collection properties _NewEnum and Count are also supported.

SWbemSecurity object

This object represents the DCOM security attributes on an object; it is exposed as a property on any object in the API that supports remote access to Windows Management services. The following object types support remote access:

  • CIM Object (SWbemObject)
  • CIM Object Collection (SWbemObjectSet)
  • Services (SWbemServices)
  • Event Source (SWbemEventSource)

All of the objects just listed surface the SWbemSecurity object as a property called Security_.

The Security object supports the following Automation properties with read/write access:

  • ImpersonationLevel
  • AuthenticationLevel

In each case, the value of the property is an enumeration type, whose members correspond precisely to the values supported by the standard DCOM security method IClientSecurity::SetBlanket.

Detailed information on the WMI scripting interface can be found on the WMI Start Page.

The next section highlights examples of WMI scripts usage. Developers should refer to the WMI Scripting SDK for implementation details.

WMI Scripts Usage

The WMI scripting API can be used for the following purposes:

  • Enumeration. For example, you can write scripts to enumerate all processes running on a local system.
  • Method execution. For example, you can create scripts to shutdown a specific process on a remote computer (for example, Notepad.exe).
  • Queries. For example, you can create scripts to determine which processes or devices are running on a local or remote system.
  • Event registration and reception. For example, you can create scripts to monitor for events from the Windows NT Event Log on a local computer.
  • Instance modification. For example, you could create a script to change the name of a disk.
  • Local and remote access. For example, you can create scripts to access an SNMP device on a remote computer, access a local or remote system and determine the services running on them, and so on.
  • Working with disparate sources of information. For example, the same script shell is used for various Win32, SNMP, PerfCount, and application objects.

Examples

This section highlights some VBScript ** examples of WMI scripting API usage.

List all processes running on the local system

The following code segment illustrates the use of enumeration, direct access to a CIM property (in this case the Name property of an instance of the CIM class Win32_Service) as if it were an Automation property, and local access.

for each Process in 
GetObject("winmgmts:{impersonationLevel=impersonate}").InstancesOf 
("Win32_process")
   WScript.Echo Process.Name
Next

List all services running on the system on host Products1

The following code segment illustrates the use of enumeration, direct CIM property access, and remote access to Windows NT system.

for each Service in 
GetObject("winmgmts:{impersonationLevel=impersonate}!//products1").InstancesOf 
("Win32_service")
   WScript.Echo Service.DisplayName
Next

Display the routing table's contents on an SNMP device

The following code segment illustrates the use of enumeration, direct CIM property access, and remote access to an SNMP device.

for each RoutingEntry in GetObject("winmgmts://./snmp/routerA").InstancesOf 
(" SNMP_RFC1213_MIB_ipRouteTable")
   WScript.Echo RoutingEntry.ipRouteDest, RoutingEntry.ipRouteNextHop, 
RoutingEntry.ipRouteType
   Next

Display information about a remote computer system Products1

The following code segment illustrates the use of Get specified object on a remote machine, and direct CIM property access.

Set System = 
GetObject("winmgmts:{impersonationLevel=impersonate}
   !//products1/root/cimv2:Win32_ComputerSystem= ""PRODUCTS1""")
WScript.Echo System.Caption
WScript.Echo System.PrimaryOwnerName
WScript.Echo System.Domain
WScript.Echo System.SystemType

Listen for Windows NT event log events on the local system

The following code segment illustrates the use of registration of a temporary event consumer on a specified event filter, and direct CIMproperty access.

Set EventSource = 
GetObject("winmgmts:{impersonationLevel=impersonate}").ExecNotificationQuery 
("select * from __InstanceCreationEvent  where TargetInstance isa 
'Win32_NTLogEvent'")

While true
   Set NTEvent = EventSource.NextEvent
   WScript.Echo NTEvent.TargetInstance.Message
Wend

Enable an interface on an SNMP device

The following code segment illustrates the use of Get specified remote SNMP device (object), Get specified instance (index 10 in interface table), and Set specified property (ifAdminStatus) to specified value (up).

Set Interface = GetObject(
"winmgmts://./snmp/routerA:SNMP_RFC1213_MIB_ifTable.ifIndex=10")
Interface.ifAdminStatus = "up"
Interface.Put_ ()

Terminate all copies of the Notepad process on host Rogue

The following code segment illustrates the use of Query, and direct CIM method execution (as if it were an Automation method).

for each Process in 
GetObject("winmgmts:{impersonationLevel=impersonate}!//rogue").ExecQuery 
("select * from Win32_Process where Name='notepad.exe'")
   Process.Shutdown (0)
       Next

Enable DHCP on the local system

The following code segment illustrates the use of Get specified object, direct CIM property access, and update of class changes to Windows Management.

Set NetworkAdapter = 
GetObject("winmgmts:{impersonationLevel=impersonate}
   !Win32_NetworkAdapterConfiguration=1")
NetworkAdapter.DHCPEnabled = true
       NetworkAdapter.Put__ ()

Restart all services that are dependent on the NetDDE service on host Products1

The following code segment illustrates the use of enumeration, association traversal, and method invocation.

For Each Service in 
GetObject("winmgmts:{impersonationLevel=impersonate}!//products1").ExecQuery 
("Associators of { Win32_service.Name = ""NetDDE"" } Where 
AssocClass = Win32_DependentService Role = Dependent" )

If Service.State = Stopped Then
      Service.Start () 
   End IF
Next

Change the name of a disk

The following code segment illustrates the use of instance modification:

set disk = GetObject 
("winmgmts:{impersonationLevel=impersonate}!Win32_LogicalDisk=""C:""")
disk.VolumeName = "My C Drive"
disk.Put_

Use of the asynchronous API and scripting in Web pages

The following two examples illustrate the use of the asynchronous API and scripting in a Web page.

Synchronous example:

<HTML>
<HEAD>
<TITLE>WBEM VBScript Example</TITLE>
<SCRIPT LANGUAGE="VBScript"> 
   
   Sub window_onload
   const impersonation = 3
   Set Locator = CreateObject("WbemScripting.SWbemLocator")
   Set Service = Locator.ConnectServer()
   Service.Security_.ImpersonationLevel=impersonation
   Set Process = Service.Get("Win32_Service.Name=""Winmgmt""")
   document.all.info.innerText = Process.DisplayName
   end sub

</SCRIPT>
</HEAD>
<BODY>
The name of the service is 
<SPAN ID="info">
unknown
</SPAN>.
</BODY>
</HTML>

Asynchronous example:

<HTML>
<HEAD>
<TITLE>WBEM VBScript Example</TITLE>

<SCRIPT FOR="mysink" EVENT="OnCompleted(hResult, ErrorObject, Context)" 
LANGUAGE="VBScript">
   alert("Completed")
</SCRIPT>

<SCRIPT FOR="mysink" EVENT="OnObjectReady(Winmgmt, Context)" 
LANGUAGE="VBScript">
   document.all.info.innerText = Winmgmt.DisplayName
</SCRIPT>

<SCRIPT LANGUAGE="VBScript"> 
<!--
   
   Sub Document_OnClick 
      const impersonate = 3
      Set Service = Locator.ConnectServer()
      Service.Security_.ImpersonationLevel = impersonate
      Service.GetAsync mysink,"Win32_Service.Name=""Winmgmt"""
   end sub
-->
</SCRIPT>
</HEAD>
<BODY>
The name of the service is 
<SPAN ID="info">
unknown
</SPAN>.
<OBJECT ID="Locator" CLASSID="CLSID:76A64158-CB41-11D1-8B02-
00600806D9B6"></OBJECT>
<OBJECT ID="mysink" CLASSID="CLSID:75718C9A-F029-11d1-A1AC-
00C04FB6C223"></OBJECT>
</BODY>
</HTML>

Conclusion

Based on industry standards and using a data-centric approach, WMI provides a single point of access for manipulating disparate management information in a managed environment. WMI uses existing technologies and provides tools, samples, and an extensible Provider architecture that developers can use as a basis for building vendor-specific management solutions for network, systems, devices, and so on.

With the WMI scripting interface, you can create scripts for management tasks related to networks, systems, servers and workstations, security and users, system health monitoring, and printers.

For More Information

For the latest information on Windows NT Server, check out the Microsoft Windows NT Server Web site at https://www.microsoft.com/ntserver/ or the Windows NT Server Forum on the Microsoft Network (GO WORD: MSNTS).

The information contained in this article represents the current view of Microsoft Corporation on the issues discussed as of the date of publication. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information presented after the date of publication.

This article is for informational purposes only. MICROSOFT MAKES NO WARRANTIES, EXPRESS OR IMPLIED, IN THIS DOCUMENT.

Microsoft, ActiveX, the BackOffice logo, JScript, Visual Basic, Win32, Windows, and Windows NT are registered trademarks of Microsoft Corporation.

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