2

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
  }
}
Joe Zack
  • 3,268
  • 2
  • 31
  • 37
  • 1
    This can't be the real reason. Network time-outs take a *lot* longer than processing an exception. You can't work around the time-out. – Hans Passant Jul 13 '11 at 21:38
  • I'm not worried about time. I'm worried about the cpu cycles and memory overhead of throwing thousands of exceptions in a relatively short amount of time. My 'real' code runs asynchronously, and throws about 150 exceptions per minute in one of my tests. – Joe Zack Jul 14 '11 at 17:50

1 Answers1

0

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
Lizz
  • 1,442
  • 5
  • 25
  • 51