2015-05-06 122 views
1

我试图在.NET 4.5上用WMI/C#在远程计算机上终止一个进程。在下面的代码中,当在ManagementObjectSearcher实例上调用Get方法时,没有返回任何内容,因此foreach内部的行未被触及。 ManagementScope已连接,并且查询变量包含终止进程的名称。 Thx寻求帮助。ManagementObjectSearcher Get()方法不返回结果

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

使用Count属性来检查,是否包含任何记录。即,if(searcher.Get().count == 0)返回true,意味着没有记录存在。

+0

谢谢,Count属性返回0,这表明事实上查询结果为空。我猜在我的代码中,一旦var query = new SelectQuery(...)被击中,查询将针对本地机器执行。在任何情况下,我已经删除了查询变量,将新的SelectQuery(...)声明移到ManagementObjectSearcher构造函数中,并且它正在工作。好极了!谢谢你指点我正确的方向。 – codelady

+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 
     }