WMI script entry

xiaoxiao2021-03-06  67

WMI script entry: first part

Release Date: 09/03/2004

| Update Date: 09/03/2004

Greg Stemp, Dean Tsaltas and Bob Wellsmicrosoft Corporation

Ethan Wilansky Network Design Group

Summary: The first Scripting Guys of Scripting Guys demonstrates how to create a large number of useful Windows system management scripts using the WMI script library.

This page

What is WMI? Quick start to WMI script WMI architecture hosting resource WMI infrastructure browsing CIM is here

Microsoft® Windows® Management Instrumentation (WMI) is probably the best secrets we knows Microsoft saved. Despite this, there is no doubt that WMI is Microsoft's main management support technology for Windows. What does this mean for you? So, if you manage Windows Server and Workstations, or if you create a Windows management application, you need to know WMI. This article is a professor you WMI, more precisely, teach you how to use the WMI script library to create a large number of Windows system management scripts in the series of articles in the series of articles.

Before starting, we should use the Andrew Clinick, which makes us have the opportunity to inherit Scripting Clinic. It can be said that when Andrew said in its recent column, he is not a joke when he plans more content! In fact, Andrew is moving to another, so he politely invited us to continue from him. In addition to the beginning of the start, we are very reluctant because Andrews Scripting Clinic is very reluctant, we are very happy to take over.

So, who are we? We are Scripting Guys, which is a group written by the System Administration Scripting Guide, which is part of the Microsoft® Windows Server 2003 resource toolbox. In the big head in the column, the left is DEAN, and the right side is Greg. There are rumors that Ethan and Bob have missed the photo due to wrinkles every week of botulinum. So, if you see their photos on the Internet, they found that they look very handsome. We have to tell you here, Ethan and Bob are really the most stupid guys we have seen! Remember to pay attention.

What is WMI?

WMI was initially issued as an additional component as an additional component in 1998, which is built in the core management support technology in Windows 2000, Windows XP, and Windows Server 2003 Series operating systems. Based on the industry standard supervised by Distributed Management Task Force (DMTF), WMI is a normative and infrastructure that can be accessed, configured, managed, and monitors all - almost all Windows resources.

To master the powerful features and scope of WMI, consider how to manage and monitor Windows workstations and servers before (or now). You may use many graphical management tools to manage Windows resources - such as disks, event logs, files, folders, file systems, network components, operating system settings, performance data, printers, processes, registry settings. , Security, service, sharing, user, group, etc.

Although the graphical tool provides a functional management solution, what is the things share? A answer is that before WMI, all Windows graphics management tools rely on the Win32 application programming interface (Application Programming Interface, APIS) to access and manage Windows resources. why? Because the only way to access Windows resources in programming methods is to pass the Win32 API. This situation allows Windows system administrators to automate commonly used system management tasks through a simple way to use common scripting languages ​​because most scripting languages ​​cannot call Win32 API directly. By providing consistent models and frameworks, WMI changes this - through models and frameworks, all Windows resources are described and disclosed to the outside world. The best point is that system administrators can use the WMI script library to create system management scripts, and manage any Windows resources exposed through WMI! Using Windows Script Host and Microsoft Visual Basic Scripting Edition (VBScript), or any scripting language that supports COM (for example, ActiveState Corporation ActivePerl), you can write scripts to manage and automate the following aspects of enterprise systems, applications, and networks:

• Windows Server 2003, Windows XP Professional and Windows 2000 System Management. You can write scripts to retrieve performance data, manage event logs, file systems, printers, processes, registry settings, schedulers, security, services, sharing, and many other operating system components and configuration settings. • Network management. You can create a WMI-based script to manage network services, such as DNS, DHCP, and devices that enable SNMP. • Sound monitoring in real time. Using WMI event subscriptions, you can write code to monitor and respond to event log items, monitor and respond to event log entries, monitor and respond to file systems, registry modifications, and other real-time operating system changes. Basically, WMI event subscriptions and notifications are what SNMP traps are in the SNMP environment. • Windows .NET Enterprise Server Management. You can write scripts to manage Microsoft Application Center, Operations Manager, Systems Management Server, Internet Information Server, Exchange Server, and SQL Server.

Back to top

Quickly start to WMI scripts

In order for you to have some concepts for WMI scripts, let's take a look at a surface that is not very important task - retrieves the total amount of physical memory installed in Windows-based remote computers. Before WMI, if there is no additional third-party tool, it cannot be easily completed by a script. In fact, before WMI, use tools including operating system tools to determine the only way to install the number of memory in your computer is through the System Properties dialog box. Today, if WMI is installed on the target computer, and there is a computer administrator access, you can use a WMI script to retrieve physical memory installed on a remote Windows computer, as simple as shown in Listing 1.

Listing 1: Search total physical memory using WMI and VBScript

STRComputer = "ATL-DC-01"

Set WbemServices = getObject ("WinMgmts: //" & strComputer)

SET WBEMOBJECTSET = WBEMSERVICES.INSTANCESOF ("Win32_LogicalMemoryConfiguration" for Each WbemObject in WbemObjectset

WScript.echo "Total Physical Memory (KB):" & WbemObject.totalphysicalMemory

NEXT

To run the sample scripts in Listing 1, copy them and paste them into your most common text editor (NotePad.exe), change the value assigned to the StrComputer variable to a valid enable WMI computer in the domain, Save the script (extension is .vbs) and run the script as shown in Figure 1.

Figure 1: GetMemory.vbs output

It is a bit incredible, there is no need to enter, you should see the physical memory volume of the target computer is displayed.

Now, in you say "God! Really use six lines of scripts to search for the amount of memory in a computer?" Before, let us first politely plug in a few words, because it is still not obvious, you can use it. The same basic steps shown in Listing 1 are retrieved from any Windows resource through WMI.

Suppose you want to retrieve the name, status, and start type of all services installed on a remote computer. The example script in Listing 2 is completely used in the same basic steps used in Listing 1.

Listing 2: Search service information using WMI and VBScript

STRComputer = "ATL-DC-01"

Set WbemServices = getObject ("WinMgmts: //" & strComputer)

SET WBEMOBJECTSET = WBEMSERVICES.INSTANCESOF ("Win32_Service")

For Each WBemObject in WbemObjectset

WScript.echo "Display Name:" & WbemObject.displayName & VBCRLF & _

"State:" & WbemObject.State & Vbcrlf & _

"START MODE:" & wbemObject.Startmode

NEXT

Run list 2 Generates the output as shown in Figure 2.

Figure 2: GetServices.vbs output

Suppose you are not interested in the service, but you need to retrieve records from the Windows event log. Use the script template in Listing 1 again, you can easily read the Windows event log, such as the presentation shown in Listing 3. We have to point out before you run a list 3, if your event log contains thousands of records, the sample script may take a long time to run.

Listing 3: Read Windows Event Log Record

STRComputer = "ATL-DC-01"

Set WbemServices = getObject ("WinMgmts: //" & strComputer)

Set wbemObjectset = WbemServices.instancesof ("Win32_NTLOGEVENT")

For Each WBemObject in WbemObjectset

WScript.echo "log file:" & wbemobject.logfile & vbcrlf & _ "Record Number:" & WbemObject.RecordNumber & Vbcrlf & _

"TYPE:" & WBEMOBJECT.TYPE & VBCRLF & _

"Time generated:" & wbemObject.timegenerated & vbcrlf & _

"Source:" & WbemObject.Sourcename & Vbcrlf & _

Category: "& WbemObject.category & vbcrlf & _

Category String: "& WbemObject.categoryString & Vbcrlf & _

"Event:" & WbemObject.Eventcode & VBCRLF & _

User: "& WbemObject.user & vbcrlf & _

"Computer:" & wbemObject.computername & VBCRLF & _

Message: "& wbemObject.Message & vbcrlf

NEXT

If we carefully check the list 1, 2 and 3, we will draw two very important observations about these three scripts. The first observation result is that all three scripts perform the same three steps: scripts connected to WMI, retrieve a WMI managed resource, and returns several properties of resources. The second important observation result is that in each script, the only change is identifying the class name of the target resource (ie, Win32_LogicalMemoryConfiguration, Win32_Service, and Win32_NTLOGEVENT), and the corresponding properties of the resource.

Three steps used in the script are common for any WMI script used to retrieve WMI hosting resource information. Let's take a slightly more detailed look at each step.

Step 1: Connect to the WMI service

In any WMI script, the first step is a connection to the Windows management service on the target computer. Connect to WMI on a local or remote computer and call VBScript's getObject function and the name of the name object of the WMI script (ie "WinMgmts:", the name of the target computer is as simple as the GetObject.

Connect to WMI in this way, returns a reference to the SwbemServices object, and we use the variables called WBEMServices in Listing 1, 2, 3 to reference the object. SwbemServices is one of the left and right objects defined in the WMI script library. The WMI script library provides a set of universal object scripts for accessing the WMI infrastructure. Once there is a reference to the SwbemServices object, you can call any way to provide SWBEMServices; InstanceSof is one of this method.

Step 2: Retrieve the instance of WMI hosting resources, the second step is mainly dependent on the task to be executed. In the information of the WMI hosted resource, step 2 is as simple as the instancesof method that calls the SwbemServices object. As the method name is indicated, instancesof returns all instances of managed resources identified by the resource class name. Instancesof returns the required resources in the form of a SwbemObjectset collection, and we reference it in Listing 1, 2, 3 by using variables named WBemObjectSet. SWBemObjectSet is another script object defined in the WMI script library.

Step 3: Display the properties of the WMI managed resource

The last step is to enumerate the contents of the SwbemObjectSet collection. Each of the SWBemObjectSet is a SwbemObject (another object in the WMI script library) - a single instance indicating the desired resource. Use SwbemObject to access the methods and properties defined in the managed resource class definition.

Then, what is the same, Win32_LogicalMemoryConfiguration, win32_service, and Win32_NTLOGEVENT classes? In addition, where are they from? Which other classes are available? Also, how to use them? The answers to these problems are dispersed in each component constituting the WMI architecture. Let's take a look.

Back to top

WMI architecture

The WMI architecture consists of three main layers, as shown in Figure 3:

• Managed resources • WMI infrastructure • Users

Figure 3: WMI architecture

We will start from the lowest layer, because the resources are residing there.

Back to top

Hosted resources

The hosted resource is an arbitrary logic or physical component, which is publicly and managed by using WMI. You can use WMI-managed Windows resources including: computer system, disk, peripherals, event logs, files, folders, file systems, network components, operating system subsystems, performance counters, printers, processes, registry settings, security, Services, sharing, SAM users, groups, Active Directory, Windows Setup, Windows Driver Mode (WDM) Device Drivers, and SNMP Management Information Basis (MIB) data, etc. WMI hosted resources communicate with WMI via a provider. When you start writing a script to interact with the WMI hosted resource, you often see a term example, which is used to reference the virtual representation of the managed resource in the running script.

Back to top

WMI infrastructure

The intermediate layer is a WMI infrastructure. WMI consists of three main components: a common information model object manager (CIMM), a common information model (CIM) repository, and provider. These three WMI components jointly provide an infrastructure that is defined, disclosed, access, and retrieves configuration and management data. Although small, the fourth component that is absolutely indispensable to write scripts is the WMI script library.

WMI provider

The WMI provider plays an intermediate role between WMI and managed resources. The provider represents the user application and script request information from the WMI managed resource, and sends instructions to WMI managed resources. For example, Listing 1 and Listing 2 use a built-in WIN32 provider to retrieve memory and service related information. Listing 3 Use the built-in event log provider to retrieve records from the Windows event log.

By publicizing the hosted resource to the WMI infrastructure based on WMI standard, a uniform access model, providing a program hidden hosted resource unique implementation details. The WMI provider uses the host API to communicate with the WMI programming interface using the WMI programming interface. For example, the built-in event log provider calls the Win32 event log API to access the event log. WMI-based scalable architecture, software developers can develop and integrate additional providers to disclose their product unique management functions. The Exchange Server 2000 provider for monitoring the Exchange Connector status is an example. Similarly, both Application Center, Operations Manager, Systems Management Server, Internet Information Server, and SQL Server include WMI providers.

The provider is usually implemented as a dynamic link library (DLL) in the% SystemRoot% / System32 / WBEM directory. WMI includes a lot of built-in providers for Windows 2000, Windows XP, and Windows Server 2003 Series operating systems. Built-in providers (also known as standard providers), provide data and management functions from known operating system sources such as Win32 subsystems, event logs, performance counters, registry, etc.). Table 1 lists a WMI provider included in Windows 2000, Windows XP, and Windows Server 2003 Series operating systems.

Table 1: Some standard WMI Provider List Provider DLL Namespace Description Active Directory Provider DSPROV.DLL ROOT / DIRECTORY / LDAP maps the Active Directory object to WMI. Event Log Provider NTEVT.DLL ROOT / CIMV2 Manage Windows Event Logs, for example, read, backup, cleaning, copying, deleting, monitoring, rename, compression, decompression, and changing event log settings. Performance Counter Provider Wbemperf.dll Root / CIMV2 provides access to raw performance data. Registry Provider STDPROV.DLL ROOT / DEFAULT Read, Write, Enumeration, Monitor, Create, Delete Registry Item and Value. SNMP Provider SNMPincl.dll Root / SNMP provides access to SNMP MIB data and captures from SNMP managed devices. WDM Provider WMIPROV.DLL ROOT / WMI provides access to information in the WDM device driver. Win32 Provider CIMWIN32.DLL ROOT / CIMV2 provides information about computers, disks, peripherals, files, folders, file systems, network components, operating systems, printers, processes, security, services, sharing, SAM users, and groups, and more Multi-resource information. Windows Installer Provider MSIPROV.DLL ROOT / CIMv2 provides access to installed software information.

Windows XP and Windows Server 2003 contain a lot of additional standard providers. For a complete list of standard providers, see the WMI Provider Reference in the WMI Software Developers Kit (SDK) document.

CIMOM

CIMOM (read as a SEE-MOM) handles interactions between users and providers. This term is from the web-based enterprise management software and the public information model specification maintained by Distributed Management Task Force.

You can imagine the CIMOM as a WMI information agent. All WMI requests and data have passed CiMom. Windows Management Instrumentation Services (WINMGMT.exe) provides a CIMOM role on Windows XP and Windows Server Series operating systems, running under the control of the General Service Host Process (SVCHOST.exe). Note On the computer running Windows 2000 or Windows NT 4.0 Service Pack 4, WMI service is run as a separate service process. On the computer running Windows Millennium Edition (ME), Windows 98, or Windows 95 OSR 2.5, WMI is run as a standard executable process.

In addition to providing public interfaces (users from accessing WMI), CIMOM also provides the following core services to the WMI infrastructure:

• Provide registration. WMI provides registration position and function information using CiMom. This information is stored in the CIM repository. • Request to be transmitted. CIMOM uses the provider registration information to transfer the user request to the appropriate provider. • remote access. Users access remote systems that enable WMI through CIMOM access to the remote system. Once the connection is established, the user can perform the same operation as the operation that can be performed locally. • safety. On the local computer or on a remote computer, the user is allowed by verifying access tags of each user before connecting to WMI, and CIMOM controls access to WMI managed resources. WMI does not override or blocks the security provided by the operating system. • Query processing. Allow users to use WMI query language (WMI Query Language, WQL) to issue queries about any WMI managed resource. For example, you can query all event logs that occurred in an event that occurred in the past 24 hours. CiMOM executes the query calculation only if the provider itself does not support query operations. • Event processing. Allow users to subscribe to events that represent changes to the WMI managed resource. For example, you can subscribe to an event indicating when the space on the logical disk drive drops below an acceptable threshold. CICOM is polled in a specified interval, and an event notification is generated when the subscription condition is met.

Managing applications, management tools, and scripts to transfer CiMom to minimize data, subscribe to events, or perform some other related tasks. CIMOM obtains the required provider and class information to meet the user's request from the CIM. CIMOM uses information obtained from the CIM to pass the user's request to the appropriate provider.

CIM repository

The basic idea of ​​WMI is - can be unified in one architecture to represent configuration and management information from different sources. CIM is this architecture, also calls the model managed environment and defines the object repository or class storage of each data block published by WMI. This architecture is based on the DMTF public information model standard.

It is very similar to the architecture of Active Directory based on classes, and CIM consists of classes. Class is a blueprint for a WMI hosted resource. However, different from the Active Directory class represents an object created and stored in the directory, and the CIM class usually represents dynamic resources. That is, the example of the resource is not stored in the CIM, but is dynamically retrieved by the provider based on the user request. It is very simple, and most WMI managed resources have changed very frequently, so you must read it on demand to ensure that the retrieval is the latest information.

In the context of CIM, the term repository is somewhat misunderstood. Although the CIM is a repository, it is possible to store static data, but its main role is a blueprint for storing the hosted resource.

Similar to the Active Directory class is that the CIM class is a hierarchical organization, and the subclass of each level is inherited from the parent class. DMTF maintains a set of cores and public base classes, systems, and applications software developers (such as Microsoft) from these class derived and created system (or application) specific extensions. The class is packet into the namespace, and the namespace is a class logical group representing a specific management area. For example, namespace Root / CIMv2 includes most of the classes that are typically associated with the computers and operating systems. The class (Win32_LogicalMemoryConfiguration, Win32_LogicalMemoryConfiguration, Win32_LogicalMemoryConfiguration, Win32_LogicalMemoryConfiguration, Win32_Service, and Win32_NTLOGEVENT) resides in Namespace Root / Cimv2, which is just three of hundreds of classes defined in the CIM.

The CIM class consists of attributes and methods. The property describes the configuration and state of the WMI hosted resource, and the method is the executable function of the operation on the WMI managed resource.

Note Do not confuse the methods and properties defined by the CIM with the method and properties provided by the automation objects in the WMI script library.

From the physics school, CIM resides in% systemroot% / system32 / wbem / repository / fs / directory, consisting of the following four files:

• INDEX.BTR. Two-Binary index file. • INDEX.MAP. Transaction control file. • Objects.data. Store the CIM repository defined by the hosted resource. • Objects.map. Transaction control file.

Note In Microsoft Windows 2000 and Windows NT 4.0 Service Pack 4, CIM is stored in% SystemRoot% / System32 / WBEM / Respository / Cim.rep. In Windows Millennium Edition (ME), Windows 98, and Windows 95 OSR 2.5 operating systems, CIM is stored in% Windir% / System / WBEM / Respository / Cim.rep.

Although CIM is based on object-oriented design principles, you don't have to be an expert in information modeling or architecture design, you can effectively use WMI and write WMI-based scripts. It is important to understand the infrastructure and organization of CIM and learn how to browse and explain its content.

WMI script library

The WMI script library provides automated object sets, scripting languages ​​(such as VBScript, JScript, and ActivePerl ActivePerl) use it accesses the WMI infrastructure.

The automation object in the WMI script library provides a consistent and unified script model for the WMI infrastructure. As shown in front, once you know how to use the WMI script library to search for a managed resource type, you can easily use the same steps to retrieve other WMI managed resources. For example, you can use any of the three scripts listed above and easily modify this script to retrieve the process (Win32_Processor) information, processor (Win32_Processor) information, operating system (Win32_Operatingsystem) on remote computers. Information, or any one of hundreds of hosted resources disclosed by WMI.

The WMI script library is implemented in a single DLL called Wbemdisp.dll, which is located in the% systemroot% / system32 / wbem directory. The WMI script library also includes a type library called WBEMDisp.tlb. You can use the WMI script type library to reference the WML constant from an XML-based Windows script file (extension. WSF).

WMI user

Users are top. Users are scripts, enterprise management applications, web-based applications, or other management tools, which access and control usable information through WMI infrastructure. Note Many management applications act as a dual role of WMI users and WMI providers. There are several Microsoft management products that belong to this situation, such as Application Center, Operations Manager, and Systems Management Server, and SYSTEMS Management Server.

Back to top

Browse CIM

We have discussed a considerable part of the content, but there is still a detail without talking, however, how to determine which resources are public through WMI. Fortunately, you can use a variety of different tools to browse the CIM architecture and check the class definition of the WMI managed resource.

• WMI control. WMI Control (WMIMGMT.MSC) is a Microsoft Management Console (MMC) snap-in, which allows you to configure WMI settings on your local or remote computer. Although you cannot use the WMI control to browse CIMs, you can use the "Security" tab of this tool to determine the CIM namespace available on the local or remote computer. For more information on using WMI controls, see Windows 2000 Help or Windows XP Help and WMI control over the support center. • WMI tester. WMI Tester (WBEMTEST.exe) is a common, graphical tool for interacting with WMI infrastructure. You can use the WMI tester to browse the CIM architecture and check the managed resource class definition. The WMI tester can also be used to perform the same operations as WMI-based scripts, such as instances and running queries that search hosted resources. The WMI tester is part of the default WMI installation on all WMI-enabled computers, so Wbemtest.exe is an excellent WMI learning and troubleshooting tool. For information on using the WMI tester, see the WMI Tester Overview in Windows XP Help and Support Center. • WMI command line. The WMI command line tool (WMIC.exe) that is released as part of Windows XP provides a command line interface to the WMI infrastructure. You can use WMIC.exe to execute common WMI tasks from the command line, including browsing CIM and check the CIM class definition. For information on using the WMI command line tool, see "Using WMI Command Line (WMIC) Tools" in Windows XP Help and Support Center • CIM Studio. As part of the WMI SDK, CIM Studio provides a web-based interface implementation with WMI infrastructure interaction. As with the WMI tester, you can use CIM Studio to view the CIM architecture, view the class definition and retrieve the instance of managed resources. The class relationship and association can be easily viewed by the CIM Studio's super user interface, and CIM Studio provides a basic search tool - they are both of the WMI tester tools. To use CIM Studio, you must download and install WMI SDK. You can download WMI SDK from Windows Management Instrumentation (WMI) SDK. • Enumclasses.vbs and enuminstances.vbs. The Windows 2000 Server Resource Toolbox includes a lot of scripts that use WMI powerful features. The three scripts listed here are common scripts that can be used to browse the CIM architecture, view the class definition, and retrieve an instance of managed resources.

Some additional resources you should view include:

• WMI SDK documentation. The WMI SDK contains a complete list of classes provided by the standard WMI provider. You can access the WMI SDK document in the MSDN online library. • TechNet Script Center. If you like, you can call it useless, but the TechNet Script Center contains hundreds of WMI-based sample scripts from the upcoming System Administration Scripting Guide. WMI Tester (WBEMTEST.EXE) drill

Now, you have some knowledge of tools that can be used to browse and see CIM, let us use the WIN32_PROCESS class definition and modify the list of processes from your local computer. Retrieve some properties.

1. Open a command prompt, type C: /> Wbemtest.exe, press Enter to start the WMI Tester Tool. Note that most of the buttons are disabled on the main WMI tester window, indicating that you are not connected to WMI. 2. Click Connect to connect to WMI services on your local or remote computer. The Connection dialog is displayed, which provides a text input area tagged as NameSpace, the default value of Root / Default. Change the value of the NAMESPACE area to root / cimv2, click the Connect button of the Connection dialog to return to the main WMI Tester window. 3. The namespace identifier in the upper left corner of the main window should be displayed as root / cimv2. Note that all buttons are now enabled, which indicates that you have successfully connected to WMI on your local host in the current credential environment. Click ENUM CLASSES to open the "Super Class Information" dialog. 4. In the "Ultra Class Information" dialog box, don't fill in the Enter Superclass Name area, click the Recursive option, click OK to enumerate all CIM classes defined in the root / cimv2 namespace. At this point, you may be viewing a Query Results dialog listing hundreds of classes defined. The number of classes depends primarily on the version of Windows you are running. For example, if you use Windows 2000, you should see approximately 600 class definitions. If you run Windows XP, you should see about 900 classes definitions. Note that the class listed in the top of the "Query Result" dialog is starting with two underscores. These are system classes. The system class is a predefined CIM class that supports internal WMI configuration and operation, such as providing program registration, namespace security, and event notifications. Now, ignore the system class and scroll down the Query Results dialog until you see the class starting with CIM_. The name starting with CIM_ is the core and public base class maintained by DMTF. Continue to scroll down until you reach the class starting with Win32_. The name starting with Win32_ is a Microsoft extension class that represents Windows-specific managed resources. If this is your first time to check the root / cimv2 namespace, you may want to be familiar with the full collection of classes in the root / cimv2 namespace, especially if there is a class of Win32_ prefix. 5. Scroll down the "Query Result" dialog until you reach the Win32_Process class, double-click the class name to open the object editor of the Win32_Process dialog. 6. The Object Editor dialog displays details (properties and methods) of the definitions and implementations of the selected classes. Recall the content we discussed before - class definition is a blueprint for WMI manageable resources. Select Hide System Properties check box to hide system properties. The remaining Win32_Process property indicates information you can retrieve from a process running on a local or remote computer. To complete your WMI script exercise, try to retrieve the Name, Handle, and ProcessID properties. Using one of the three lists as a template, try running the script before going to step 7. In the local computer, run the script, set the value of the StrComputer variable to "." (A single point in the quotation marks). 7. After running the newly created getProces.vbs script, you can verify the results of the script with the WiMi tester. In the object editor of the Win32_Process dialog box, click Instances. The resulting query result dialog lists an instance of a process running on a computer. Double-click an instance of a specified process to see the details of this instance. Back to top

Just here.

It is true that we just touched the surface layer written by the WMI script. Sincerely, this is intentional. WMI provides the possibility of such script preparation, so it is easy to cause "see the trees, no forests". But don't worry, as the content of this series, we will fill all the gaps. The important content to be refined is: WMI is a separate, most important management support technology in Windows. You do not need to be a developer or script to write authority to start writing WMI-based scripts. Continue to modify your newly created script to retrieve additional process properties, or further - retrieve other managed resources. Before we met next month, you may find that you have a toolbox full of customized system management scripts. Let us know how you do it. Listing 4: Answer for WMI tester drills

Strcomputer = "." 'Dot (.) Equals Local Computer In WMI

Set WbemServices = getObject ("WinMgmts: //" & strComputer)

SET WBEMOBJECTSET = WBEMSERVICES.INSTANCESOF ("Win32_Process")

For Each WBemObject in WbemObjectset

WScript.echo "Name:" & wbemObject.name & vbcrlf & _

"Handle:" & WbemObject.handle & vbcrlf & _

Process ID: & wbemObject.Processid

NEXT

Scripting clinic

Greg Stemp is one of the most recognized authorities in the United States, and is widely known as world-class ... haha! Well, how do you have a football coach in their resume? really? He was fired? Oh, very good! Greg Stemp works in ... Oh, come, don't I say this? Ok! Greg Stemp sells the salary from Microsoft, in Microsoft he has the title of the SYSTEM Administration Scripting Guide.

Bob Wells swayed around, and prepared to each of the people listening to him. There are rumors that Bob's two Daxie Rethers have more written to scripts than most human beings. Spatant time, Bob submitted to the System Administration Scripting Guide.

Ethan Wilansky spends many working hours in writing and consultation. He is enthusiastic on script writing, yoga, gardening and his family (not necessarily in this order). He is currently working on a method of creating scripts that can put down the garbage and washing disc.

WMI script entry: second part

Release Date: 09/06/2004

| Update Date: 09/06/2004

Greg Stemp, Dean Tsaltas, Bob Wells, Microsoft Corporation, My.Settings, My.user and My.Webservices

Ethan Wilansky Network Design Group

Summary: Scripting guys Continued their discussion to write WMI scripts, which focuses on the CIM repository and CIM classes to help you use all powerful features of WMI scripts.

If you want to build a house, you need to know how to read and explain the architectural chart. If you want to make an electronic appliance, you need to know how to read and explain the diagram. So if you want to write a WMI script, you guessed it, you need to know how to explain WMI's blueprint-CIM repository for management. The CIM repository, also known as the WMI repository in the WMI SDK, is a WMI architecture that stores a class definition of the modeling WMI hosted resource. In order to emphasize the importance of CIM and CIM classes, carefully consider entry in WMI scripts: 4 scripts displayed in the first part, and list 1 and Listing 2 below. Listing 1 is a slightly enhanced version from the first part of the service script, and Listing 2 is another variant of the same script using the Win32_OperatingSystem class.

Note If you have doubts about Listing 1 and 2, we recommend that you read (or re-read) the first part of this series.

Listing 1: Search service information using WMI and VBScript

Strcomputer = "." 'Dot (.) Equals Local Computer In WMI

Set objwmiservice = getObject ("WinMgmts: //" & struser)

Set colservices = objwmiservice.instancesof ("Win32_Service")

For Each ObjService in colservices

Wscript.echo "name:" & objService.name & vbcrlf & _

Display Name: "& objService.DisplayName & VBCRLF & _

"Description:" & objService.Description & Vbcrlf & _

"Path Name:" & objService.pathname & Vbcrlf & _

"START MODE:" & objService.Startmode & Vbcrlf & _

"State:" & objService.State & Vbcrlf

NEXT

Listing 2: Retrieve operating system information using WMI and VBScript

StrComputer = "."

Set objwmiservice = getObject ("WinMgmts: //" & struser)

Set coloperatingsystems = objWMiservice.instancesof ("Win32_OperatingSystem")

For Each Objoteingsystem in coloperatingsystems

WScript.echo "Name:" & objoodativesystem.name & vbcrlf & _

