PowerShell Function to Create CimSessions to Remote Computers with Fallback to Dcom

I’ve found myself writing the same code over and over in my PowerShell scripts where I’m performing a task that requires me to create a CimSession to one or more computers without knowing what version of PowerShell is installed on the remote computers or if PowerShell is even installed on the remote computers.

While it is possible to create a CimSession to a remote computer in any of those scenarios I just described, it’s a fair amount of code to add to multiple scripts and then the same redundant code ends up being in multiple files which creates a nightmare if you ever find an issue with the code and need to update it for any reason.

I decided to turn the code I would use to create these CimSessions into a function which is shown below and add it to a script module so I could just call the function from the PowerShell script that needed the CimSessions created before the script performs its task(s).

This function will create a CimSession to a remote computer(s) using the WSMAN protocol if the stack version is 3.0 or higher:


The following regular expression matches any version that is 3.0 or higher:

[3-9] Numbers three through nine.
| or
[1-9] Numbers one through nine. [0-9] Followed by numbers zero through nine. + One or more times.
\. A “dot” is a special character so it must be escaped with a backslash.
[0-9]+  Numbers zero through nine. One or more times.

I’ll use this function to create a CimSession to servers named SQL01 and SQL03:


Notice in the previous example that one CimSession was created with the WSMAN protocol and the other one with DCOM. Believe it or not, SQL03 is a Windows 2008 Server (non-R2) that does NOT have PowerShell installed at all:


The previously created CimSessions can be used to query information from WMI on the remote computers regardless of which underlying protocol is used for communication:


The function shown in the blog article can also be downloaded from the TechNet Script Repository.

Update: The most recent version can be downloaded from my PowerShell repository on GitHub.



  1. Tony Auby

    Other than the fact that you’re using the newer PS CIM cmdlets, what is the difference between Get-CIMInstance over the CIMSession and Get-WMIObject -ComputerName , where the CIMSession has connected via DCOM?

  2. Tony Auby

    Why does the WSMAN Stack version have to be 3.0 or greater?


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: