You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

查询Windows Defender实时防护状态时遇无效查询ManagementException错误

解决WMI查询Windows Defender实时防护状态的无效查询错误

你的问题出在两个核心错误上:

  • WMI查询构造错误:你错误地将WMI命名空间Root\Microsoft\Windows\Defender作为MSFT_MpPreference类的属性,放到了WHERE条件中,但该类并没有Path属性,这直接导致了"Invalid query"异常。
  • 状态判断属性误用:RealTimeScanDirection用于控制流量扫描的方向(入站/出站),并非实时防护的启用状态,正确的属性应为RealTimeProtectionEnabled。

修正后的完整代码:

public static bool GetRealTimeProtectionStatus()
{
    bool enabled = false;
    string wmiNamespace = @"Root\Microsoft\Windows\Defender";
    string className = "MSFT_MpPreference";

    // 正确的构造方式:分别指定命名空间和查询语句,无需WHERE条件
    using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmiNamespace, $"SELECT * FROM {className}"))
    {
        foreach (ManagementObject obj in searcher.Get())
        {
            // 读取实时防护的启用状态属性
            enabled = (bool)obj.GetPropertyValue("RealTimeProtectionEnabled");
            break;
        }
    }

    return enabled;
}

额外提示

  • 权限验证:管理员权限确实是必要的,但如果仍有问题,可检查系统是否禁用了Defender的WMI访问权限。
  • 异常处理:建议添加try-catch块捕获ManagementException,比如当系统安装了第三方杀毒软件、Defender被禁用时,WMI命名空间可能无法访问。
  • 系统兼容性:MSFT_MpPreference仅支持Windows 10及以上版本的Defender,旧系统需使用其他WMI类。

内容的提问来源于stack exchange,提问作者Gehad Fuda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 05:07:18