c#
  • .net
  • wmi
  • wql
  • 2012-04-03 74 views 0 likes 
    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內部搜索WMI Object path以標識將在該方法上執行的實例。

    在這種情況下爲Win32_Process WMI類的WMI對象路徑看起來像Win32_Process.Handle="8112",所以當你看到Handle屬性是WMI對象路徑的一部分,必須包含在您的WQL sentece,

    檢查該樣本。

    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 2012-04-04 22:38:05

    +0

    我剛剛測試過 - 是的,只需將句柄添加到WQL中即可終止。謝謝! – mdelvecchio 2012-04-04 22:47:07

    相關問題