PowerShell for Windows Admins

Jun 30 2017   12:59PM GMT

Finding a CIM class

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Tags:
CIM
Powershell
WMI

One of the problems you might find is finding a CIM class. You know its name but you don’t know which namespace its in.

The old WMI cmdlets allow you to search the namespaces recursively

PS> Get-WmiObject -Class Win32_Process -Namespace root -Recurse -List


 NameSpace: ROOT\CIMV2

Name Methods Properties
 ---- ------- ----------
 Win32_Process {Create, Terminat... {Caption, CommandLine, CreationClassName, CreationDate...}

But the CIM cmdlets don’t have this functionality. I’ve been meaning to do something about this for ages but finally got motivated by something I read while proof reading PowerShell in Action – yes its getting closer, much closer.

What I ended up with is these 2 functions

function get-namespace {
 [cmdletBinding()]
param ([string]$namespace = 'root') 
 Get-CimInstance -Namespace $namespace -ClassName '__NAMESPACE' |
 foreach {
 "$namespace\" + $_.Name
 get-namespace $("$namespace\" + $_.Name)
 }
 }

function find-cimclass {
 [cmdletBinding()]
param (
 [string]$namespace = 'root',
 [string]$classname
 )

$class = $null

## test namespace for class
 $class = Get-CimClass -Namespace $namespace -ClassName $classname -ErrorAction SilentlyContinue

if (-not $class) {
 $namespaces = get-namespace -namespace $namespace
 foreach ($name in $namespaces){
 $class = $null
 $class = Get-CimClass -Namespace $name -ClassName $classname -ErrorAction SilentlyContinue
 if ($class){break}
 }
 }

$class
 }

Find-Cimclass takes a namespace and class name as parameters. It tries to find the class in the given namespace. If it can’t find it then get-namespace is called to generate a list of namespaces to search. The function iterates over the collection of namespaces testing each one for the class. When it finds the class it returns the class information.

Get-namespace searches for all instances of the __Namespace class in the given namespace. it then recursively call itself to test each of those namespaces. That way you get the whole tree.

If you’re searching for a given class I recommend that you start at the root class to ensure that you test everywhere.

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: