我想检查某台机器上是否安装了某个功能。
我有一个 powershell 代码来检查这一点,现在我想从 .net 代码中检查这一点。
我可以看到在 cmdlet 中,代码检查是否存在无效命名空间
错误。
在网上搜索时,我发现了以下代码:
ManagementClass myClass = new ManagementClass(scope, path, getOptions);
try
{
myClass.get();
}
catch (System.Management.Exception ex)
{
if (ex.ErrorCode == ManagementStatus.InvalidNamespace)
{
return true;
}
}
...
我想稍微清理一下这段代码,所以基本上我有两个问题:
还有其他方法可以检查
InvalidNamespace
错误吗? (我复制的代码后来被用来调用myClass
中的某些方法,所以我想知道是否可以以更直接的方式实现我的目标)我真的需要参数
getOptions
吗?
最佳答案
要获取所有 wmi 命名空间,您必须首先连接到根命名空间,然后查询所有 __NAMESPACE 实例,并对每个实例递归地重复此过程。关于 getOptions 参数,它是 ObjectGetOptions
在这种情况下,类不是必需的,因此可以为 null。
检查此代码以获取所有 wmi 命名空间(您可以使用该信息填充列表,然后检查计算机中是否存在命名空间)
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# - 检查 C# 中的 WMI 命名空间是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5871217/