Finding a CIM class

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.

Advertisements
This entry was posted in PowerShell and CIM, PowerShell and WMI. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s