check if WMI namespace exists from c#

依然范特西╮ 提交于 2020-01-03 04:17:07

问题


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();
        }
    }
}


来源:https://stackoverflow.com/questions/5871217/check-if-wmi-namespace-exists-from-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!