C# ManagementObjectSearcher Get()方法不返回任何结果
我正在尝试使用.NET 4.5上的WMI/C#终止远程计算机上的进程。在下面的代码中,当对ManagementObjectSearcher实例调用Get方法时,不会返回任何内容,因此不会到达foreach中的行。ManagementScope已连接,查询变量包含要终止的流程的名称。 谢谢你的帮助C# ManagementObjectSearcher Get()方法不返回任何结果,c#,.net,wmi,C#,.net,Wmi,我正在尝试使用.NET 4.5上的WMI/C#终止远程计算机上的进程。在下面的代码中,当对ManagementObjectSearcher实例调用Get方法时,不会返回任何内容,因此不会到达foreach中的行。ManagementScope已连接,查询变量包含要终止的流程的名称。 谢谢你的帮助 try { ConnectionOptions connOptions = new ConnectionOptions(); connOp
try
{
ConnectionOptions connOptions = new ConnectionOptions();
connOptions.Impersonation = ImpersonationLevel.Impersonate;
connOptions.EnablePrivileges = true;
ManagementScope manScope = new ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", NetworkName), connOptions);
manScope.Connect();
var query = new SelectQuery("select * from Win32_process where name = '" + ProcessName + "'");
using (var searcher = new ManagementObjectSearcher(manScope, query))
{
foreach (ManagementObject process in searcher.Get())
{
process.InvokeMethod("Terminate", null);
}
}
}
catch (ManagementException err)
{
//Do something with error message here
}
使用
Count
属性检查它是否包含任何记录。也就是说,if(searcher.Get().count==0)
返回true
,表示不存在任何记录。如我在上面的评论中所述,为完整起见,下面是我所做更改的代码
try
{
ConnectionOptions connOptions = new ConnectionOptions();
connOptions.Impersonation = ImpersonationLevel.Impersonate;
connOptions.EnablePrivileges = true;
ManagementScope manScope = new ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", NetworkName), connOptions);
manScope.Connect();
ProcessName = ProcessName + ".exe";
using (var searcher = new ManagementObjectSearcher(manScope, new SelectQuery("select * from Win32_Process where Name = '" + ProcessName + "'")))
{
foreach (ManagementObject process in searcher.Get())
{
process.InvokeMethod("Terminate", null);
}
}
}
catch (ManagementException err)
{
//Do something with error message here
}
在我的情况下,我无法使用WMI查询远程接收CPU利用率值:
SELECT PercentProcessorTime FROM Win32_PerfFormattedData_PerfOS_Processor WHERE Name='_Total'
我将项目构建平台目标从任何CPU更改为x64,以匹配我的系统位,问题得到了解决。另一种方法是在选择了任何CPU时取消选中首选32位复选框。谢谢,Count属性返回0,这表明事实上查询结果为空。我猜在我的代码中,只要点击var query=new SelectQuery(…),查询就会针对本地机器执行。在任何情况下,我都删除了查询变量,将新的SelectQuery(…)声明移动到ManagementObjectSearcher构造函数中,它就开始工作了。耶!谢谢你给我指明了正确的方向。欢迎:)很高兴……我帮了你……)