Kill only one process with taskkill

余生长醉 提交于 2019-12-24 03:43:48

问题


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?


回答1:


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



回答2:


This assumes you don't care which instance you kill:

@echo off
for /f "tokens=2 delims=," %%T in ('tasklist /nh /fi "imagename eq rundll32.exe" /fo csv') do (
  echo taskkill /F /pid %%~T 
  goto :eof
)

Version above just echoes taskkill command (you may copy paste to execute for testing), remove echo when you're sure it behaves as it should.



来源:https://stackoverflow.com/questions/13196731/kill-only-one-process-with-taskkill

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!