2015-05-06 157 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 
     }