"CAPTION:" & objoteingsystem.caption & vbcrlf & _

"CurrentTimeZone:" & objoodativesystem.currenttimezone & vbcrf & _ "Lastbootuptime:" & objoteingsystem.lastbootuptime & vbcrlf & _

"LocalDatetime:" & objoteingsystem.localdatetime & vbcrlf & _

"Locale:" & objoodativesystem.locale & vbcrlf & _

"Manufacturer:" & ObjoperatingSystem.Manufacturer & Vbcrlf & _

"Ostype:" & ObjoperatingSystem. Ostype & Vbcrlf &_

"Version:" & objoteingsystem.version & vbcrlf & _

Service Pack: "& ObjoperatingSystem.ServicePackmajorversion & _

"." & objoodativesystem.servicePackminorversion & VBCRLF & _

"Windows Directory:" & objoteingsystem.windowsDirectory

NEXT

Each script in the first part of this series and in Listing 1 and 2, in Listing 1 and 2, the only feature is identifying the class name of the WMI hosting resource and the subset of each class attribute. The same script template can be used to retrieve all physical memory, service, event logging, processes, and operating system information, which proves important roles played in the CIM class in the WMI script. Once you know how to write a script to manage a class of WMI managed resources, you can use the same basic techniques for other managed resources.

Of course, knowing the class name of a hosted resource and the corresponding attributes of this class are only part of this article. Before you can use the WMI script, you need to know more about the structure of the CIM repository and the CIM class. why? We will give two important reasons.

1. Learn how to browse CIM will help you determine computer and software resources exposed via WMI. 2. Learn how to explain the blueprint (class definition) of the hosted resource (class definition) will help you understand the tasks that can be performed on the managed resource.

No matter what WMI tool is used, these two points are established, whether using the WMI script library, WMI command line tool (WMIC.exe), or enterprise management applications, you need to know how to browse CIM and explain the CIM class.

The reason why CIM is not so obvious but equally important is that CIM is an excellent document resource for WMI managed resources. That's right, if you need more information about the WMI class, you can use WMI SDK. However, if you don't need detailed information about the WMI class? Suppose you just want to know if you are running, whether you support a specified class, method, or attribute. So, look at the CIM of the target computer.

For example, we are often asked "Why can't the 'join the computer in the TECHNET's script to domain' scripts in Windows 2000?" Answer Yes, because Win32_computerstem class in Windows 2000 (it is WMI used in the script Class) does not support JoIndomainorWorkGroup methods. In the WMI version of Windows XP and Windows Server 2003, the JoIndomainorWorkGroup method is added to the Win32_computersystem class. So how do you understand or learn it? One way is to use the WMI tool collection listed in the first part. Another more powerful, flexible approach is to use the WMI script library. One of the things that WMI, true cool, you can use the WMI script library to learn WMI. That's right, use the WMI script to retrieve the same method of WMI hosting resources, you can also write WMI scripts to learn about the various interesting details of WMI itself. You can write WMI scripts to list all namespaces and classes in the CIM repository. You can write a script to list all the providers installed on a computer that enables WMI. You can even write the WMI script to search the hosted resource class definition.

Whether you choose an existing tool or create your own tool, you need a basic understanding of the structure of the CIM repository. So, let us start from the place where the first part is stopped, and take a closer understanding of the WMI's management blueprint - CIM repository. In the entire discussion, we will use the WMI script library to explain how to retrieve WMI configuration information and manage resource class definitions.

Manage blueprint

In the first part, we said that the basic idea of ​​WMI is - configuration and management information from different sources can be uniformly represented by an architecture, and the CIM repository is a schema for WMI. The architecture can be imagined as a blueprint or a model that represents a thing existing in the real world. It is like building a model to build a physical structure (for example, a house), and WMI CIM builds a model that constitutes hardware, operating system, and software of the computer. CIM is the data model of WMI.

Note Although the CIM repository can store some data (and it does store), its main purpose is to build a model of the management environment. CIM is not designed for a large number of management information it defined. Instead, most of the data is dynamically retrieved from the WMI provider as needed. One exception is WMI operation data. WMI operation data (for example, named spatial information, provider registration information, managed resource class definition, and permanent event subscription) are stored in the CIM repository.

Figure 1 provides a conceptualized view of the internal structure and organization of a CIM repository. As shown in Figure 1, the CIM uses classes to create a data model. It is undeniable that CIMs are far exceeding 11 of the relationship maps - last time we count about 5,000 on Windows Server 2003. It is important to understand that the CIM repository is a custom WMI hosted environment and a class store for each manageable resource exposed through WMI.

Figure 1 shows three important CIM concepts, you need to understand them to successfully browse and explain the WMI architecture.

1. The CIM repository is divided into multiple namespaces. 2. Each namespace contains a group of one or more classes below: System class, core, and public class and / or extension classes. 3. There are three main types: abstraction, static and dynamic. The abstract class is a template for derived (defined) and non-abstract classes that cannot be used to retrieve an example of managed resources. Static class definitions of physical stored in a CIM repository - the most common is WMI configuration and operational data. Dynamic class is a class that models WMI managed resource modeling from the provider. The fourth type of associated class is also supported. Associated classes are an abstract, static or dynamic class, describe the relationship between two or hosted resources. Don't worry too much about the type of CIM class, we will soon discuss the CIM class type in a more practical environment. Let us see every CIM concept in more detail.

Figure 1: Structured view of the CIM repository - WMI architecture

Note CIM Physics resides in Windows XP and Windows Server 2003 named% systemroot% / system32 / wbem / repository / fs / objects.data file. Windows 2000 and Windows NT 4.0 Service Pack 4 stores CIM in% SystemRoot% / System32 / WBEM / Repository / Cim.rep. In Windows Millennium Edition (ME), Windows 98, and Windows 95 OSR 2.5 operating systems, CIM is stored in% Windir% / System / WBEM / Repository / Cim.rep.

Namespace definition

The CIM class is organized into the namespace. Namespace is the partition mechanism used by CIM, controlling the scope and visibility of managed resource class definitions. Each namespace in CIM contains a logical group that represents a specific technique or a management area. All classes in the namespace must have a unique class name, the class in a namespace cannot be derived from the class in another namespace, which is why you will find the same system, core defined in multiple namespaces. And public categories.

Most of the types of Windows managed resource modeling resident in the root / cimv2 namespace. However, according to the recommendations in Figure 1, root / cimv2 is not the only namespace you need to pay attention to. For example, event logs, performance counters, Windows installer, and Win32 providers store their managed resource class definitions in root / cimv2 namespace. On the other hand, the registry provider stores its class definition in the root / default namespace. In addition, the new Windows Server 2003 DNS provider stores its hosted resource class definition in the root / microsoftDNS namespace.

Name space

So how do name space affect your WMI script? Each WMI script is connected to a named space as part of the initial connection step (last month we briefly discussed), as shown below:

StrComputer = "."

Set WbemServices = getObject ("WinMgmts: //" & strComputer)

As above, if the target namespace is not specified, the script is connected to the namespace identified by the following registry:

HKEY_LOCAL_MACHINE / SOFTWARE / Microsoft / WBEM / Scripting / Default Namespace

The default namespace setting is the WMI script, and the default setting for% PATH% environment variable is the operating system. When you submit a command, the operating system uses% PATH% environment variable to locate the executable file of the command using the% Path% environment variable when you submit a command prompt. If the operating system cannot find this file, an error will occur. Similarly, when you retrieve a hosted resource in the WMI script, if you do not specify a namespace, the CIMOM (WMI service) looks for the blueprint (class definition) of the managed resource in the default namespace. If CIMOM can't find a managed resource class definition in the default namespace, a WBEM_E_INVALID_CLASS (0x80041010) error is generated.

Note Do not confuse the default namespace settings with root / default namespace. They are unrelated unless you set the root / default settings for your default namespace.

Namespace root / CIMv2 is initially configured as script default namespace; however, the default script namespace can be easily changed. Therefore, you should always identify a namespace of a managed resource in your WMI script, not the default setting. If we follow our own suggestions last month, all 4 lists (and the links 1 and 2 of this article) should be written as follows:

StrComputer = "."

SET WBEMSERVICES = GetObject ("WinMgmts: //" & strComputer & "/ root / cimv2")

Add the target namespace to the connection string to tell CIMOM where to find the managed resource class definition in the CIM, very much like the fully qualified path tells the operating system to find a file. When you specify the target namespace, the default namespace is not used.

Manage scripts default namespace

You can use the WMI script library with the Win32_WMisetting class to read and change the default namespace of the script in conjunction with the WMI script library to read and change the script. Win32_wmisetting is a dynamic class modeling for operating parameters for WMI services. The writable attribute indicates that the default namespace of the script is AspscriptDefaultNamespace.

Listing 3 Use the same three WMI scripts to write steps - connection, retrieval, and display - we have been using the steps, but there is a significant change. As mentioned earlier, we specify a fully qualified namespace of the Win32_WMisetting class in the WMI connection string that passes the getObject function of Microsoft Visual Basic Scripting Edition (VBScript). Then, here you will think Microsoft does not follow their own suggestions. Not only do we follow our namespace in Listing 3, but we will define namespaces since then. Yes, if you want to avoid invalidated class errors in your WMI script, it is so important.

Listing 3: In order to use WMI and VBScript, retrieve the default namespace of the script

StrComputer = "."

Set objwmiservice = getObject ("WinMgmts: //" & strComputer & "/ root / cimv2")

Set colwmisettings = objwmiservice.instancesof ("win32_wmisetting")

For Each Objwmisetting in ColWMisettings

WScript.echo "Default Namespace for Scripting:" & _objwmisetting.aspscriptdefaultnamespace

NEXT

To run the sample script in Listing 3, copy this script and paste into your favorite text editor, save the script (extension .vbs), then run the script as shown in Figure 2. You should see the default namespace of the local computer back to the console.

Figure 2: GetDefaultNameSpace.vbs output

To set the default namespace of the script, perform the same script in Listing 3, but to do an important change - well, if you count the number of questions, you count two. You should use SwbemObject to set the properties of the PUT_ method called SwbemObject to submit the changes to WMI managed resources without reading attributes from the WMI Script Library of SwbemObject from the WMI managed resource. Setting and submitting operations execute within the for Each cycle in Listing 4, because the SwbemServicesInstancesOf method always returns a SwbemObjectset collection, even if there is only one target WMI hosting resource instance, such as Win32_WMisetting.

Listing 4: Set the default namespace for the script with WMI and VBScript settings

StrComputer = "."

Set objwmiservice = getObject ("WinMgmts: //" & strComputer & "/ root / cimv2")

Set colwmisettings = objwmiservice.instancesof ("win32_wmisetting")

For Each Objwmisetting in ColWMisettings

Objwmisetting.aspscriptdefaultnamespace = "root / cimv2"

Objwmisetting.put_

NEXT

Don't focus too focus on the structure of the WMI script, because we will detail the WMI script library in the third part of this series. Now let's turn your attention back to CIM.

List the namespace

So far, we have used the same WMI script technique to retrieve an instance of dynamic WMI managed resources. For example, in the first part, we use the same script template to retrieve physical memory, services, event logging, and processes. In the second part, we retrieve service, operating system information, and script default namespaces. This shows that you can use the same WMI script technology to retrieve naming space information from the CIM. Like the situation in the hosted resource script, you need the only change to the script to be the target class name.

Name Space Information is stored in a CIM as a static instance of the __namespace class. __Namespace class is an example of a static class type of our previously defined defined. Unlike dynamic WMI managed resources from the provider on-demand, static class instances are stored in the CIM and do not need to be retrieved from the CIM using the WMI provider. Listing 5 Use the __namespace class to retrieve and return to all namespaces directly under the root namespace.

Listing 5: Retrieving CIM namespace using WMI and VBScript

StrComputer = "."

Set objServices = getObject ("WinMgmts: //" & strComputer & "/ root")

Set colnamespaces = objServices.instancesof ("__ namespace") for Each ObjNamespace in colnamespaces

Wscript.echo objnamespace.name

NEXT

Figure 3 shows the results of running Listing 5 on a Windows Server 2003 computer. The namespace list will vary depending on the different versions of Windows and WMI installed on the target computer.

Figure 3: GetNameSpaces.vbs output

If you may have noticed, Listing 5 does not provide a complete description of all available namespaces on the target computer. It only retrieves and is displayed in a single, specifies the namespace under the namespace. In order to return all namespaces on the local or remote enable WMI, you need to modify the list 5 to recursively connect to and enumerate each namespace. Fortunately, this doesn't want you to imagine it. Especially like the list of lists, we do this for you.

Change Listing 5 to the recursive namespace script shown in Listing 6, mainly including the original scripting body in the subroutine, and providing a mechanism to call the subroutines of each namespace instance retrieved from the CIM. Listing 6 This task is completed by performing the following steps:

1. Listing 6 initializes StrComputer from the name of the target computer. Single point (".") In WMI represents a local computer. You can change the values ​​assigned to the StrComputer to any WMI-enabled computer in the domain where you have managed control. 2. Script calls the recursive subroutine, then passed to the subroutine a string that initializes the namespace to "root". 3. The body of the enumnamespaces subroutine is the same as the list 5, except for an important change. Let us gradually study the subroutines.

1. EnumnameSpaces starts from the value of a single parameter strnamespace from the echo generic routine. The STRNAMESPACE identifies the namespace used in the connection string when the subroutine is called. 2. Use the getObject function in VBScript, and the subroutine is connected to the namespace identified by the Strnamespace parameter identifier of the subroutine. 3. After establishing the WMI service and namespace of the target computer, the subroutine immediately retrieves all namespace instances under the namespace referenced by the StrNameSpace reference. Use the for Each loop, the subroutine immediately enumerates the current connection Namespace instance under namespace. However, it is not simply emitting the name of the namespace, and the name of each sub-name space is connected to the current namespace in the new call to the EnumNameSpaces subroutine. Repeat these subroutine steps until all namespace instances are enumerated.

Listing 6: Retrieve all CIM namespaces using WMI and VBScript

StrComputer = "."

Call Enumnamespaces ("root")

Sub EnumNamespaces (StrnameSpace)

WScript.echo Strnamespace

