Search code examples
c#wmiwmi-queryget-wmiobject

WMI query too slow


I need get Office is Activated or need activation and i use normal query in WMI:

 ManagementObjectSearcher searcher =
                        new ManagementObjectSearcher("root\\CIMV2",
                        "SELECT * FROM " + wmi + " WHERE Name LIKE \"%Office%\" ");

                    foreach (ManagementObject queryObj in searcher.Get())
                    { 
                        queryObj["Name"].ToString() + "', '" + queryObj["LicenseStatus"].ToString();                           

But this query sometimes require 45/50 seconds, now I have to understand how to replace it or speed it up, becasue if i use this command from CMD

WMIC /NAMESPACE:\\root\CIMV2 PATH SoftwareLicensingProduct WHERE LicenseStatus=1 GET Name

It respond in 2 seconds! But i can't integrate CMD in C# only if run external command and from CMD i don't have full query access

This query work:

WMIC /NAMESPACE:\\root\CIMV2 PATH SoftwareLicensingProduct WHERE "name like '%Office%'" Get Name

Now add LicenseStatus=1

WMIC /NAMESPACE:\\root\CIMV2 PATH SoftwareLicensingProduct WHERE "name like '%Office%'" and LicenseStatus=1 Get Name

And query not work, why?


Solution

  • Based on the WMIC query you gave, you are only pulling the "Name" property which is whats increasing your performance so that your query only runs for 2 seconds.

    So this...

    WMIC /NAMESPACE:\\root\CIMV2 PATH SoftwareLicensingProduct WHERE LicenseStatus=1 GET Name
    

    Would translate to this query in your code...

    SELECT Name FROM SoftwareLicensingProduct WHERE LicenseStatus=1
    

    Your other example is correct but you just need to move your second quotes over

    WMIC /NAMESPACE:\\root\CIMV2 PATH SoftwareLicensingProduct WHERE "name like '%Office%' and LicenseStatus=1" Get Name
    

    Which, in your code, would look like this (I added LicenseStatus to the query as well since you reference that property in your routine)

    ManagementObjectSearcher searcher =
                            new ManagementObjectSearcher("root\\CIMV2",
                            "SELECT Name, LicenseStatus FROM " + wmi + " WHERE Name LIKE \"%Office%\" and LicenseStatus=1");
    
                        foreach (ManagementObject queryObj in searcher.Get())
                        { 
                            queryObj["Name"].ToString() + "', '" + queryObj["LicenseStatus"].ToString();
    

    That should run fairly quick since its only getting the two properties you are using.