Kill only one process with taskkill

Ciri picture Ciri · Nov 2, 2012 · Viewed 11.4k times · Source

For the purpose of running a game I need to start its exe twice and then kill one of the rundll32.exe processes. I don't want to do this by hand every time so I put it in a batch file like so:

start Gothic2.exe
start Gothic2.exe
taskkill /IM rundll32.exe /F

There are 2 instances of rundll32.exe running and both are killed, I only need to terminate one of them. PIDs don't help because the rundll32.exe gets a new one every time it is started. How can I kill only one process when there are more with the same name?

Answer

Mark picture Mark · Nov 2, 2012

Assuming that rundll32.exe spins up when you start Gothic2.exe AND that there are no other processes running on your system that would also spin that up AND that it's OK to kill the first instance of rundll32.exe, you could use this:

start Gothic2.exe
for /f "tokens=2" %%x in ('tasklist ^| findstr rundll32.exe') do set PIDTOKILL=%%x
start Gothic2.exe
taskkill /F /PID %PIDTOKILL%

I suppose if you wanted to kill the second instance of rundll32.exe instead, you could modify it like this:

start Gothic2.exe
for /f "tokens=2" %%x in ('tasklist ^| findstr rundll32.exe') do set PIDTOSAVE=%%x
start Gothic2.exe
for /f "tokens=2" %%x in ('tasklist ^| findstr rundll32.exe ^| findstr /v %PIDTOSAVE%') do taskkill /F /PID %%x