通过 WMI 查询时防止 ComExceptions

发布于 11-19 19:28 字数 530 浏览 1 评论 0原文

我有一些代码,使用 WMI 在 Windows 域中搜索符合特定条件的计算机。

如果我无法与我尝试查询的计算机通信,我会收到 COMException。在大型域上进行测试时,这可能会导致抛出数千个异常,这在性能方面非常昂贵。

有没有办法让我在查询之前检查有效连接,以便防止这些错误发生?

简化示例:

foreach(var computer in domain) {
  var scope = new ManagementScope(computerPath, options), query);
  try {
    using (var searcher = new ManagementObjectSearcher(scope)) {

      if (searcher.Get().Count == 0) {
        // do stuff
      }

    }
  } catch(ComException e) {
    // Log and continue
  }
}

I've got some code that uses WMI to scour a windows domain for computers matching certain criteria.

I get a COMException If I'm unable to communicate with the computer I'm trying to query. When testing on a large domain, this can result in thousands of exceptions being thrown, which is very expensive performance-wise.

Is there a way for me to check for a valid connection, BEFORE querying, so that I can prevent these errors from happening?

Simplified Example:

foreach(var computer in domain) {
  var scope = new ManagementScope(computerPath, options), query);
  try {
    using (var searcher = new ManagementObjectSearcher(scope)) {

      if (searcher.Get().Count == 0) {
        // do stuff
      }

    }
  } catch(ComException e) {
    // Log and continue
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

雅心素梦2024-11-26 19:28:15

VBScript (vbs) 中的这段代码将通过 WMI 执行此操作:初始化 WMI 连接,并对身份验证或连接问题执行错误处理。我想对于两者都了解的人来说,“转录”到 c# 大约需要 30 秒。 :)

' Verify Computer exists and account used has sufficient rights
Set objSWbemServices = GetObject( "winmgmts:\\" & strComputer & "\root\cimv2" )
If( IsEmpty( objSWbemServices ) = True ) Then
   WScript.Echo( "OBJECT_NOT_INITIALIZED :: " & strComputer )
   WScript.Quit( OBJECT_NOT_INITIALIZED )
End If

This bit of code in VBScript (vbs) will do just that via WMI: initialize the WMI connection, and perform error handling for authentication or connection issues. I imagine it would take about 30 seconds for someone who knows both to "transcribe" to c#. :)

' Verify Computer exists and account used has sufficient rights
Set objSWbemServices = GetObject( "winmgmts:\\" & strComputer & "\root\cimv2" )
If( IsEmpty( objSWbemServices ) = True ) Then
   WScript.Echo( "OBJECT_NOT_INITIALIZED :: " & strComputer )
   WScript.Quit( OBJECT_NOT_INITIALIZED )
End If
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文