Suppose I just started the following programs in the background:
START /B CMD /C tomcat.exe
START /B CMD /C tomcat.exe
START /B CMD /C tomcat.exe
and I want to kill the second one. Because they have the same image name, I can't use taskkill
to kill them using tomcat.exe
or I'll kill more than I want.
What I want is to get the process ID of each when they're kicked off.
My question is: Is there a way to get the process ID of a console program I've just started in the background?
You can use
wmic
to help you get ProcessId:You have to get Pid of each new tomcat instance to be stored in a file (pid1.txt, pid2.txt, ...) so you can kill the one you want.
You could also take a look at: https://stackoverflow.com/a/25622550/4584335
Here's a utility batch function that'll let you spawn a process and have its PID set to a variable. Copypaste this into the bottom of your script, after the final
exit /b
orgoto :EOF
so it can only be executed bycall
. It looks complicated (and truth be told it is perhaps a little more complicated than the current situation requires), but it ought to handle backslashes and quoted arguments if you should ever need to recycle it for future projects.If you
wmic process call create "ping localhost"
from a console, you'll see how this works. Unlikestart /b
, usingwmic process call create
to run a new asynchronous process will output the PID of the process as it's started.Call the function above like this: