title: Getting ProcessId with CommandLine
body: <p>I already searched here for an answer but I couldn't find any working code snippets or tips.</p>
  
  <p>How do I get ProcessIds with a given CommandLine? I already got CommandLine by Pid with this method:</p>
  
  <pre><code>private IEnumerable&lt;string&gt; GetCommandLine(Process process)
  {
      using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId = " + process.Id))
      using (ManagementObjectCollection objects = searcher.Get())
      {
          foreach (var element in objects)
              yield return element["CommandLine"]?.ToString();
      }
  }
  </code></pre>
  
  <p>This works for getting CommandLine with given ProcessId.
  But I want the ProcessId with given CommandLine.
  I started a process which would have this CommandLine I'm searching for.
  This is my attempt:</p>
  
  <pre><code>private IEnumerable&lt;int&gt; GetIdsByCommandLine(string commandLine)
  {
      using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT ProcessID FROM Win32_Process WHERE CommandLine = " + commandLine))
      using (ManagementObjectCollection objects = searcher.Get())
      {
          foreach (var element in objects)                
              yield return (int) element["ProcessId"];                
      }
  }
  </code></pre>
  
  <p>But if I run this, it stops at beginning of the foreach-loop: "Query invalid"
  Can anybody help me with such a query to get ProcessId by CommandLine?
  Thanks in advance!</p>
  
  <p>Edit:
  I need this for a process watchdog. I have 4 programs which are started with arguments. But there shouldn't be any instance of those programs before they start. So my attempt is to start each, getting the CommandLine (GetCommandLine above) of the process, killing the process, and then I want to search for processes with the same CommandLine to kill them. Only when this is done, I can start my 4 programs without them freaking around. That's why I need exactly a way to extract processIds by CommandLine.</p>