I've got some code that uses WMI to scour a windows domain for comput开发者_如何学运维ers 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
}
}
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
精彩评论