Safely Using WMI in PowerShell (Part 3)

by Nov 20, 2019

In this mini-series, we are looking at the differences between Get-WmiObject and Get-CimInstance. Future PowerShell versions no longer support Get-WmiObject, so it is time to switch to Get-CimInstance if you haven’t already.

In the previous part you learned that both cmdlets return the same basic information for WMI classes, but the metadata properties added by both cmdlets differ considerably, and occasionally, the data type for properties differs, too. For example, date and time is returned as DateTime by Get-CimInstance, and as a string representation by Get-WmiObject. Overall, the differences are minimal, though, and easy to adjust.

Once you start querying information over the network, there is a considerable difference between Get-WmiObject and Get-CimInstance:

  • Get-WmiObject uses DCOM for all remoting. It is hard-wired. DCOM is an old remoting protocol. It uses a lot of resources, and requires many ports to be open in your firewall.
  • Get-CimInstance uses WinRM by default and works like a web service. However, you can change this behavior in many ways, so the remoting layer was separated from the actual WMI query.

You might notice this difference when you try and contact an old server, and the server responds to Get-WmiObject but throws an exception with Get-CimInstance. Old servers only support the old DCOM protocol.

Here is how you can tell Get-CimInstance to fall back to the old DCOM protocol that Get-WmiObject used:

# replace server name to some server that you control
$server = 'SOMESERVER1'

# Get-CimInstance uses WinRM remoting by default
Get-CimInstance -ClassName Win32_BIOS -ComputerName $server

# telling Get-CimInstance to use the old DCOM to contact an old system
$options = New-CimSessionOption -Protocol Dcom
$session = New-CimSession -SessionOption $options -ComputerName $server
Get-CimInstance -ClassName Win32_BIOS -CimSession $session
Remove-CimSession -CimSession $session 

As you see, you can configure a CimSession object which is fully configurable. Using a CIMSession object instead of a computer name has another advantage: you can reuse the session for multiple queries which saves a lot of time. Just make sure you close the session when you are done.


Twitter This Tip! ReTweet this Tip!