Set objwmiservice = getObject ("WinMgmts: //" & strcomputer & "& strnamespace)

Set colnamespaces = objwmiservice.instancesof ("__ namespace")

For Each Objnamespace in colnamespaces

Call enumnamespaces (Strnamespace & "/" & objNamespace.name)

NEXT

End Sub

Figure 4 shows the results of running Listing 6 on the same Windows Server 2003 computer. Figure 4: GetAllNameSpaces.vbs output

Define class classification

As shown in Figure 1 above, there are three universal classes for constructing CIM: systems, cores, and public, and expansions.

System class

The system class is a class that supports internal WMI configuration and operations (for example, namespace configuration, namespace security, provider registration, and event subscriptions and notifications). When browsing the CIM, you can easily identify system classes through two underscores before each system class. For example, the __systemclass, __, and __win32provider classes shown in Figure 1 are system classes. In the previous section, our __namespace classes we study are examples of another system class.

The system class can be abstract or static. Abstract systems are templates for derived other abstract or static system classes. Static system class definitions Physics store WMI configuration and operational data in the CIM repository. For example, the __ Win32Provider system class defines the provider registration information stored in the CIM. CIMOM (WMI Service) uses the provider registration information stored in the CIM to map the request of the dynamic managed resource to the corresponding provider.

As we have previously used the __namespace system class, you can use the same WMI script technology to retrieve the static instance of the system class stored in the CIM. For example, Listing 7 retrieves and displays all the __win32provider instances registered in root / cimv2 namespace.

Listing 7: Retrieve Win32 Provider registered in root / CIMV2 namespace using WMI and VBScript

StrComputer = "."

Set objwmiservice = getObject ("WinMgmts: //" & strComputer & "/ root / cimv2")

Set colwin32providers = objwmiservice.instancesof ("__ win32provider")

For Each Objwin32Provider in ColWin32Providers

Wscript.echo objWIN32Provider.name

NEXT

Unless you are writing a book about WMI, you are unlikely to use the system class in the WMI script. There is an exception to the WMI monitor script. The WMI monitor script is a script for subscribing to the WMI event. (The event is a real-time notice of WMI hosting resources.) We will discuss WMI event subscriptions and notices in future columns.

Note For those who are inappropriate, three of the most common WMI __event system classes are: __ instancecreationEvent, __ instancemodificationeverent, and __instancedeeletionevent. Although we still discuss them here, you can find sample monitoring scripts that use these system classes in the monitor section of the TechNet Script Center.

Core and public categories

The core and public classes play two roles. First of all, it is also the most important, they show abstract classes - systems and application software developers (such as Microsoft Developers) derive and create specific technologies from these abstract classes. Second, they define all of the special management areas, but they are not limited to special technologies or resources. Distributed Management Task Force (DMTF) Defines and maintains the core and public categories that can be identified by the CIM_ prefix. The four classes starting in CIM_ are core and public classes in Figure 1.

In approximately 275 cores and public cages defined in root / cimv2 namespace, all of them are abstract classes in addition to several exceptions. What does this mean for you? This means you will rarely use the core and public categories (class CIM_-prefixed classes) in the WMI script. why? Because you can't retrieve an instance of an abstract class, the abstract class can only be used as the foundation of the new class. Because 271 in the core and public categories are abstract, they are mainly used by software developers to create specific technical extensions. So, what is the exception? 4 of 275 cores and public categories are not an abstract class. They use the Win32 Provider (CIMWIN32.DLL) to search the dynamic class of the hosted resource instance. Record, these 4 dynamic classes are CIM_DataFile, CIM_DirectoryContainsfile, CIM_ProcessExecutable, and CIM_VideoControllerResolution.

Extension class

Extended class is a specific technical class created by the system and application software developers. The win32_baseservice, win32_systemservices, win32_systemservices, and win32_computersystem classes shown in Figure 1 are Microsoft Extensions. The Microsoft extension class in the root / cimv2 namespace can be identified by the Win32_ prefix. Although so, you should not infer that all Microsoft extensions start with Win32_, because not this. For example, the stdregProv class defined in the root / default namespace is not prefixed in Win32_, although the StdRegProv class is a Microsoft extension class for registry management tasks. Before you ask, we must first say: No, we don't know why the stdregProv class is defined in root / default namespace instead of root / CIMv2.

When we write this article, approximately 463 Win32 expansion classes are defined in the root / cimv2 namespace. In 463 Win32 classes, 68 are abstract classes and the remaining 395 are dynamic classes. What does this mean for you? This means that the extension class is the primary category you will want to use in the WMI script.

Note The class statistics we provide is based on the beta version of Windows Server 2003, and only wants to explain the general CIM concept. Based on individual factors, such as: Windows versions, WMI versions, and installed software, your number will vary.

List of classes

At this point, we will tell you something should not be a big accident. You can write a script to retrieve all classes defined in a namespace. For example, inventory 8 lists all classes defined in the root / cimv2 namespace. However, unlike all the scripts that use the SwbemServicesInstanceSOF method, inventory 8 uses a different method, which is SubClassesof, which is also provided by the SwbemServices object of the WMI script library.

As the name of the method, SubClassesOf returns all subclasses that specify the parent class or namespace (when there is no parent class). Such as instancesof, subclasseSOF returns all subclasses in the SwbemObjectSet collection, where each project in the collection is a SwbemObject representing a single class.

Another important difference in Listing 8 is an objclass.path_.path attribute in the for Each loop body. Let's take a look at the for Each loop to understand what this is. The For Each loop is enumerating each SwbemObject (Objclass) in the SwbemObjectUBClasS set of SwbemServicesUBClassesof methods. Each SwbemObject represents a discrete class in the root / cimv2 namespace. This is some of the possibility of confusing. Unlike us, all the scripts displayed by the property defined by the hosted resource blueprint (class definition), Path_ is the attribute provided by the SwbemObject of the WMI script library. To understand this, you have to consider using SwbemObject's context. Do you use SwbemObject to access instances of managed resources? Or are you defined by using SwbemObject to access the category of the hosted resource?

When you use SwbemObject to access instances of managed resources, you are more likely to use SwbemObject to access properties and methods defined by managed resource blueprints (class definitions). When you use SwbemObject to get detailed class information - such as supported properties, methods, and qualifiers - you use the properties and methods provided by SwbemObject themselves. Path_ is a such attribute.

Path_ actually references another WMI script library object that provides the Path property named SwbemObjectPath. The SWBemObjectPathPath property contains a fully qualified path to the class referenced by the SwbemObject (ObjClass in Listing 8). A reminding you again, don't focus too much on the script object, because we will discuss in detail in the third part.

Listing 8: Retrieve all classes defined in root / cimv2 namespace using WMI and VBScript

StrComputer = "."

Set objwmiservice = getObject ("WinMgmts: //" & strComputer & "/ root / cimv2")

Set colclasses = objwmiservice.subclassesof ()

For Each Objclass in colclasses

WScript.echo Objclass.Path_.path

NEXT

Running on our Windows Server 2003 Computer Run list 8 shows a long list of 914 classes, Figure 5 shows part of it.

Figure 5: GetClasses.vbs output

Of course, you can easily modify the list 8 to list the classes in other namespaces by changing only the target namespace of the script. You can also use the list 8 with the FINDSTR.EXE command to search for classes. For users who are unfamiliar with the FindStr.exe command: FindStr.exe is a command line tool for searching for strings in a file.

For example, suppose you need to know if you are running Windows version supports new Windows XP and Windows Server 2003 Win32_TSSessionSetting classes. You can use the following command line to determine if the WIN32_TSSESSETTING class exists in the root / cimv2 namespace.

C: / scripts> CScript getClasses.vbs | FindSTR / I "Win32_tssetting"

Here to try a few additional solutions.

• List all system classes in root / cimv2 namespace: C: / scripts> CScript getClasses.vbs | FindSTR / I "__" • List all core and public categories in root / cimv2 namespace: C: / scripts > cscript getClasses.vbs | FindSTR / I "CIM_"

• List all Win32 extensions in root / cimv2 namespace: C: / scripts> cscript getClasses.vbs | FindSTR / I "Win32_"

• List all the c: / scripts> cscript getClasses.vbs | Findstr / I "Process" in the root / cimv2 namespace: c: / scripts> cscript getClasses.vbs |

CIM class type definition

It should be apparent that the class is the basic construction block of the CIM repository. WMI configuration information and WMI managed resources are defined by one or more classes. Similar to the Active Directory architecture, the CIM class is organized by level, in which subclasses in this organizational structure are inherited from the parent class, methods, and qualifiers (now do not have to consider attributes, methods, and qualifiers, we will be next Festival discussion). For example, Win32_Service Dynamic class is inherited from Win32_baseservice abstraction; the latter is inherited from the CIM_Service abstraction; CIM_Service abstraction is inherited from the CIM_LogicalElement abstraction class; CIM_LogicAleMent abstraction is inherited from the CIM_MANAGEDSystemElement abstraction (As shown in Figure 1). It is the sum of the category in the class level of the hosted resource definition to define managed resources.

As mentioned earlier, there are 3 main types: abstraction, static and dynamic.

Abstract class

The abstract class is a template for defining a new class. For example, the abstract class in the Active Directory architecture, the CIM abstraction class is based on other abstractions, static and dynamic classes. Each, um, almost the definition of each WMI hosted resource class is from one or more abstract classes (or derived).

You can identify abstract classes by checking the Abstract qualifiers of the class. The abstract class must define the Abstract Limit and set the value of the Abstract qualifier to True. Supplemental List A of this article shows how to use the WMI script library to list all abstraction classes defined in root / cimv2 namespace.

Abstract class types are most commonly used for core and public class definitions. Abstracts are very small in the WMI script because you cannot retrieve an instance of an abstract class.

Static class

Static class defines the data stored in the CIM repository. The static class has the same example as the dynamic class, but the instance of the static class is stored in the CIM repository. Similarly, static class instances are retrieved from the CIM. They don't use the provider.

You can identify static classes by checking the qualifiers of the class. However, it is different from the abstraction and dynamic class type identified by the specified default, and the static class is identified by not containing the Abstract and Dynamic qualifiers.

Static class types are most commonly used for system class definitions. The static class is extremely useful in the WMI script.

Dynamic class

Dynamic class is a class that models WMI managed resource from providing programs.

You can identify dynamic classes by checking the Dynamic qualifiers of the class. Dynamic classes must define a Dynamic qualifier and set the value of the Dynamic qualifier to True. Supplemental List B in this article demonstrates how to use the WMI script library to list all the dynamic classes defined in root / cimv2 namespaces.

Dynamic class types are most commonly used for definitions of expansion classes. Dynamic classes are the most common class types used in WMI scripts.

Associated class

The fourth type is called associated classes and is also supported. Association class is an abstraction, static or dynamic class that describes the relationship between two or hosted resources. The Win32_SystemServices class shown in Figure 1 is an example of a dynamic associated class that describes the relationship between the computer and the service running. You can identify associated classes by checking the class of Association qualifiers. Abstract, static or dynamic association classes must define the ASSociation qualifier and set the value of the Association qualifue to True.

Back to top

Analyze

It sounds like breaking a record, each of which is defined by a class through the WMI managed hardware and software resources. A class is a blueprint (or template) of a discrete WMI hosted resource, and all instances of resources use this blueprint. Class represents what your computer has. Because computers have things such as disks, event logs, files, folders, memory, printers, processes, processors, services, etc., WMIs have on disks, event logs, files, folders, memory, printers, processes, processors, Class of services such as services. Although there are exceptions (such as __event abstract system classes), most classes used in scripts can be directly contacted to actual, active substances.

These so-called blueprints are composed of attributes, methods, and restrictions. Before studying attributes, methods, and restrictions, let us briefly discuss the origins of the managed resource definition.

Suppose Microsoft decides to create a new, system administrator can be used to manage and monitor WMI providers for Microsoft DNS servers. The DNS Provider Development Team requires at least two files: a provider and a managed object format (MOF) file.

The provider is a dynamic link library that acts as the WMI infrastructure and the basic managed resource (in this example, the Microsoft DNS server). The provider responds to WMI requests by calling the local API of the hosted resource.

The MOF file contains a class definition that describes the functions provided by the DNS provider. The MOF file utilizes a function of describing the DNS provider for class that typically modeling resource modeling with the DNS server. Each class defined in the DNS MOF file defines data (attributes) - the data and properties are associated with the specified DNS-related resources, and the operations you can perform on this resource (Method).

After installing the DNS provider, the DNS Provider Dynamic Link Library registers the operating system and WMI, and the DNS MOF file has undergone a compilation process, which loads the DNS provider class definition to the CIM repository. At this point, the DNS provider can be used for any user-enabled users (including scripts).

Although our story is real - Microsoft has developed a new DNS provider for Windows Server 2003, the important thing that can be obtained is that the hosted resource class defines from the MOF file. The MOF file is for WMI and like the MIB file to SNMP.

The MOF file is based on a text file for a MOF language created and maintained by Distributed Management Task Force (DMTF). As shown in Figure 6, each managed resource class definitions comply with a well-defined structure and syntax.

Figure 6: Structure defined by hosted resource class

As shown in Figure 6, each managed resource class definition is composed of attributes, methods, and qualifiers.

Attributes

Attributes are the nouns describing the hosted resource. Class use properties describe, such as identification, configuration, and managed resource status, etc. For example, the service has a name, display name, description, startup type, and status. The Win32_Service class also has the same thing.

Each attribute has named, type, and optional attribute qualifiers. As with the method shown in the previous Listing 1, the property name is used with the SwbemObject of the WMI script to access the properties of the managed resource.

method

The method is to perform a verb of an operation on the hosted resource. What can you do with the service? Ok, you can start them, stop them, suspend them or continue them. The result is how to allow you to start, stop, suspend, and continue the service. Nothing is incredible. Each method is named, return type, optional parameter, and optional method qualifiers. Like attributes, the name of the name is used to use the SwbemObject of the WMI script library to call the method.

Not all classes define methods.

Default

The qualifier is an adjective that provides additional information about classes, attributes, or methods to what they apply. For example, the problem "WIN32_SERVICE class is?" Is an answer from the Dynamic qualifier of the class. When you start writing a WMI script that is not just simply retrieving information (for example, modifying attributes, or calling methods), the qualifier becomes more important because they define the operating features of the properties you are updating or being called. So which information provides for the qualifier?

Class qualifier

The class qualifier provides information about the class. E.g:

• If you know before, Abstract, Dynamic and Association qualifiers will tell you type. • The Provider qualifier tells you the provider of this class. For example, the Provider qualifier of the Win32_Service class tells you this class using the CIMWIN32 provider (CIMWIN32.DLL). On the other hand, as the Win32_NTLOGEVENT class is indicated by the Win32_NTLOGEVENT class, the Win32_NTLOGEVENT class uses the MS_NT_EVENTLOG_PROVIDER provider (NTEVT.DLL). • The Privileges qualifier tells you the special privileges you want to use. For example, the Privileges qualifier of the Win32_NTLOGEVENT class tells you that the SSESECURITYPRIVILEGE must be enabled before the Win32_NTLOGEVENT class can manage the security log.

Attribute qualifier

The attribute qualifier provides information about each attribute. E.g:

• The CIMTYPE qualifier tells you the data type of the property. • The READ qualifier indicates that this property is readable. • The WRITE qualifier indicates whether you can modify the value of the properties. For example, the AspscriptDefaultNamespace property of the Win32_WMisetting class modified in Listing 4 is marked as writable. On the other hand, all Win32_service properties elected in Listing 1 are defined as read-only - means that they do not define the WRITE qualifier. • The key qualifier indicates that this property is a key to the class and is used to identify the unique example of managed resources in the same resource collection.

Method definition

The method qualifier provides information about each method. E.g:

• The Implement Limit is indicated that this method has a implementation provided by the provider. • ValueMap qualifiers define a set of allowed values ​​for method parameters or return types. • The Privileges qualifier tells you the dedicated privileges you need to call this method.

There is more qualifiers than those mentioned herein. For a complete list, see the WMI Qualifiers theme in WMI SDK.

As shown in Figure 7, you can use the WMI Tester (WBEMTEST.exe tool to check the properties, methods, and qualifiers of the class. Of course, you can also use the WMI script library to retrieve the same information, soon you will see it.

Figure 7: Use the WMI Tester (WBEMTEST.EXE) View Win32_Service Class

Comparison class and hosting resources

Most WMI properties and methods are reasonably named. For example, as shown in Figure 8, if you will be compared to the properties and methods defined by the Win32_Service class, it is not difficult to infer Win32_service.name, win32_service.displayname or win32_service.displaithpion, may contain anything. Figure 8: Service Properties dialog and Win32_Service class properties and methods

So why should we care about all these content? Because the class determines what you can (or can't) do with WMI. If there is a class of services, you can manage the service; if not, you can't do this. Properties and methods are important because the WMI version is different between operating systems. Win32_computersystem classes in Windows XP have many new properties and methods, and they are not in the Win32_Computersystem class in Windows 2000. You must know the details of WMI, because of ADSI, in order to make the work, WMI properties and methods must be available for target computers.

How do I determine if a remote Windows computer supports an attribute or method? Check the class definition.

Search class definition

Like everything in WMI, there are countless ways to retrieve the class definition of managed resources. Ok, maybe we have a bit exaggerated, but it is also enough to say that there are many ways to provide solutions for each user interface preferences. If you want to retrieve text files, just split the MOF file. If you prefer the command line, use the WMI command line tool wmic.exe (Windows XP only). If you are willing to spend the time on the graphical tool, use the WMI tester (WBEMTEST.EXE) or CIM Studio. Or if you like us, use the WMI script library.

With the WMI script library, you can retrieve managed resource classes in three different ways.

1. You can search class information using SwbemObjectQualifiers_, Properties_, and Methods_ attributes. 2. You can use the SwbemObjectGTGETObjectText_ method to retrieve class definitions formatted in MOF syntax. 3. You can use the SWBemObjectExgetText_ method to retrieve class definitions formatted in XML (Windows XP and Windows Server 2003).

Let us briefly look at each script scheme, which ends today.

Use SwbemObject Properties_, Methods_ and Qualifiers_

Listing 9, 10 and 11 demonstrate how to use the extenties_, methods_, and Qualifiers_ attributes of the WMI script library to retrieve information about the Win32_Service class. We will study inventory 9, then point out the differences in Listing 10 and Listing 11, because three scripts use the same basic method.

Listing 9 begins with initialization three variables, they are: strComputer, Strnamespace and StrClass assignments to StrComputer are enabled WMI target computers. The value assigned to the StrnameSpace is the namespace to connect to. Values ​​assigned to STRCLASS are the name of the class in the target namespace, and the properties of this namespace will be retrieved and displayed. Separate these three values ​​to multiple variables to make other computers, namespaces, and classes of the script simpler. In fact, you can easily convert the list 9 to the command line script with the Windows Script Host (WSH) parameter set.

Next, this script uses VBScript's getObject function to connect to WMI services on the target computer. CAUTION What is the difference between the connection string passing to getObject? In addition to specifying the target namespace, the class name is also specified, which has a profound impact on the content returned by GetObject and WMI script libraries. For all the scripts we have, getObject returns a reference to the SwbemObject that represents the target class, rather than returns a reference to the SwbemServices object. why? The answer is the object path. Although we will discuss the object path in detail in the third part, we still give you an outline interpretation to help you understand what is done in Listing 9 to Listing 11 (and supplemental list c). Each WMI class and each WMI managed resource instance have an object path. Understand the object path as a WMI version of a fully qualified path. Each file has a fully qualified path, which is composed of the device name, followed by 0 or more directory names, plus the file name. Similarly, each class and hosted resources have an object path, which is enabled by the WMI computer name, followed by the CIM namespace, followed by the hosted resource class name, the key attribute of the KEY property, and the value of the key attribute, as shown below . (Note that square brackets only intend to distinguish the four license parts of an object path, they are not part of the object path.)

[//Computername][/namespace][ :classname][.keyproperty='Value ']

When you use all or part of the object path in the connection string passing to getObject (By the way, this is what we have been doing), the object path you use is determined by the reference type returned by the getObject and WMI script library. . For example, if you only contain a computer name part of an object path, you will get a SWBEMServices object reference to the default namespace. If you contain a computer name and / or namespace, you will also get a reference to the SwbemServices object. If you contain a computer name, namespace, and class name, you will get a reference to SwbemObject that represents this class. If all four parts are included, you will get SWBemObject that represents a managed resource instance identified by the class, key, and values. Remind again that we will discuss the object path in more detail in the third part of this series. Now, understand the OBJClass in Listing 9 is a reference to the SwbemObject that represents the Win32_Service class.

The remainder of the script is quite simple and easy. After returning a simple, identifying its property After the title of the class name of the display, the script uses the SwbemObject reference reference (OBJClass) returned from getObject to access the SwbemObjectProperties_ attribute (Objclass.properties_). The SwbemObjectProperties_ attribute references a SwbemPropertySet, which is a collection of properties of this class. Each attribute in the SwbemPropertySet collection is an SwbemProperty (ObjClassProperty) object, we use it to read and echo the name of each property.

In summary, the For Each loops enumerate the class's SwbemPropertySet collection (via the SwbemObjectProperties_ attribute) and returns the Name property of each SwbemProperty in the SwbemPropertySet collection.

Listing 9: Retrieving Win32_Service property using SwbemObject Properties_

StrComputer = "." strnamespace = "root / cimv2"

STRCLASS = "Win32_Service"

Set objclass = getObject ("WinMgmts: //" & strComputer &_

"/" & strnamespace & ":" & strs)

WScript.echo Strclass & "Class Properties"

WScript.echo "------------------------------"

For Each ObjclassProperty In objclass.properties_

WScript.echo Objclassproperty.Name

NEXT

Figure 9 shows the names of 25 attributes defined by the Win32_Service class (or inheritance).

Figure 9: GetProperties.vbs Output

In addition to a significant exception, the list 10 is the same as the list 9. For Each loop enumeration class SwbemMethodSet collection (via the SwbemObjectMethods_ attribute) and returns the Name property of each SwbemMethod (ObjClassMethode) in the SwbemMethodSet collection.

Listing 10: Use SwbemObject Methods_ to retrieve Win32_Service method

StrComputer = "."

Strnamespace = "root / cimv2"

STRCLASS = "Win32_Service"

Set objclass = getObject ("WinMgmts: //" & strComputer &_

"/" & strnamespace & ":" & strs)

WScript.echo Strclass & "Class Methods"

WScript.echo "---------------------------"

For Each ObjclassMethod in objclass.methods_

WScript.echo ObjclassMethod.Name

NEXT

Figure 10 shows the names of 10 methods defined by the Win32_Service class (or inherited).

Figure 10: GetMethods.vbs Output

In addition to three-point exception, Listing 11 is the same as the list 9 and the list 10.

1. For Each loop enumeration class SwbemQualifierSet collection (via the SwbemObjectQualifiers_ attribute) and returns the Name property of each Swbemqualifier (ObjclassQualifier) ​​in the Swbemqualifier (ObjClassqualifier). 2. Because the class qualifier is part of the class definition and the qualifier has a value, the Listing 11 also retrieves and elects the Value property of each Swbemqualifier (ObjClassquaalifier) ​​in the SWBemquaNErges collection. 3. Because a qualifier can have a number of values ​​stored in an array, the list 11 must illustrate this point before the value of the qualifier is read. If you don't do this, if the script is trying to read an array-based qualifier as a scalar variable, it will cause an error in runtime. The Privileges qualifier of the Win32_NTLOGEVENT class is an array-based qualifier instance. Listing 11: Use SwbemObject Qualifiers_ to retrieve Win32_Service class qualifiers

StrComputer = "."

Strnamespace = "root / cimv2"

STRCLASS = "Win32_Service"

Set objclass = getObject ("WinMgmts: //" & strComputer &_

"/" & strnamespace & ":" & strs)

WScript.echo Strclass & "Class Qualifier"

WScript.echo "------------------------------"

For each objclassqualifier in objclass.qualifiers_

If Vartype (Objclassqualifier.Value) = (VBVARIANT VBARRAY) THEN

Strqualifier = Objclassqualifier.name & "=" & _

Join (Objclassqualifier.Value, ",")

Else

Strqualifier = Objclassqualifier.name & "=" & _

Objclassqualifier.value

END IF

WScript.echo Strqualifier

Strqualifier = ""

NEXT

Figure 11 shows the names and values ​​of the five classes defined by the Win32_Service class definition (or inherit).

Figure 11: GetClassqualifiers.vbs output

If you may have noticed, Listing 9 and Listing 10 cannot display attributes and method qualifiers. To be honest, this is deliberate to keep the script in a size that is easy to understand. The good news is that the end of this column we have joined the full class qualifier, attribute, attribute qualifier, method, method definition script (see Supplemental List C). Welcome.

In case, this is not clear, you can combine the properties of each class defined in the CIM in a list 6 (getAllNameSpaces.vbs script) and the list 8 (getClasses.vbs script) to retrieve the properties of each class defined in the CIM. Methods and qualifiers. With the generated script with the findstr.exe command, you get a solution to search for any class, properties, methods, or qualifiers defined in the CIM. Use SwbemObject getObjectText_

In the previous we said, you can retrieve the management resource class definition directly from the MOF file (including the definition of the class). For example, if you want to find the Win32_Service class, you can view the% systemroot% / system32 / wbem / custom32.mof file. However, it is cost to use the MOF file directly. You must check each class in the class hierarchy of the hosted resource to get a full managed resource blueprint.

For example, you want to find Win32_Service. You have to check all 5 classes in the Win32_Service class hierarchy to get a complete blueprint, as shown in Figure 1. If you use the WMI tester (WBEMTEST.EXE) SHOW MOF button (see Figure 7), it is also the same. The more simple method of obtaining the form of the MOF representation is to use the SwbemObjectGTObjectText_ method of the WMI script, as shown in Listing 12.

Unlike Listing 9 to 11, inventory 12 uses the SwbemServicesget method to retrieve classes without using getObject. You must use the SWBEMSERVICESGET method to enable the WbemflagUseamentededquailifiers flag. Enable the WBEMFLAGUSEAMENDEDQUAILIFIERS flag telling WMI to return the entire hosting resource blueprint (class definition), not just local definitions.

There is also a second benefit using the wbemflaguseadeededqualifiers tag. You also retrieve class descriptions, as well as descriptions of the properties, methods, and qualifiers of each class. Class, attributes, methods, and qualifiers are typically defined in a localized purpose, separate MOF files. For example, the neutral language part of the Win32_Service class is defined in CIMWIN32.MOF. The specific language part of the Win32_Service class, includes description information, is defined in CIMWIN32.mfl. Specific language (or localized) MOF files typically have a .mfl (rather than .mof) extension.

The SWBEMServicesget method returns a reference to the SwbemObject (ObjClass) that represents the target class, which is used to call the SwbemObjectGTgetObjectText_ method. The getObjectText_ method returns the MOF representation of the class. If we use getObjectText_ without enabling WBEMFLAGUSEAMENDEDQUAILIFIERS tags, this method will only return only those defined by Win32_Service, and inherited attributes and methods are omitted.

Figure 12: Use SwbemObject GetObjectText_ to retrieve the MOF expression form of the Win32_Service class

StrComputer = "."

Strnamespace = "root / cimv2"

STRCLASS = "Win32_Service"

Const wbemflaguseagendededqualifiers = & h20000Set objWMiservice = getObject ("WinMgmts: //" & strcomputer & "/" & strnamespace)

Set objclass = objwmiservice.get (strclass, wbemflaguseageready)

Strmof = Objclass.getObjectText_

WScript.echo Strmof

However, there is a qualification for using getObjectText_: there is no information about inheritance definition in the MOF syntax included in this method. When the Key qualifier is defined in the properties of a parent class, if you want to use getObjectText_ to determine a class's Key property, this may bring problems.

Use SwbemObjectEx GetText_

Windows XP and Windows Server 2003 include a new way called GetText_, which can be used to retrieve the XML performance form defined by the managed resource class.

In addition to an obvious exception, use GetText_ similar to using getObjectText_ similar: 3 parameters passing to the getText_ method.

The first parameter is required, it identifies the generated XML format. It is currently possible as one of two values ​​defined by WMI WbemObjectTextFormatenum: WbemObjectTextFormatcimdtd20 (value: 1) or WBemObjectTextFormatWMIDTD20 (value: 2). Value 2 (WBemObjectTextFormatWMIDTD20) tells GetText_ The XML generated by the extended WMI version formatted according to the Distributed Management Task Force CIM Document Type Definition (DTD) version 2.0.

The second parameter is optional and is currently reserved for the operation mark. It must be set to 0 (zero).

The third parameter colnamedValueSet is also a SWBemNameDValueSet collection for providing a special instructions for getText_. Here, we let GetText_ perform:

• Retrieve and encode all properties and methods, more than just local defined properties and methods. • Contains class qualifiers, attribute qualifiers, and method qualifiers in the generated XML. • Contains system properties in the generated XML. • Contains a class origin for all properties and methods.

Listing 13: Use SwbemObjectEx getText_ to retrieve the XML performance form of the Win32_Service class (Windows XP and Windows .NET)

StrComputer = "."

Strnamespace = "root / cimv2"

STRCLASS = "Win32_Service"

Const wbemflaguseagendededqualifiers = & h20000

Const wbemObjectTextFormatWMIDTD20 = 2

Set objwmiservice = getObject ("WinMgmts: //" & strcomputer & "& strnamespace)

Set objclass = objwmiservice.get (strclass, wbemflaguseage) set colnamedvalueset = createObject ("wbemscripting.swbemnamedvalueset")

ColnamedValueSet.Add "Localonly", False

ColnamedValueSet.Add "includequalifiers", True

ColnamedValueSet.Add "Excludesystemproperties", False

ColnamedValueSet.Add "IncludeClassorigin", True

Strxml = objclass.gettext_ (WbemObjectTextFormatWmidtd20, 0, ColnamedValueSet)

Wscript.echo strXml

To successfully run list 13, copy the script and paste into your most common text editor, save the script (extension .vbs, for example: getXml.vbs), then run the script using the command line listed below.

C: / scripts> cscript // nologo getXml.vbs> Win32_service.xml

Figure 12 shows the generated XML file, Win32_Service.xml, using Microsoft Internet Explorer.

Figure 12: GetXml.vbs output

Back to top

Just here.

If there is any doubt, difficult or unknown for WMI, it may be a lot of data issued by WMI. We are willing to think that we have been equipped with knowledge and tools necessary to effectively find and explain the WMI managed resource class definition. Of course, you are the best referee for this point, so please try our best to know if we are in short. The boring content is over, ready to be happy in the third part when we invest in the WMI script library. Oh, no matter what, please send the rest of the time.

Wait! Before you pack, there is the last place to pay attention to: The WMI development team let us tell you that the WMI tool used before WMI SDK can now be updated. Updated tools (including WMI CIM Studio, WMI event registration, WMI event viewer and WMI object browser), are now compatible with Windows XP and Windows Server 2003 and Windows 2000. In addition, the updated tool does not contain WMI SDK, which means that you can now install these tools without having to install the entire WMI SDK. Isn't this very cool?

Back to top

Supplemental script

Listing A: List the abstract class type defined in root / cimv2 namespace

StrComputer = "."

Set objwmiservice = getObject ("WinMgmts: //" & strComputer & "/ root / cimv2")

Set colclasses = objwmiservice.subclassesof ()

For Each Objclass in colclasses

For each objclassqualifier in objclass.qualifiers_

If Lcase (Objclassqualifier.name) = "Abstract" thenswscript.echo objclass.path_.class & ":" & _

Objclassqualifier.name & "=" & _

Objclassqualifier.value

END IF

NEXT

NEXT

Listing B: List the dynamic class type defined in the root / cimv2 namespace

StrComputer = "."

Set objwmiservice = getObject ("WinMgmts: //" & strComputer & "/ root / cimv2")

Set colclasses = objwmiservice.subclassesof ()

For Each Objclass in colclasses

For each objclassqualifier in objclass.qualifiers_

If lcase (objclassqualifier.name) = "Dynamic" THEN

WScript.echo Objclass.Path_.class & ":" & _

Objclassqualifier.name & "=" & _

Objclassqualifier.value

END IF

NEXT

NEXT

List C: Use SwbemObject Qualifiers_, Properties_, and Methods_ to search class qualifiers, attributes, attribute qualifiers, methods, and method qualifiers

StrComputer = "."

Strnamespace = "root / cimv2"

STRCLASS = "Win32_Service"

Set objclass = getObject ("WinMgmts: //" & strComputer &_

"/" & strnamespace & ":" & strs)

WScript.echo Strclass & "Class Qualifier"

WScript.echo "------------------------------"

i = 1

For each objclassqualifier in objclass.qualifiers_

If Vartype (Objclassqualifier.Value) = (VBVARIANT VBARRAY) THEN

STRQUALIFIER = I & "." & objclassqualifier.name & "=" & _

Join (Objclassqualifier.Value, ",")

Else

STRQUALIFIER = I & "." & objclassqualifier.name & "=" & _

Objclassqualifier.value

END IF

WScript.echo Strqualifier

Strqualifier = ""

i = i 1

NEXT

WScript.echo

Wscript.echo strclass & "class property" "wscript.echo" ------------------------------------------------------------------------------------------------------------------------------------------------------------ -------------------- "

i = 1: j = 1

For Each ObjclassProperty In objclass.properties_

WScript.echo I & "." & Objclassproperty.name

For Each ObjPropertyqualifier In objclassproperty.qualifiers_

IF Vartype (ObjPropertyqualifier.Value) = (vbvariant vbarray) THEN

Strqualifier = I & "." & j & "."

ObjPropertyqualifier.name & "=" & _

Join (ObjPropertyqualifier.Value, ",")

Else

Strqualifier = I & "." & j & "."

ObjPropertyqualifier.name & "=" & _

ObjPropertyqualifier.Value

END IF

WScript.echo Strqualifier

Strqualifier = ""

J = J 1

NEXT

WScript.echo

i = i 1: j = 1

NEXT

WScript.echo

WScript.echo Strclass & "Class methods and method qualifier"

WScript.echo "---------------------------------------------- --- "

i = 1: j = 1

For Each ObjclassMethod in objclass.methods_

WScript.echo I & "." & Objclassmethod.name

For each objmethodqualifier in objclassmethod.qualifiers_

IF Vartype (ObjMethodqualifier.Value) = (vbvariant vbarray) THEN

Strqualifier = I & "." & j & "."

Objmethodqualifier.name & "=" & _

Join (Objmethodqualifier.Value, ",")

Else

Strqualifier = I & "." & j & "."

Objmethodqualifier.name & "=" & _

Objmethodqualifier.Value

END IF

WScript.echo Strqualifier

Strqualifier = "" j = j 1

NEXT

WScript.echo

i = i 1: j = 1

NEXT

Scripting clinic

Greg Stemp has long been recognized as one of the authorities in the US domestic scripting, and is widely known as world-class ... Haha! Well, how do you have a football coach in their resume? really? He was fired? Oh, OK. Greg STEMP is working in ... Oh, ok, I can't even say this? Ok! Greg Stemp raised from Microsoft, where he had the title of the SYSTEM Administration Scripting Guide.

Dean Tsaltas is a Nova Scotian living in redmond. He has begun to say a fluent American, and even laugh at his pronunciation of friends and families in the Marina. His computer career begins at his very small, then his grandmother and parents gave him, bought him with his beloved C-64, and subscribed to Compte! Journal. Now, he has worked for several years in Microsoft. He has a sentence to tell friends and family in hometown and Vancouver: "No, I haven't seen Bill yet!"

Bob Wells swayed around, and prepared to each of the people listening to him. There are rumors that Bob's two Daxie Rethers have more written to scripts than most human beings. BOB submitted to the System Administration Scripting Guide in a spare time.

Ethan Wilansky spends many of his working hours in writing and consulting. He is enthusiastic on script writing, yoga, gardening and his family (not necessarily in this order). He is currently working on a method of creating scripts that can put down the garbage and washing disc.

Getting started with WMI scripts: Part III

Release Date: 9/9/2004

| Update Date: 9/9/2004

Greg Stemp, Dean Tsaltas and Bob Wellsmicrosoft Corporation

Ethan Wilansky Network Design Group

Summary: Define the WMI script library and show how to use it to access and manage WMI managed resources. Take 7 basic script types that can be created with WMI scripts, which are used for tasks such as creation, delete, retrieving managed resource instances.

Script prepared with all the best! I haven't seen it for a while. Instead of using excuses, you are bored -, for example, we are completing the Microsoft Windows 2000 script guide (more about it in the future) - Not as good as letting us start, ok? We will start from the content of the WMI script to the content, turn your attention to the WMI script's mystery, the remaining part - WMI script library.

Before going deep into this section, let us briefly review the content we have discussed so far. Getting started at WMI scripts: In the first part, we discussed the structure and main components of WMI because they are related to WMI scripts. Getting started in WMI script: In the second part, we discussed the common information model (COMMON Information Model, CIM), which is a Knowledge Base that stores the WMI managed resource blueprint (class definition). Although we know that many people skip the second part (based on "Rate this page", we have assumed that you have learned this part. If you don't know, I think you know where to find it. This page

WMI script library definition explains WMI script library object model Scripting Guys WMI script template Guide Search Handling Resource Instance Displays the property of the hosted resource property to modify the hosted resource to create a new instance of the hosted resource Create a hosting resource to delete the hosted resource instance subscription event to here Bar

WMI script library definition

So, what is the WMI script library? Let us answer this question with a metaphor. Recall the stereo system or media player on your computer. What is the commonality of all stereo systems? For, they all have volume control, treble and bass control. For the radio, the tuner is the tuner, and there may be a equalizer. It doesn't matter if you choose to listen to Ba Doven, Qi Baillin spacecraft band, Art of noise, or no matter who is music, the controller always works.

WMI script library is like (not true like, just will be on your stereo system). That is, the WMI script is provided with a consistent controller (in the form of an automated object), which allows you to access and manage WMI managed resources. Whether you are managing computers, event logs, operating systems, processes, services, or selection of resources that you love, the objects in the WMI script are always also working.

The consistency provided by the automation objects in the WMI script library is optimally conveyed through the limited tasks that you can perform using the WMI script library. Overall, you can create seven basic script types using the WMI script library.

1. You can retrieve the WMI managed resource instance. 2. You can read WMI managed resource properties. 3. You can modify the WMI managed resource properties. 4. You can call the WMI managed resource. 5. You can create a new instance of WMI managed resources. 6. You can delete an instance of WMI managed resources. 7. You can schedule events to monitor the creation, modification, and / or deletion of WMI managed resources.

You can use the 7 basic script type as a script template. Just like the volume controller adjusts any CD, the cassette, the 8-track tape or. WMI script template can be used to manage any WMI managed resources. Once you know about the template to manage a class of WMI managed resources, you can easily rewrite the same template to manage it into a hundred other WMI managed resources.

WMI script library object model

Since we have determined that the WMI script is the control panel of the entire WMI infrastructure, let us open it and explore. In Figure 1 of the first part of this series, the implementation of the WMI script library is a single automation component called WBEMDisp.dll in the% SystemRoot% / System32 / Wbem Directory.

In general, the WMI script library consists of 24 automation objects (19 in Windows 2000 and earlier), 21 of which are described in the WMI script library object model relationship diagram shown in Figure 1. Now, you must understand all 24 objects, how terrible details, you feel polite, you don't need that. In fact, you will be very happy to know that there is a basic understanding of the two to three objects shown in Figure 1, you can create 6 of the 7 script templates listed above. What are the objects? Take a little, you have to stop, wait until we finish. In addition to 24 automation objects in WBEMDisp.dll Windows XP and Windows Server 2003, the script library also contains 13 enumerations. Enumeration is just an alias for a set of constants. We will not discuss this set of constants here because they are very clear in WMI SDK. To learn more about the WMI script constant, see the script API constant in the WMI SDK.

In many ways, you can use the automation objects in the WMI script to be used by the core interface provided by ADSI. What do we mean? This, the ADSI core interface (for example, IADS and IADSContainer) provides a consistent way for the script objects in Active Directory - regardless of the objects and properties of the object. Similarly, the automation object in the WMI script is a consistent and unified script model for WMI managed resources.

Understanding the relationship between the automation objects in the WMI script library (WBEMDisp.dll) and the custom resource class definition in the CIM Knowledge Base (Objects.data) is important. As we explained in the second part, the hosted resource class is defined as a blueprint for computer resources disclosed by WMI. In addition to defining the hosted resources, the blueprint also defines the only method and properties for each managed resource.

On the other hand, the WMI script provides an instance of an automated object script set in a usual sense for verifying and connecting to WMI, and subsequently accessing instances of WMI managed resources. Once the WMI script is used to obtain an instance of the WMI managed resource, you can access the method and properties defined by the category definition of the hosted resource - as if these methods and properties are part of the script library.

Figure 1. WMI script library object model wbemdisp.dll

Back to top

Explain the WMI script library object model

Although Figure 1 looks not very intuitive, the WMI script library object model provides a large number of in-depth explorations on how WMI scripts work. The line in Figure 1 points to the object obtained by calling the method (or access attribute) of the original object. For example, call the Swbemlocator ConnectServer method, return a SWBEMServices object. To call the SwbemServiceSexecNotificationQuery method, return to the SWBEMEventSource object. On the other hand, call the SWBEMServicesExecQuery or InstanceSof method to return to the SwbemObjectset collection. To call the SWBEMSERVICESGET method, return to SwbemObject.

Let us appear in this series and the WMI script of the second part and the object model, and how they work. Usually for most WMI scripts, each script performs three basic steps.

1. Each script starts with the WMI service connected to the target computer. This script uses the GetObject function of Microsoft Visual Basic Scripting Edition (VBScript) with the WMI connection string, and the connection string consists of WMI name object "WINMGMTS:", followed by the WMI object path to the target computer and namespace. STRComputer = "." set objswbemservices = getObject ("WinMgmts: //" & struct ")

Use this method to connect to WMI to return a reference to the SWBemServices object shown in Figure 1. Once a reference to the SwbemServices object, you can call SwbemServices. The calling SWBEMServices method mainly depends on the type of WMI script you created. 2. Next, use the SwbemServicesInstancesOf method, each script retrieves a WMI managed resource instance. SET COLSWBEMOBJECTSET = ObjswbemServices.instancesof ("Win32_Service")

Instancesof always returns a SwbemObjectset collection. As shown in the connection between SwbemServices and SwbemObjectSet objects, SwbemObjectSet is one of the three WMI script library object types that SWBEMServices can return. 3. Finally, by enumerating the instance in the SwbemObjectset, each script accesses the properties of the WMI managed resource. For Each ObjswbemObject in ColSwbemObjectset

Wscript.echo "name:" & objswbemObject.name

NEXT

As shown in Figure 1, each managed resource instance in the SWBemObjectSet collection is represented by a SwbemObject.

There are three most important things in the 24 automation objects in the WMI script library - that is, you should learn the object - SwbemServices, SwbemObjectSet and SwbemObject. why? Because SwbemServices, SwbemObjectSet and SwbemObject are essential for almost every WMI script. In fact, if we retrieve the ADSI class, SwbemServices, SwbemObjectSet and SwbemObject are corresponding to WMI scripts, IADS and IadsContainer are corresponding to ADSI scripts. (Scripting Guys) Free: For those who have not yet been involved in the ADSI script, there is a tip here - that is, IADS and IADSContainer are you first study in the 6 interfaces provided by the ADSI library. Believe in us.)

SwbemServices is an object that represents a verified connection to the WMI namespace on the local or remote computer. In addition, SwbemServices plays an important role in each WMI script. For example, you use the SwbemServicesInstancesOf method to search all instances of hosted resources. Similarly, you combine the SwbemServiceSexecQuery method with a WQL (WMI query language) query to use an instance of all or a subset of hosted resources. In addition, you use the SwbemServiceSexecNotificationQuery method to subscribe to the event that represents changes in the managed environment. SwbemObjectSet is a collection of zero or more SwbemObject objects. Why is it zero? Because of a computer, it is possible to say, such as a zero instance of a tape drive (modeling by Win32_TaPedrive). Each SwbemObject in SwbemObjectSet can represent one of two things:

1. Example of the WMI managed resource. 2. Examples of class definitions.

SwbemObject is a multi-identity object that serves the resources you are managed. For example, if you retrieve the instance of Win32_Process managed resources, SwbemObject presents an identity of analog Win32_Process class definition, as shown on the left side of Figure 2. On the other hand, if you retrieve the instance of Win32_Service managed resources, SwbemObject presents the identity of the analog Win32_Service class, as shown on the right of Figure 2.

Figure 2. SwbemObject plays WIN32_PROCESS and WIN32_SERVICE

If you carefully study Figure 2, you will notice that SwbemObject discloses two distinct methods and properties sets. The top collection with the name of the next scribe is SwbemObject, which resides in WBEMDisp.dll. Underline is used to prevent it from conflict with the names and properties defined by the managed resource class definition.

The method and attribute set at the bottom of the figure are not part of the SWBemObject. They are defined by managed resource class definitions in CIM. When you retrieve an instance of an instance or hosted resource, SwbemObject dynamically binds the methods and properties defined by the managed resource class definition. You use SwbemObject to call methods and access properties defined in managed resource class definitions, as if the method and properties are part of the SwbemObject. SwbemObject transforms any managed resource defined in CIM is why the WMI script is so intuitive. Once you know how to connect and retrieve an instance, then everything is set to SwbemObject.

Ok. So what about the WMI script library object model? This object model tells you that you can use the GetObject function of VBScript (or WSH) with WMI name object (Winmgmts :), and a WMI object path (for example, "[// computername] [/ namespace] [: classname] [. KeyProperty = "Value ']") is used in conjunction to create SWBEMSERVICES and SWBEMOBJECT. On the other hand, Swbemlocator, Swbemlasterror, SwbemObjectPath, SwbemNamedValueSet, SwbemSink, SwbemDateTime, and SwbemRefresher objects are created using the CreateObject function of VBScript (or WSH). The remaining objects cannot be created using getObject or createObject. Instead, they are obtained by calling a method or accessing an attribute. The object model also tells you that 7 objects in the WMI script publicly open a SwbemSecurity object, just like the security label icon instruction next to the object next to or on the right.

For more information on specifying the footbook objects, methods, or attributes, see the WMI script API in the WMI SDK document. To understand the basic mechanisms of the WMI script library, let's transfer attention to the 7 WMI script templates listed above. How about the content of the variable naming practice before we continue?

Three words about variable naming practice

In subsequent sample scripts, the variable names used to reference each WMI automation object follow consistent naming practices. Each variable is named according to the name of the automation object in the WMI script, with "OBJ" as a prefix (for object reference) or "col" (for the set object reference). For example, a variable that references the SwbemServices object is named objswbemservices. A variable that references SwbemObject is named objswbemobject. And a variable that references SwbemObjectSet is named colswedbemObjectSet.

Why is this important? Of course, people can argue that it is not important. However, this idea is to help you understand the type of WMI object you are using at different points in the WMI script. If it is helpful, it is good. If not, I ignore it. Another thing that is slightly important is that the subject is that the object reference variable name can be any name that meets your favorite. If you prefer a variable name like "foo" and "bar", or "Dog" and "CAT", that is also possible. There is no requirement that you must name a reference to the SwbemServices object ObjswbemServices. This is just how we do it.

Back to top

WMI Script Template Guide for Scripting Guys

It is undeniable that WMI is very difficult to learn and it is more difficult to use. In many ways, it is very difficult to get this reputation because WMI is really difficult. It's not just because it is too big. WMI can be used to manage anything within the scope of computer hardware, computer software, and almost both. Some people will naturally think that any techniques that contain such many different elements must be difficult.

In fact, in accordance with numerous standard methods, many tasks can be implemented with WMI. For example, you have seen a template as the basis for scripts, these scripts returns information about almost any managed resource. In the first part of this series, the same basic script (having one or two smaller modifications) are used to return a total of events that are like installed memory, service, and event logs in the event log. The following topics provide basic WMI script templates, which can be used:

• Retrieve managed resource instances. • Display managed resource properties. • Modify the managed resource attribute. • Call the managed resource method. • Create a new instance of the hosting resource. • Delete instances of managed resources. • Subscribe to the event to monitor the creation, modification, and / or delete of managed resources.

Before we start, we need to make sure that we are very clear about: You can (and can't) do what is managed by the hosted resource is a hosted resource blueprint in a common information model (CIM) repository (ie class) Definition) is determined instead of the WMI script library. This is why the second part of this series is slightly important (hint, hint). Don't you believe it? We will give you some examples.

You can only modify the writable properties. How to determine if a property can be written? The "WRITE" qualifier of the property can be checked using Wbemtest.exe, WMI CIM Studio, WMIC.exe, or a script. (See Figure 7 or Listing C in the second part of this series as how to check attribute qualifiers.) If the "Write" qualifier is not defined for the attribute, then the default value is "false", which means that this property is only Read.

An example is to: If the class definition of the resource sets the subscript of the SupportsCreate class to "True", you can only create a new instance of the hosted resource. How do you determine a managed resource class definition to set SupportsCreate as "True"? Again, as shown in FIG. 7 and in the list of the second part of this series, you check the class qualifier of the hosted resource.

Note In things, you will find that some managed resources can be created, updated, and / or deleted, even if the category definition of the managed resource cannot be set to the appropriate qualifier. We were told that this is being corrected.

I have to say something before the start. All of the following script templates are designed for local computers. This is achieved by setting the value of the variable StrComputer to a point ("."). To run a script on a remote computer, just set the StrComputer's value to the name of the remote computer. For example, this line code will run on a computer named ATL-DC-01:

STRComputer = "ATL-DC-01"

Back to top

Search for hosting resources

So far, we have always used the SwbemServicesInstanceSof method to search for hosted resource instances, as shown in Listing 1.

Listing 1. Use SWBEMSERVICES InstancesOf to retrieve service information

StrComputer = "."

Set objswbemservices = getObject ("WinMgmts: //" & strComputer & "/ root / cimv2")

SET COLSWBEMOBJECTSET = ObjswbemServices.instancesof ("Win32_Service")

For Each ObjswbemObject in ColSwbemObjectset

WScript.echo "Display Name:" & objswbemObject.displayName & vbcrf & _ "State:" & objswbemObject.State & Vbcrlf & _

"START MODE:" & objswbemObject.startmode & vbcrlf

NEXT

Although INSTANCESOF has indeed successful, what is the case of only a subset of instances or properties? Suppose you want to optimize instances and properties to restore to the smallest network traffic. In this case, you will be very happy to hear WMI support a large number of strong query tools.

Query WMI is a process that issues a request to a managed resource that matches some predefined conditions. For example, WMI queries can only request services with StartMode Of Auto (automatic start mode) in the Stopped state.

The WMI query provides a more efficient mechanism for the retrieval of managed resource instances and their properties. The WMI query returns only the instances and properties that match the query, but instancesof always returns all instances of the specified resource and all properties of each instance. Similarly, the query is performed on the target computer consistent with the object path, not on the source computer running the script. Therefore, the WMI query can significantly reduce network traffic caused by less efficient data retrieval mechanism like instancesof.

To query WMI, use WMI Query Language (WQL) to construct a query string. The query string defines the results that must be satisfied to obtain successful match. After the query string is defined, the query is submitted to the WMI service using the SwbemServiceSexecQuery method. A hosted resource instance that meets the query is returned to the script in the form of a SWBemObjectSet collection.

Using WQL and ExecQuery methods (instead of instancesof) provides flexibility to create scripts that return only items that you are interested. For example, you can use a basic WQL query to return all properties of all instances of a given housing resource, as shown in Listing 2. This is the same as the information returned by the InstancesOf method. If you compare lists 1 and 2, you will notice that the bold part of the third line is the only difference between the two scripts.

Listing 2. Search service information using SWBEMSERVICES EXECQUERY

StrComputer = "."

Set objswbemservices = getObject ("WinMgmts: //" & strComputer & "/ root / cimv2")

SET COLSWBEMOBJECTSET = ObjswbemServices.execQuery ("SELECT * WIN32_SERVICE")

For Each ObjswbemObject in ColSwbemObjectset

WScript.echo "Display Name:" & objswbemObject.displayName & Vbcrlf & _

"State:" & objswbemObject.state & vbcrlf & _

"START MODE:" & objswbemObject.startmode & vbcrlf

NEXT

You can also use WQL to create a targetful query, that is, do the following things:

• Returns the selected properties of all instances of the hosted resource. "SELECT DisplayName, State, StartMode from win32_service" • Returns all properties of a class selected instance. "Select * from win32_service where state = 'stopped'"

• Returns the selected properties of a class's selected instance. "SELECT DisplayName, State, StartMode from Win32_Service Where State = 'Stopped'"

Creating a targetful query sometimes significantly increases the speed of data returns. (For example, returning only those events containing EventCode 0 in the application event log are more fast than returning all events in all event logs.) The target query also makes the data returned easier. For example, suppose you only want an event with EventCode 0 in the application event log, you will return only those items that use the target. Instead, instancesof will return all events, and you will have to check each event separately and determine if it: 1. From the application event log and, 2. With EventCode 0. Although this can be done, this is too low and it needs additional work for you.

A targetful query can also reduce the number of returned data, which is an important consideration to the script running on the network. Table 1 shows some different numbers of different query types. As you can see, the number of data returned through various query types is considerable.

Table 1. Comparison of different instances of WMI query and retrieval methods / WQL query objSWbemServices.InstancesOf bytes returned ( "Win32_Service") 157,398 objSWbemServices.ExecQuery ( "SELECT * FROM Win32_Service") 156,222 objSWbemServices.ExecQuery ( "SELECT Name FROM Win32_Service ") 86,294 objSWbemServices.ExecQuery (" SELECT StartMode FROM Win32_Service ") 88,116 objSWbemServices.ExecQuery (" SELECT StartMode FROM Win32_Service WHERE State = 'Running' ") 52,546 objSWbemServices.ExecQuery (" SELECT StartMode, State FROM Win32_Service WHERE State = 'Running' ") 56,314 objswbemservices.execquery (" SELECT * WIN32_SERVICE WHERE Name = 'Winmgmt') 27,852 ObjswBemServices.get ("Win32_Service.Name = 'Winmgmt') 14,860

At this point, we hope that we have convince you, about ExecQuery better than instancesof. Let us go from Listing 2 to a universal WMI script template, which can be easily modified to retrieve any instance of any WMI managed resource. Listing 3 contains our first template.

Listing 3. Template for retrieving managed resource instances

StrComputer = "."

Strnamespace = "/ root / cimv2"

STRCLASS = "Win32_Service" set objswbemservices = getObject ("WinMgmts: //" & strComputer & strnamespace)

SET ColSwbemObjectSet = ObjswbemServices.execQuery ("Select * from" & strclass)

For Each ObjswbemObject in ColSwbemObjectset

WScript.echo "Display Name:" & objswbemObject.displayName

Wscript.echo "State:" & objswbemObject.state

Wscript.echo "Start Mode:" & objswbemObject.startmode

NEXT

Use this template with other WMI classes:

1. Set the value of StrClass to the corresponding WMI class for the target hosting resource. 2. If necessary, set the value of StrNameSpace to the WMI namespace of the target class. 3. Replace the statement in the FOR Each loop of the display attribute and its value. Delete the following line and replace them with the corresponding code line of the displayed attribute value. WScript.echo "Display Name:" & objswbemObject.displayName

Wscript.echo "State:" & objswbemObject.state

Wscript.echo "Start Mode:" & objswbemObject.startmode

Scripting Guys Free Release If you are using a managed resource that returns a number of instances (for discussion purposes, we will "many" define more than 1000), you can optimize ExecQuery by using optional tags. For example, suppose you use ExecQuery to query event logging (modeled by Win32_NTLOGEVENT class). If you are known, the event log will contain thousands of records. By default, you may encounter performance issues related to returning a large number of result sets, such as event log queries. The reason that must be implemented in this way is that WMI caches a SwbemObject reference for each instance, or in our example, is for each event log. To avoid this problem, you can let ExecQuery return to only SwbemObjectSet, as shown below.

StrComputer = "."

Strnamespace = "/ root / cimv2"

STRCLASS = "Win32_NTLOGEVENT"

Const wbemflagreturnimmediately = & h10

Const wbemflagforwardonly = & h20

Set objswbemservices = getObject ("WinMgmts: //" & strComputer & strnamespace)

SET ColswbemObjectSet = ObjswbemServices.execQuery ("Select * from" & strs, _

"Wql" _

Wbemflagreturnimmediately wbemflagforwardonly) 'Insert RemainDer of Script Here (E.g., for Each Next Loop ...

Note WBEMFLAGRETURNIMMEDIATELY tag (which is defined in one of our previously descriptions) is the default ExecQuery behavior and is semi-synchronized. Important optimization is to add a WBemFlagForwardonly tag. Combine WbemflagreturnimMediaTely and WbemflagForwardonly will get a only enumeration number. The only enumeration is much faster than the default enumeration, as WMI does not maintain references to objects in SwbemObjectSet.

Back to top

Display managed resource properties

One limit of the script shown in Listing 3 is that it needs you know the name of all the properties you want to retrieve and display. If you want to display a value of all the properties of a resource, you don't know the name of these properties, and you don't want to type 40 or 50 line code that you need to display each property value. What should I do? In this case, you can use the template in Listing 4, which automatically retrieves and displays the value of each property found in a class.

Listing 4. Scriptomatic Lite Template

StrComputer = "."

Strnamespace = "/ root / cimv2"

STRCLASS = "Win32_Process"

Set objswbemservices = getObject ("WinMgmts: //" & strComputer & strnamespace)

SET ColSwbemObjectSet = ObjswbemServices.execQuery ("Select * from" & strclass)

WScript.echo "Scriptomatic Lite - Class:" & strclass

Wscript.echo "===================================" & string (len (strinclass), "=") & vbcrlf

INTINSTANCE = 1

For Each ObjswbemObject in ColSwbemObjectset

WScript.echo "Instance:" & INTINSTANCE & VBCRLF & "--------------"

For each objswbemproperty in objswbemObject.properties_

StropertyValue = ConvertPropertyValuetostring (ObjswBemProperty.Value)

Wscript.echo objswbemproperty.name & ":" & strpropertyValue

NEXT

WScript.echo

INTINSTANCE = INTINSTANCE 1

Function ConvertPropertyValuetostring (Byval PropertyValue)

IF isobject (propertyValue) THEN

ConvertPropertyValuetString = "" Elseif Isnull (PropertyValue) THEN

ConvertPropertyValuetString = ""

Elseif Isarray (PropertyValue) THEN

ConvertPropertyValuetString = Join (propertyValue, ",")

Else

ConvertPropertyValuetString = CSTR (PropertyValue)

END IF

END FUNCTION

Use this template with other WMI classes:

1. Set the value of the STRCLASS to the appropriate WMI class for the target hosting resource. 2. If necessary, set the value of StrNameSpace to WMI namespace for the target class.

Back to top

Modify the properties of hosted resources

In Windows 2000, WMI is the main read-only technology. In the 4,395 properties defined in the Windows 2000 root / CIMV2 namespace, only 39 properties are writable. These numbers have increased in Microsoft WindowsXP, 145 can be writable in approximately 6,560 properties. This number is even greater in Windows Server 2003.

The template in Listing 5 demonstrates how to modify a writable attribute. This script retrieves all instances of managed resources simulated by the Win32_osRecoveryConfiguration class. (In this case, this class only contains a single instance.) This script provides a new value for the three properties (DebugInfotype, DebugFilePath, and OverWriteexistingDebugfile) and the SwbemObjectput_ method submits a change (so configuring the operating system recovery option). If you forget to call the PUT_ method, these changes will not be applied.

Note This template only works on the writable properties. Trying to change the read-only properties will result in errors. To determine if an attribute is writable, check the "WRITE" qualifier of this property.

Listing 5. Templates for modifying the writable properties of the hosted resource

StrComputer = "."

Strnamespace = "/ root / cimv2"

STRCLASS = "Win32_OSrecoveryConfiguration"

Set objswbemservices = getObject ("WinMgmts: //" & strComputer & strnamespace)

SET ColSwbemObjectSet = ObjswbemServices.execQuery ("Select * from" & strclass)

For Each ObjswbemObject in ColSwbemObjectset

ObjswbemObject.debuginfotype = 1

ObjswbemObject.debugfilepath = "c: /tmp/memory.dmp"

ObjswbemObject.OverWriteexistingdebugfile = false

ObjswbemObject.put_

NEXT

Note how SwbemObject is used in the for Each loop to: (1) Direct access and modification is defined by the win32_osrecoveryConfiguration class; (2) calling its own PUT_ method to submit the changes. Use this template to use other WMI classes that implement writable properties:

1. Set the value of StrClass as the corresponding WMI class for the target managed resource. 2. Enter the value of the Strnamespace as the WMI namespace of the target class if necessary. 3. Replace the statement in the for Each loop in which the new attribute value is configured. Delete the following line, and replace them with the corresponding code line being modified: objswbemObject.debuginfotype = 1

ObjswbemObject.debugfilepath = "c: /tmp/memory.dmp"

ObjswbemObject.OverWriteexistingdebugfile = false

Back to top

Call the management resource method

The method defined in the class definition of the hosted resource allows you to perform operations on the managed resource. For example, the Win32_Service class contains methods such as launching and stopping services; Win32_nteventlogfile contains methods for backing up and clearing event logs; Win32_OperatingSystem includes restarting or shutting down a computer.

Listing 6 provides a template that can be used to write scripts that call the WMI managed resource method. This specific script uses the StopService method for the Win32_Service class to stop the "Alarm" service on the local computer.

Note This method must be implemented before calling the method defined in the class definition of the hosted resource. How to determine if a method is implemented? Check the implementation of this method. TRUE Values ​​indicate that a method has the implementation provided by the provider. It has been said that some methods should not be defined to implement a qualifier, even if the method has been implemented. The Win32_ServiceStopService method shown below is such an example. Determine if a method is implemented, it will also be involved in some troubles and errors. As we mentioned earlier, we were told that solutions were being corrected.

Listing 6. Template for calling managed resource methods

StrComputer = "."

Strnamespace = "/ root / cimv2"

STRCLASS = "Win32_Service"

Strkey = "name"

strkeyvalue = "alerter"

Set objswbemservices = getObject ("WinMgmts: //" & strComputer & strnamespace)

SET ColswbemObjectSet = ObjswbemServices.execQuery_

("Select * from" & strclass & "where" & strkey & "= '" & strkeyvalue & "')

For Each ObjswbemObject in ColSwbemObjectset

objswbemobject.stopservice ()

NEXT

Use this template with other WMI classes:

1. Set the value of StrClass to the corresponding WMI class for the target hosting resource. 2. If necessary, set the value of StrNameSpace to the WMI namespace of the target class. 3. Set the value of StrKey to form the name of the WHERE clause basics. 4. Set the value of StrKeyValue to StrKey. 5. Replace the statement in the for Each loop of the call mode. Delete the following line and replace them with the corresponding code line being called: if necessary, you must also join the appropriate method parameters. ObjswBemObject.StopService () Back to top

A new instance of creating a hosted resource

Some WMI classes allow you to create a new instance of its modeling resource. For example, you can create environment variables with Win32_environment classes, Win32_Process class creation process, Win32_share class creates shared resources.

Before you create a new instance of the resource, you must verify that the category of the managed resource supports the creation operation. Verify by checking the SupportScreate qualifier of this class. A TRUE value indicates the creation of this class support instance (default value false). Once you have determined this class support to create actions, you must determine how to create a new instance. There are two ways to create a new instance:

1. If this class defines the CreateBy class qualifier with the value of PutInstance, you create a new instance using SwbemObjectSPawnStance_ and PUT_ methods. 2. If the value assigned to the CreateBy class qualifier is not Putinstance (for example, it is create), you create a new instance using methods identified by the CreateBy qualifier.

Let's take a look at each template.

Listing 7 demonstrates how to create a resource when the resource class definition is set to TRUE, when setting the createby to PutInstance, how to create an instance of the resource. After connecting to the WMI on the target computer, your first step should be a blueprint (ie, class definition) that you want to create (ie class definition). To do this, use the SwbemServicesget method to retrieve the actual WMI class (not the retrieval class instance). After the object indicating the class, create a new, "blank" instance using the SwbemObjectspawnInstance_ method. Set the properties of the new instance and call the SwbemObjectPut_ method to create a new instance.

Listing 7. Creating a new instance template with spawnInstance_ oí PUT_

StrComputer = "."

Strnamespace = "/ root / cimv2"

STRCLASS = "Win32_ENVIRONMENT"

Set objswbemservices = getObject ("WinMgmts: //" & strComputer & strnamespace)

Set objswbemObject = objswbemservices.get (strclass)

Set objNewswBemObject = objswbemObject.spawninstance_ ()

ObjneWSwbemObject.properties_.item ("name") = "tmpshare"

ObjneWSwbemObject.properties_.item ("UserName") = ""

ObjneWSwbemObject.properties_.item ("variablevalue") = "c: / tmp" ObjnewswbemObject.put_

Use this template with other WMI classes that support Putinstance:

1. Set the value of StrClass as the corresponding WMI class for the target managed resource. 2. Enter the value of the Strnamespace as the WMI namespace of the target class if necessary. 3. Replace the statement that configures environment variable values. Delete the following row and replace them with the corresponding code line of the object being created: objnewswbemObject.properties_.item ("name") = "tmpshare"

ObjneWSwbemObject.properties_.item ("UserName") = ""

ObjneWSwbemObject.properties_.item ("variablevalue") = "c: / tmp"

Scripting Guys Free Release When you create a new instance using SwbemObjectSPawnInstance_ and PUT_ methods, you must provide (one or more) values ​​for all key properties of the class. For example, the WIN32_ENVIRONMENT class used in Listing 7 defines two key properties: Name and Username. How to determine a class key property? Use WBEMTEST.EXE, WMI CIM Studio, WMIC.exe or script to check the key qualifier of this property.

Listing 8 demonstrates how to create an instance of the resource when providing its own creation method. After connecting to the WMI on the target computer, your first step should be a blueprint (ie, class definition) that you want to create (ie class definition). To do this, use the SwbemServicesget method to retrieve the actual WMI class (not the retrieval class instance). After the object indicating such a class, the method of calling the CreateBy qualifier identification of the class is called with the SWBemObject. The script template in Listing 8 creates a new shared folder using the Win32_share create method.

Listing 8. Templates for creating new instances using managed resource methods

StrComputer = "."

Strnamespace = "/ root / cimv2"

STRCLASS = "Win32_share"

Const Shared_folder = 0

StrPath = "C: / TMP"

STRSHARENAME = "TMP"

INTMAXIMALLOWED = 1

STRDESCRIPTION = "Temporary Share"

Set objswbemservices = getObject ("WinMgmts: //" & strComputer & strnamespace)

Set objswbemObject = objswbemservices.get (strclass)

IntreturnValue = ObjswbemObject.create (StrPath, _

STRSHARENAME, _

Shared_folder, _

INTMAXIMUMALLOWED, _

STRDESCRIPTION)

WScript.echo "Return Value:" & intReturnValue

To use a template with WMI classes that provide custom creation methods: • Set the value of strclass to the corresponding WMI class for the target hosting resource. • If necessary, set the value of StrNameSpace to the WMI namespace of the target class. • Replace the statement of the initialized variable, which is the parameter that is passed to the creation method. Delete the following line and replace them with the corresponding code line being created: const shared_folder = 0

StrPath = "C: / TMP"

STRSHARENAME = "TMP"

INTMAXIMALLOWED = 1

STRDESCRIPTION = "Temporary Share"

• Replace the Win32_share create method call with the appropriate method you are creating the managed resource you are creating. Delete the following line and replace them with the corresponding code line being created: intReturnValue = ObjswBemObject.create (strpath, _

STRSHARENAME, _

Shared_folder, _

INTMAXIMUMALLOWED, _

STRDESCRIPTION)

Scripting Guys Gifts When you create a new instance using methods provided by a category definition of managed resources, you must provide values ​​for any mandatory parameters defined by this method. For example, the Win32_share class used in Listing 8 defines 3 forced parameters: path, name, and type. How do you determine the forced parameters of a method? Refer to the class definition of managed resources in WMI SDK.

Back to top

Delete managed resource instance

If you can create a new instance of a hosted resource, you can delete an instance. In fact, control which managed resource instances can be deleted and those rules that control creation operations are amazing. Let's take a request, then we will look at several examples.

Before deleting a resource instance, you must verify whether the class of the managed resource supports delete operation. This is done by checking the SupportSdelete qualifiers of the class. A TRUE value indicates that this type of support is deleted (the default value is false). Once you have already determined such support deletion, you must determine how to delete instances. There are several ways to delete instances:

• If this class defines the DELETEBY qualifier for the value of DeleteInstance, you can use the SWBEMServicesDelete or SwbemObjectDelete_ method to remove the instance. • If the value assigned to the Deleteby class limit is not deleteInstance (for example, it is delete), you can use a method of delete the method to delete an instance.

Listing 9 and Listing 10 demonstrate how to delete the environment variables created in Listing 7. Listing 9 Using the SWBEMServicesDelete method, Listing 10 uses the SwbemObjectDelete_ method. When the resource class definition is set to True, you can use the list 9 and the list 10 when the And Deleteby is set to DeleteInstance.

Listing 9. Templates for deleting instances using SWBEMSERVICES Delete Method

StrComputer = "."

Strnamespace = "/ root / cimv2"

Strinstance = "Win32_environment.name = 'tmpshare', username = ''"

Set objswbemservices = getObject ("Winmgmts: //" & struser & strnamespace) ObjswbemServices.delete strinstance

Listing 10. Templates for deleting instances using SwbemObject Delete_ method

StrComputer = "."

Strnamespace = "/ root / cimv2"

Strinstance = "Win32_environment.name = 'tmpshare', username = ''"

Set objswbemservices = getObject ("WinMgmts: //" & strComputer & strnamespace)

Set objswbemObject = objswbemservices.get (strinstance)

ObjswbemObject.delete_

To use these templates with other WMI classes that support DeleteInstance:

1. Set the Strinstance value to the corresponding WMI class, key, and key value of the target managed resource instance.

Listing 11 deletes the shared folder created in Listing 8, while doing this, demonstrate how to delete an instance of the resource when a resource class definition provides its own deletion method. It takes a little time to compare lists 10 and 11. Check out what is different outside the obvious value assigned to Strinstance? When the class definition of the hosted resource is set to DeleteInstance, the list 10 uses the SwbemObjectdelete_ method (note underscore) to delete an instance. On the other hand, the Listing 11 uses the Win32_share delete method.

Listing 11. Templates for deleting instances using managed resource methods

StrComputer = "."

Strnamespace = "/ root / cimv2"

Strinstance = "Win32_share.name = 'tmp" "

Set objswbemservices = getObject ("WinMgmts: //" & strComputer & strnamespace)

Set objswbemObject = objswbemservices.get (strinstance)

ObjswbemObject.delete

To use this with other WMI templates that provide custom deletion methods:

1. Set the Strinstance value to the relevant WMI class, key, and key value of the target managed program instance.

Back to top

Subscribe event

Great. The first project of this practice: is lazy! Don't worry, we are still talking about event subscriptions. However, not here, but we will introduce our sisters: TechNet TALES from the Script column, we just published a brief Introduction to WMI Events. In addition to seeing the introduction to WMI event subscription, you will also find another script resource.

Back to top

Just here.

At the end of our WMI script trilogy. It is undeniable that there are still many things that need to be discussed, and we will continue later. If you want to send us a suggestion on the Scripting CLINC topic you want to read, we will be very happy. You can send us a message from the "User Opinions" at the top of this page. There is something before we forget. Remember Microsoft Windows 2000 Scripting Guide - Do we mention the book mentioned in this article about automation system management? Already written! Although we hope that you all rushed to buy a book - By the way, BookPool is the lowest price technology book online retailer on the earth, but we also know that the world is like our own hammer. Therefore, we have also provided this book all 1328 online reading. Then, next time scripting clinic, um, you will go out later. If you think some or all of this book, anyway, let us know your opinion - good, poor or disgusting. Of course, we are more interested in what we are missing and what we can do to improve the second edition. I hope you can see you!

Scripting clinic

Greg Stempgreg Stemp has long been recognized as one of the authorities of the United States to write scripts in the United States, and is widely known as world-class ... Haha! Well, how do you have a football coach in their resume? really? He was fired? Oh, very good! Greg STEMP is working in ... Oh, ok, I can't even say this? Ok! Greg Stemp sells the salary from Microsoft, in Microsoft he has the title of the SYSTEM Administration Scripting Guide.

Dean Tsaltas is a Nova Scotian living in redmond. He is already able to say a fluent American, and even laugh at his pronunciation of friends and family in his coastal province. His computer career begins at his very small, then his grandmother and parents gave him, bought him with his beloved C-64, and subscribed to Compte! Journal. Now he has worked in Microsoft several years. He has a sentence to tell friends and family in hometown and Vancouver: "No, I haven't seen Bill yet!"

Bob Wells is free to walk around, and the benefits of the people who listen to him. There are rumors that Bob's two Daxie Rethers have more written to scripts than most human beings. BOB submitted to the System Administration Scripting Guide in a spare time.

Ethan Wilansky spends many of his working hours in writing and consulting. He is enthusiastic on script writing, yoga, gardening and his family (not necessarily in this order). He is currently working on a method of creating scripts that can put down the garbage and washing disc.

转载请注明原文地址:https://www.9cbs.com/read-87090.html

New Post(0)