首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >终止进程需要WQL "SELECT *...“吗?

终止进程需要WQL "SELECT *...“吗?
EN

Stack Overflow用户
提问于 2012-04-04 06:13:05
回答 1查看 1.7K关注 0票数 0

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

代码语言:javascript
复制
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语句会抛出异常:

代码语言:javascript
复制
"Operation is not valid due to the current state of the object."

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

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-04-04 07:04:52

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

在本例中,对于WQL类,Win32_Process对象路径类似于Win32_Process.Handle="8112",因此正如您所看到的,Handle属性是WQL对象路径的一部分,并且必须包含在您的WQL语句中,

请检查此示例。

代码语言:javascript
复制
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();
        }
    }
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10002207

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档