How can you run a batch file which taskkills all other cmd.exes which are currently running, except for the one that is doing the task kill command?
Asked
Active
Viewed 3,057 times
4
-
There might be something in the sysinternals toolkit – Nicholas Albion Aug 19 '12 at 04:15
3 Answers
4
Combining these 2 threads:
- how to get PID from command line filtered by username and imagename
- how to get own process pid from the command prompt in windows
you can write down something like this in a simple cmd file (akillfile.cmd
)
title=dontkillme
FOR /F "tokens=2 delims= " %%A IN ('TASKLIST /FI ^"WINDOWTITLE eq dontkillme^" /NH') DO SET tid=%%A
echo %tid%
taskkill /F /IM cmd.exe /FI ^"PID ne %tid%^"
1
copy cmd.exe, rename it to a.exe, then use this command in a batch file: start a.exe /k taskkill /f /im cmd.exe

Michael Roller
- 375
- 2
- 4
- 9
0
This worked for me, added to the very beginning of the .bat which is to kill all previously launched instances of itself, then immediately make itself susceptible to be killed by subsequent calls of the same .bat file:
title NewlyLaunchedThing
taskkill /F /IM cmd.exe /FI "WINDOWTITLE ne NewlyLaunchedThing"
title Thing
...do everything else
Note that, apparently, the "title" is a keyword, which sets a variable named "WINDOWTITLE".
Also, the "=" (equals sign) is apparently optional for assigning title/WINDOWTITLE. Meaning, this works as well, and may be preferred for clarity:
title = newTitle

Mike_K
- 1
- 2