2012-04-03 9 views
0

私は特定の時間が経過した後に特定のプロセスを終了するコードを書いています。終了やろうとしたときにSELECT Name, CreationDateのWQLステートメントを使用して例外がスローされます -プロセスを終了するにはWQL "SELECT * ..."が必要ですか?

ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT Name, CreationDate FROM Win32_Process WHERE Name = 'foo'"); 

foreach (ManagementObject process in searcher.Get()) 
{ 
    process.InvokeMethod("Terminate", null); 
} 

問題は:

"Operation is not valid due to the current state of the object." 

を...私は(ポストのために簡略化)以下のコードを使用していますしかし、SELECT *を使用すると、処理が終了します。なぜですか?結果セットに必要な特定のWMI列がありますか?

ありがとうございました!

答えて

4

WMIメソッドを実行すると、WMI Object pathがそのメソッドでインスタンスを識別するWMI内部検索が実行されます。あなたはHandleプロパティは、WMIオブジェクトパスの一部であり、あなたのWQLのsenteceに含まれている必要があります参照ようWin32_Process WMIクラスのWMIオブジェクトパスは、Win32_Process.Handle="8112"ようになります。この場合

このサンプルをチェック。

using System; 
using System.Collections.Generic; 
using System.Management; 
using System.Text; 
//this will all the notepad running instances 

namespace GetWMI_Info 
{ 
    class Program 
    { 

     static void Main(string[] args) 
     { 
      try 
      { 
       string ComputerName = "localhost"; 
       ManagementScope Scope;     

       if (!ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase)) 
       { 
        ConnectionOptions Conn = new ConnectionOptions(); 
        Conn.Username = ""; 
        Conn.Password = ""; 
        Conn.Authority = "ntlmdomain:DOMAIN"; 
        Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), Conn); 
       } 
       else 
        Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null); 

       Scope.Connect(); 
       ObjectQuery Query = new ObjectQuery("SELECT Handle FROM Win32_Process Where Name='notepad.exe'"); 
       ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query); 

       foreach (ManagementObject WmiObject in Searcher.Get()) 
       { 
        WmiObject.InvokeMethod("Terminate", null); 

       } 
      } 
      catch (Exception e) 
      { 
       Console.WriteLine(String.Format("Exception {0} Trace {1}",e.Message,e.StackTrace)); 
      } 
      Console.WriteLine("Press Enter to exit"); 
      Console.Read(); 
     } 
    } 
} 
+0

「SELECT Handle、Name、CreationDate」は必要なものですか? – mdelvecchio

+0

私はちょうどテストしました - はい、WQLにハンドルを追加するだけで終了が可能です。ありがとう! – mdelvecchio

関連する問題