title: How to get PID of a process running in Windows using Java
body: <p>I have used OSHI libraries available, but the getProcessID function is not working. I need to find the PID of a process entered by the user.</p>
  <p>I have now used this code</p>
  <pre class="lang-java prettyprint-override"><code>public static String getProcessPID(String processName, boolean... ignoreLetterCase) {
      String pid = &quot;&quot;;
      boolean ignoreCase = true;
      if (ignoreLetterCase.length &gt; 0) {
          ignoreCase = ignoreLetterCase[0];
      }
  
      // Acquire the Task List from Windows
      ProcessBuilder processBuilder = new ProcessBuilder(&quot;tasklist.exe&quot;);
      Process process;
      try {
          process = processBuilder.start();
      }
      catch (java.io.IOException ex) {
          return &quot;&quot;;
      }
      // Read the list and grab the desired PID
      String tasksList;
      try (Scanner scanner = new Scanner(process.getInputStream(), &quot;UTF-8&quot;).useDelimiter(&quot;\\A&quot;)) {
          int counter = 0;
          String strg = &quot;&quot;;
          while (scanner.hasNextLine()) {
              strg = scanner.nextLine();
  
              // Uncomment the line below to print the current Tasks List to Console Window.
              // System.out.println(strg);
  
              if (!strg.isEmpty()) {
                  counter++;
                  if (counter &gt; 2) {
                      if (ignoreCase) {
                          if (strg.toLowerCase().contains(processName.toLowerCase())) {
                              String[] tmpSplit = strg.split(&quot;\\s+&quot;);
                              pid += (pid.isEmpty()) ? tmpSplit[1] : &quot;, &quot; + tmpSplit[1];
                          }
                      }
                      else {
                          if (strg.contains(processName)) {
                              String[] tmpSplit = strg.split(&quot;\\s+&quot;);
                              pid += (pid.isEmpty()) ? tmpSplit[1] : &quot;, &quot; + tmpSplit[1];
                          }
                      }
                  }
              }
          }
      }
      return pid;
  }
  </code></pre>
  <p>This fails for processes with multiple instances running such as Chrome. So, how do I get Parent ProcessID or a process with a space in between the name?</p>