check if WMI namespace exists from c#

2019-06-07 06:33发布

问题:

I want to check if a certain feature is installed on a certain machine. I have a powershell code that checks this, and now I want to check this from .net code. I can see that in the cmdlet, the code checks if there is an invalid namespace error.

When searching the web, I found the following code:

ManagementClass myClass = new ManagementClass(scope, path, getOptions);

try
{
    myClass.get();
}
catch (System.Management.Exception ex)
{
    if (ex.ErrorCode == ManagementStatus.InvalidNamespace)
    {
         return true;
    }
}
 ...   

I want to clean this code a bit, so basically I have 2 questions:

  1. Is there another way to check for an InvalidNamespace error? (The code I've copied was later used to invoke some method within myClass, so I wonder if I can somehow achieve my goal in a more direct way)

  2. Do I really need the parameter getOptions?

回答1:

To get all the wmi namespaces, you must first connect to the root namespace and then query for all the __NAMESPACE instances, and for each instance recursively repeat this process. about the getOptions parameter which is a ObjectGetOptions class is not necessary in this case, so can be null.

Check this code to get all the wmi namespaces (you can populate a list with that info and then check if the namespace exist in the machine)

using System;
using System.Collections.Generic;
using System.Text;
using System.Management;

namespace MyConsoleApplication
{
    class Program
    {
        static private void GetWmiNameSpaces(string root)
        {
            try
            {
                ManagementClass nsClass = new ManagementClass( new ManagementScope(root), new ManagementPath("__namespace"), null);
                foreach (ManagementObject ns in nsClass.GetInstances())
                {
                    string namespaceName = root + "\\" + ns["Name"].ToString();
                    Console.WriteLine(namespaceName);
                    //call the funcion recursively                               
                    GetWmiNameSpaces(namespaceName);
                }
            }
            catch (ManagementException e)
            {
                Console.WriteLine(e.Message);
            }
        }


        static void Main(string[] args)
        {
            //set the initial root to search
            GetWmiNameSpaces("root");
            Console.ReadKey();
        }
    }
}


标签: c# wmi