通过 WMI 查询时防止 ComExceptions
我有一些代码,使用 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
}
}
VBScript (vbs) 中的这段代码将通过 WMI 执行此操作:初始化 WMI 连接,并对身份验证或连接问题执行错误处理。我想对于两者都了解的人来说,“转录”到 c# 大约需要 30 秒。 :)
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#. :)