0

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

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

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

问题 - 尝试执行终止时使用 WQL 语句SELECT Name, CreationDate引发异常:

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

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

谢谢!

4

1 回答 1

5

当您执行 WMI 方法时,将执行 WMI 内部搜索WMI 对象路径以识别该方法上的实例。

在这种情况下,对于Win32_ProcessWMI 类,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();
        }
    }
}
于 2012-04-03T23:04:52.323 回答