我试图在.NET 4.5上使用WMI / C#终止远程计算机上的进程。在下面的代码中,当在ManagementObjectSearcher实例上调用Get方法时,不会返回任何内容,因此未到达foreach中的行。 ManagementScope已连接,查询变量包含终止进程的名称。 感谢任何帮助。
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
}
答案 0 :(得分:1)
正如我在上面的评论中所述,为了完整性,这里的代码包含我的更改,如下所示。
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
}
答案 1 :(得分:0)
使用Count
属性检查是否包含任何记录。也就是说,if(searcher.Get().count == 0)
返回true
,表示没有记录。
答案 2 :(得分:0)
就我而言,我无法使用WMI查询远程接收CPU利用率值:
SELECT PercentProcessorTime FROM Win32_PerfFormattedData_PerfOS_Processor WHERE Name='_Total'
我将项目构建平台的目标从任何CPU 更改为 x64 ,以匹配我的系统位数,从而解决了问题。另一种方法是,取消选中任何CPU 的首选32位复选框。