终止过程需要WQL“SELECT * ...”?

时间:2012-04-03 22:13:05

标签: c# .net wmi wql

我正在编写代码以在指定的时间后终止特定进程。我正在使用以下代码(简化为帖子):

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

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

问题 - 使用SELECT Name, CreationDate的WQL语句在尝试终止时抛出异常:

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

...但是,使用SELECT *可以工作并终止该过程。为什么 - 结果集中是否需要特定的WMI列?

谢谢!

1 个答案:

答案 0 :(得分:4)

当您执行WMI方法时,将执行W WMI Object path内部搜索以识别方法上的实例。

在这种情况下,对于Win32_Process WMI类,WMI对象路径看起来像Win32_Process.Handle="8112",因此您看到Handle属性是WMi对象路径的一部分,并且必须包含在你的WQL表达,

检查此样本。

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();
        }
    }
}