我正在尝试使用 system.management
中的 WMI 查询本地计算机以获取有关 Windows 安全中不同服务状态的信息,例如 Windows Defender 和防火墙。出于测试目的,我在控制台项目中工作,我只是尝试访问 MSFT_MpComputerStatus
和 AMServiceEnabled
等属性,但无论我做什么,尝试时都会抛出异常通过集合 foreach。
我是 WMI 的新手,所以它可能只是我错过的东西,但我已经尝试让它工作几天了。通过搜索,我发现了几个不同的代码示例,展示了如何访问属性类,例如: ( For finding everything in a class )
( For accessing properties on a specific ManagementObject instance )
( Using the WMI code creator tool was suggested here )
我使用命名空间尝试了所有这些:root\\Microsoft\\Windows\\Defender
和类:MSFT_MpComputerStatus
但没有任何效果。
下面是该工具编写的代码,即使这样在我的控制台应用程序和工具本身中都失败了。
try
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\Microsoft\\Windows\\Defender",
"SELECT * FROM MSFT_MpComputerStatus");
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("MSFT_MpComputerStatus instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("AMServiceEnabled: {0}", queryObj["AMServiceEnabled"]);
Console.WriteLine("AntispywareEnabled: {0}", queryObj["AntispywareEnabled"]);
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
这应该返回一些 bool 值,指示服务是打开还是关闭,但是一旦它到达 foreach 循环,就会抛出此异常“System.Management.ManagementException:此方法未在任何类中实现”。 我在这里错过了什么吗?有没有其他方法可以使用 WMI 获取我需要的信息?
编辑:
经过更多搜索后,我还发现 MSFT_MpComputerStatus
也存在于 root\\Microsoft\\protectionManagement
中,但使用此命名空间会产生相同的结果。
编辑 2: 是设置问题。在 3 台公司开发电脑和一台非开发电脑上测试了上述代码,代码在非开发电脑上运行良好。如果我发现罪魁祸首是什么,我会将其张贴在这里。
编辑 3: 我们的反病毒系统 (bitdefender) 才是问题的根源。努力寻找解决方法(如果有)。
编辑 4: 请参阅我自己的答案。
最佳答案
当 windows defender 被完全禁用时(大多数 AV 软件在安装时似乎都会这样做)对该类的访问将丢失,但它仍然可见。要获取 Windows 安全状态,通常必须使用其他方法,例如 SecurityCenter2 命名空间(未正式支持)、wscapi (c++) 或通过一些 powershell 命令。
关于c# - 无法通过 ManagementObjectCollection 进行 foreach,引发 "This method is not implemented in any class"异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55379380/