Counting things in WMI

So, say you’re trying to get a count of the number of SMS_Package objects in the SCCM WMI interface, perhaps matching some parameter. You can easily do this using WQL and the SELECT COUNT(*) function, e.g.:


This can be executed on a WqlConnectionManager object’s QueryProcessor, via the ExecuteQuery method. The return from these is always an IResultObject (which is weird kind of object which can be both one or many objects at once – it wraps up other objects and presents a standard interface to permit you to enumerate them without being aware of their type, kind of like PSObject).

As detailed here in MSDN results from queries involving such WQL statements as COUNT come wrapped up in a __Generic class. This means in practice that the Count property (which contains the output of the COUNT(*)) is attached to the IResultObject’s first child.

So overall you get this:

    IResultObject packageWithName = Connection.QueryProcessor.ExecuteQuery(String.Format("SELECT COUNT(*) FROM SMS_Package WHERE Name='{0}'", PackageName));

int count = 0;

foreach (IResultObject collection in packageWithName)
count = collection["Count"].IntegerValue;

this.WriteDebug(String.Format("Count of existing packages is: {0}", count));

(This is code from inside a PSCmdlet derived class in case you’re wondering what this refers to).

The utility of this, of course, is to ensure that you don’t add more than one package with the same name since it should be unique. It’s slightly inelegant accessing the child by using foreach, but I haven’t worked out a better way to do it (documentation for IResultObject isn’t particularly great).