In the previous tip we explained why Get-CimInstance may have advantages over the older Get-WmiObject cmdlet.

Now here is another example that illustrates just why Get-CimInstance may be much faster than Get-WmiObject.

When you need to query multiple WMI classes from a remote machine, for example because you are building an inventory report, Get-WmiObject needs to connect and disconnect each time you run the cmdlet. Get-CimInstance, however, can reuse an existing session.

Here is an example illustrating how the same session is used for two queries:

# create the session
$options = New-CimSessionOption -Protocol Wsman
$session = New-CimSession -ComputerName sr0710 -SessionOption $options

# reuse the session for as many queries as you like
$sh = Get-CimInstance -ClassName Win32_Share -CimSession $session -Filter 'Name="Admin$"'
$se = Get-CimInstance -ClassName Win32_Service -CimSession $session

# remove the session at the end
Remove-CimSession -CimSession $session

If you need to target older computers that do not support WSMan, simply change the protocol to DCOM in the code above: replace “Wsman” by “Dcom”.

Twitter This Tip! ReTweet this Tip!