Question

i'm writing code to terminate specific processes after a specified amount of time. i'm using the below code (simplified for post):

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

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

the problem -- using a WQL statement of SELECT Name, CreationDate throws an exception when trying to do the terminate:

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

...but, using SELECT * works and terminates the process. why is this -- is there a specific WMI column that's needed in the resultset?

thanks!

Was it helpful?

Solution

When you executes a WMI method, the WMI internally searh for the WMI Object path to identify the instance over the method will be executed.

In this case for the Win32_Process WMI class the WMI Object Path looks like Win32_Process.Handle="8112", So as you see the Handle property is part of the WMi Object path and must be included in your WQL sentece,

Check this sample.

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();
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top