clamp
clamp

Reputation: 34036

WMI: Querying a specific instance of a class

I want to make changes to the config of Microsoft Windows UWF Filter (uwfmgr.exe) via WMI in C#. Now certain changes can only be done to a specific instance of the WMI class due to their nature. For example:

    var scope = new ManagementScope(@"root\standardcimv2\embedded");
    using (var uwfClass = new ManagementClass(scope.Path.Path, "UWF_Servicing", null))
    {
        var instances = uwfClass.GetInstances();
        foreach (var instance in instances)
        {
            Console.WriteLine(instance.ToString());
        }
    }

This code prints:

\\COMPUTER\root\standardcimv2\embedded:UWF_Servicing.CurrentSession=true
\\COMPUTER\root\standardcimv2\embedded:UWF_Servicing.CurrentSession=false

The changes can only be done to the instance where CurrentSession = false.

How can I get this instance in a clean way?

In other words, I dont want to do:

instance.ToString().Contains("CurrentSession=false")

I believe there is a "nicer" way to do this. Thanks in advance!

Upvotes: 0

Views: 1017

Answers (1)

Simon Mourier
Simon Mourier

Reputation: 139065

You can use SQL for WMI WHERE clause queries, something like this:

var searcher = new ManagementObjectSearcher(
                   @"ROOT\StandardCimv2\embedded",
                   @"SELECT * FROM UWF_Servicing WHERE CurrentSession = FALSE");
foreach (ManagementObject obj in searcher.Get())
{
    ... etc ...
}

But you can also use the object's properties (values types will map to standard .NET's types), like this:

var searcher = new ManagementObjectSearcher(
                   @"ROOT\StandardCimv2\embedded",
                   @"SELECT * FROM UWF_Servicing");
foreach (ManagementObject obj in searcher.Get())
{
    var currentSession = obj.GetPropertyValue("CurrentSession");
    if (false.Equals(currentSession))
    {
        ... etc ...
    }
}

Upvotes: 1

Related Questions