Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# WMI Process Differentiation?

Tags:

c#

wmi

Scenario

I have a method that returns a list of processes using WMI. If I have 3 processes running (all of which are C# applications) - and they all have THE SAME PROCESS NAME but different command line arguments, how can I differentiate between them If I want to start them or terminate them!?

Thoughts

As far as I can see, I physically cannot differentiate between them, at least not without having to use the Handle, but that doesn't tell me which one of them got terminated because the others will still sit there with the same name........

....really stumped, help greatly appreciated!

like image 728
Goober Avatar asked Oct 25 '22 17:10

Goober


2 Answers

Create the process using a technique that gives you the process ID as an out parameter. E.g.

  • WMI: Win32_Process.Create method returns [out] uint32 ProcessId
  • .NET: Process.Start method returns a Process object with a Process.Id property

Then you can use that value to truly know which version of the process you want to kill later. E.g.

  • WMI: Get Win32_Process instance matching ProcessId, call Terminate()
  • .NET: Get Process instance using GetProcessById, call Kill and then WaitForExit

(Note that if the process stops before you kill it, the OS can assign that same process ID to a new process, so of course you'll want to double check that you're killing the right one, e.g. check the process name too)

like image 179
Daryn Avatar answered Nov 12 '22 23:11

Daryn


The WMI Win32_ProcessObject has a CommandLine property you could use if that is what you know differentiates the instances.

string query = “Select * From Win32_Process Where Name = “ + processName;
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection processList = searcher.Get();

foreach (ManagementObject obj in processList)
{
     string cmdLine = obj.GetPropertyValue("CommandLine").ToString();

     if (cmdLine == "target command line options")
     {
          // do work
     }
}
like image 44
Mike Marshall Avatar answered Nov 12 '22 23:11

Mike Marshall