【问题标题】:terminating process requires WQL "SELECT *..."?终止进程需要 WQL "SELECT *..."?
【发布时间】:2012-04-03 22:13:04
【问题描述】:

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

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 列?

谢谢!

【问题讨论】:

    标签: c# .net wmi wql


    【解决方案1】:

    当您执行 WMI 方法时,将执行 WMI 内部搜索 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();
            }
        }
    }
    

    【讨论】:

    • 你是说“SELECT Handle, Name, CreationDate”是需要的吗?
    • 我刚刚测试过——是的,只需将 Handle 添加到 WQL 即可启用终止。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多