Home > Articles > Programming > Windows Programming

Efficient Windows PowerShell Administration with WMI and CIM

Timothy Warner, author of Sams Teach Yourself Windows PowerShell in 24 Hours, differentiates between the often-confused terms WMI and CIM, and explains how best to use these technologies with Windows PowerShell.
Like this article? We recommend

Let's imagine that you and I started a business manufacturing and selling network interface cards (NICs). Industry standards would be pretty important to us, right? How could we make it easier for our Ethernet NICs to work natively with systems based on, say, Windows, Linux, and OS X? What about compatibility with different network architectures, protocols, and client/server applications? (Whoa—I'm glad we don't really need to worry about that particular set of problems!)

Windows systems administrators rely on several Distributed Management Task Force (DMTF) industry standards to make our lives easier. The DMTF is an industry consortium whose membership includes major computer hardware and software manufacturers. Their goal is to agree on standards so their products work together as seamlessly as possible.

In this article, we'll look at how to apply a couple of key DMTF standards to help us be more effective with Windows PowerShell–based systems administration.

Understanding the Relationship Between CIM and WMI

The Common Information Model (CIM, pronounced sim) is a DMTF specification that describes computer hardware and software components. CIM is part of a larger systems-management framework called Web-Based Enterprise Management (WBEM).

Every Windows server or client computer has a local CIM repository. As systems administrators, we can tap into that CIM repository to fetch and set properties and take action on the repository data.

Although it's a long-time DMTF member, a while back Microsoft made the ill-advised decision to write its own abstraction layer on top of CIM, called Windows Management Instrumentation (WMI).

What's confusing to many admins is that in Windows PowerShell v3 and later we can access the CIM repository by using either WMI or CIM calls. One of my goals in this article is to show you the pros and cons of each approach.

Let's begin by running through a simple example to help us visualize the CIM repository. At the moment I'm running a Windows 8.1 computer on which I've installed the free and open-source WMI Explorer desktop application. Figure 1 shows an annotated user interface.

Figure 1 WMI Explorer.

We start using WMI Explorer by clicking Connect to load the current computer's CIM repository (annotation A in Figure 1). The namespace is the highest level in the CIM hierarchy. In my experience, we use ROOT\CIMV2 almost exclusively for Windows systems management. When we double-click ROOT\CIMV2, after a moment the Classes pane populates (annotation B). Whereas a namespace defines a group of related classes, the class itself is a blueprint (definition) for a particular hardware or software component.

Type service in the Quick Filter list and double-click Win32_Service to load all service instances on the local computer (annotation C). If we think of a class as a generic object blueprint, an instance is an individual copy of that blueprint.

Any Windows computer has many services running, so WMI Explorer displays a mighty big list of service instances. Type spooler in the Quick Filter list and double-click Win32_Service.Name="Spooler" to load the properties of that instance (annotation D).

At the bottom of the WMI Explorer window (annotation E) is the following query:

SELECT * FROM Win32_Service WHERE Name='Spooler'

Earlier I explained that WMI is Microsoft's implementation of CIM. Microsoft also created the WMI Query Language (WQL) to give admins a method that works like Structured Query Language (SQL) for accessing CIM object data. If you don't yet know SQL, I'd encourage you to learn it, because you can apply that syntax in WQL to query system configuration data.

Finally, spend some time clicking across the six tabs marked at annotation F:

  • Instances: Defines the object and shows selected attributes (properties) that describe the object).
  • Properties: Full list of properties, along with their descriptions. The window that shows the MSDN documentation is especially helpful here.
  • Methods: Actions that an object can perform. For example, we can call StartService() and StopService(), respectively, to start and stop the given service.
  • Query: Use WQL syntax to run ad hoc queries against the current object.
  • Script: Generate a PowerShell script from the current query.
  • Logging: Status messages reported from the CIM repository itself.

WMI in Action

I don't want to spend too much time on the WMI cmdlets because, frankly, Microsoft is deprecating them in favor of its own CIM cmdlets. However, you'll still need the legacy WMI commands if you're supporting computers running Windows PowerShell v1 or v2 or if legacy scripts are used in your environment.

Let's enumerate the WMI cmdlets:

Get-Command -Noun wmi* | Select-Object -Property Name

Name
----
Get-WmiObject
Invoke-WmiMethod
Register-WmiEvent
Remove-WmiObject
Set-WmiInstance

For accessing the local computer's CIM repository, Get-WmiObject works pretty well. The command defaults to the ROOT\CIMv2 namespace, so all we need to do is to supply the appropriate class name:

Get-WmiObject -Class Win32_OperatingSystem

SystemDirectory : C:\Windows\system32
Organization    :
BuildNumber     : 9600
RegisteredUser  : Windows User
SerialNumber    : 00261-80246-78149-AA747
Version         : 6.3.9600

The WMI situation begins to show its age when we use the -ComputerName parameter to retrieve WMI information from remote computers:

Get-WmiObject -Query "SELECT * FROM win32_service WHERE name='Spooler'" -ComputerName
 localhost,mem1,mem2 | Format-List -Property PSComputerName,Name,State,Status

PSComputerName : DC1
Name           : Spooler
State          : Running
Status         : OK

PSComputerName : MEM1
Name           : Spooler
State          : Running
Status         : OK

PSComputerName : MEM2
Name           : Spooler
State          : Running
Status         : OK

Sure, it works, but at what cost?

Notice the handy -Query parameter in the previous example. If you've worked with relational databases and the SQL data access language, you'll feel right at home with using WQL to query CIM repository data. Here's the deal: The Get-WmiObject cmdlet uses old-school PowerShell remoting, which involves the following issues:

  • The underlying network transport involves DCOM and RPC, which are older, "heavier" protocols with corresponding reduced network performance.
  • DCOM and RPC use dynamic port allocation, which means that you'll have difficulty on most networks unless the appropriate firewall rules are configured.
  • Remote computers are queried serially rather than in parallel.

These three issues (especially the firewall port issue) can plague your work with annoying problems. For instance, frustrating "No RPC server available" error messages might crop up when you use Get-WmiObject, because the cmdlet is trying to use random TCP ports.

If the WMI cmdlets have any advantage, it's that you can take action on CIM repository data from remote computers, using methods available to you because DCOM and RPCs build up and tear down persistent connections to the remote CIM repositories for each connection request. Take a look:

$mem2spool = Get-WmiObject -Query "SELECT * FROM win32_service WHERE name='Spooler'"
$mem2spool | Get-Member -MemberType Method | Select-Object -Property Name

Name
----
Change
ChangeStartMode
Delete
GetSecurityDescriptor
InterrogateService
PauseService
ResumeService
SetSecurityDescriptor
StartService
StopService
UserControlService

That capability is actually pretty cool, because we can control that remote service by using dot notation:

$mem2spool.StopService()
$mem2spool.StartService()

As we'll see next, the "new school" CIM commands don't have methods—or at least not initially.

CIM in Action

Whereas the old WMI cmdlets use stateful connections for remote access and trip over existing firewall rules, the new CIM cmdlets run in a much leaner, meaner fashion, thanks to their use of the DMTF Web Services-Management (WS-Man) protocols.

Current Windows OS versions rely on the Windows Remote Management (WinRM) service to make standards-based PowerShell remoting possible. PowerShell WS-Man remoting brings these possibilities:

  • HTTP/HTTPS transport and XML serialized data streams make the remote access extremely firewall-friendly.
  • WS-Man remoting is stateless, which means faster performance than with the older DCOM/RPC methods.
  • Remote computers are queried in parallel, in what Microsoft calls a "fan out" remote management scenario.

Pretty exciting stuff!

Let's enumerate the CIM cmdlets:

Get-Command -Module CimCmdlets | Select-Object -Property Name

Name
----
Export-BinaryMiLog
Get-CimAssociatedInstance
Get-CimClass
Get-CimInstance
Get-CimSession
Import-BinaryMiLog
Invoke-CimMethod
New-CimInstance
New-CimSession
New-CimSessionOption
Register-CimIndicationEvent
Remove-CimInstance
Remove-CimSession
Set-CimInstance

The Get-CimInstance command is the direct analog to Get-WmiObject, so I suggest that you learn how to use this command post-haste. Let's get help:

Get-Help Get-CimInstance -ShowWindow

One great thing about the CIM cmdlets (unlike the WMI cmdlets) is that they support tab completion! This feature is tremendously useful when you aren't exactly sure which class name you need:

PS C:\> Get-CimInstance -ClassName Win32_BIOS


SMBIOSBIOSVersion : 6.00
Manufacturer      : Phoenix Technologies LTD
Name              : PhoenixBIOS 4.0 Release 6.0
SerialNumber      : VMware-56 4d f5 d0 c3 4b d8 9e-3b bf 2e fa 04 4d 67 d7
Version           : INTEL  - 6040000

Following are two examples in which we look for processes whose names start with the letter n. Notice that we can use -Query with a WQL expression or -Filter with a more PowerShell-native filter expression. Both examples return the same results:

Get-CimInstance -Query "SELECT * FROM Win32_Process WHERE name LIKE 'n%'"

ProcessId Name        HandleCount WorkingSetSize VirtualSize
--------- ----        ----------- -------------- -----------
664       notepad.exe 76          7524352        2199118839808
1664      notepad.exe 76          7491584        2199122526208


Get-CimInstance -ClassName win32_process -Filter "name like 'n%'"

ProcessId Name        HandleCount WorkingSetSize VirtualSize
--------- ----        ----------- -------------- -----------
664       notepad.exe 76          7524352        2199118839808
1664      notepad.exe 76          7491584        2199122526208

But wait—what about remote access, and what I said about methods earlier in this article? Take a look:

$mem1spooler = Get-CimInstance -ComputerName mem1 -query "SELECT * FROM win32_service WHERE name='Spooler'"
$mem1spooler | gm -MemberType Method

   TypeName: Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_Service

Name                      MemberType Definition
----                      ---------- ----------
Clone                     Method     System.Object ICloneable.Clone()
Dispose                   Method     void Dispose(), void IDisposable.Dispose()
Equals                    Method     bool Equals(System.Object obj)
GetCimSessionComputerName Method     string GetCimSessionComputerName()
GetCimSessionInstanceId   Method     guid GetCimSessionInstanceId()
GetHashCode               Method     int GetHashCode()
GetObjectData             Method     void GetObjectData(System.Runtime.Serialization.S...
GetType                   Method     type GetType()
ToString                  Method     string ToString()

Remember those useful methods that become available when we use Get-WmiObject to create a variable to hold a remote server's spooler service? Not so with Get-CimInstance. The reason is simple: WS-Man remoting is stateless, so there's no persistent link to the remote computer's CIM repository.

Also, WS-Man remoting uses SOAP and XML to serialize the data stream from the remote host to your local server, so you're not dealing with live objects as you are with Get-WmiObject. Long story short—no methods. However, we can absolutely leverage the PowerShell pipeline and the Invoke-CimMethod cmdlet to call a method. Suppose I stop the Spooler service on my mem1 server, like this:

Get-CimInstance -ComputerName mem1 -query "SELECT * FROM win32_service WHERE name='Spooler'" | Invoke-CimMethod -MethodName StopService

In case you wondered how I knew to call StopService as my method, let me draw your attention to the Get-CimClass cmdlet:

Get-CimClass -ClassName Win32_Service  | Select-Object -ExpandProperty CimClassMethods

Name                  ReturnType Parameters
----                  ---------- ----------
StartService              UInt32 {}
StopService               UInt32 {}
PauseService              UInt32 {}
ResumeService             UInt32 {}
InterrogateService        UInt32 {}
UserControlService        UInt32 {ControlCode}
Create                    UInt32 {DesktopInteract, DisplayName, ErrorControl, LoadOrde...
Change                    UInt32 {DesktopInteract, DisplayName, ErrorControl, LoadOrde...
ChangeStartMode           UInt32 {StartMode}
Delete                    UInt32 {}
GetSecurityDescriptor     UInt32 {Descriptor}
SetSecurityDescriptor     UInt32 {Descriptor}

Next Steps

If you understood what we covered in this article, you've come a great distance in mastering PowerShell-based management with CIM. Your next step is to learn how to use CIM sessions to make even more efficient use of network bandwidth when managing remote computers. To that point, I'll leave you with a few references to check out:

Happy PowerShelling!

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020