Kill all processes with taskkill by username but exclude some processes

batchcmd.exewindows

I want to kill all processes with taskkill by username, with this command:

taskkill /f /fi "USERNAME eq %username%"

The problem is that I want to exclude (skip) some processes (not kill them all), such as explorer.exe, taskmgr.exe, cmd.exe, and of course current CMD instance

How can i exclude this processes with taskkill?

thanks

Best Answer

Windows Native Batch Script CMD Method

Below is a batch script solution that uses Tasklist and FOR /F loops setting and parsing variables accordingly to get just the process names of the processes running of a specific user.

With Findstr these results are then parsed further to exclude any specified exclusions you set in the Exclusions variable up top.

It'll take the final remaining results and kill those process names for that specific username giving you the desired results via a batch script just as explained.

Batch Script

There are only two variables to set for this to work which are the Username and the Exclusions, and the rest will just work and do the rest of the process as you need. Just specific the full process names separated by a space one next to the other just as in the below script.

@ECHO ON
SET Username=user
SET Exclusions=explorer.exe taskmgr.exe cmd.exe 

SET tmpfl=%temp%\%~n0tmp.dat
IF EXIST "%tmpfl%" DEL /F /Q "%tmpfl%"
SET Exclusions=%Exclusions% taskkill.exe 

SETLOCAL ENABLEDELAYEDEXPANSION
FOR /F "DELIMS=: TOKENS=2" %%A IN ('TASKLIST /FI "USERNAME EQ %Username%" /FO LIST ^| FIND /I "Image name:"') DO (
    SET var=%%~A
    SET var=!var: =!
    ECHO !var! | FINDSTR /I /V "%Exclusions%">>"%tmpfl%"
)
FOR /F "USEBACKQ TOKENS=*" %%A IN ("%tmpfl%") DO (
    TASKKILL /F /FI "USERNAME eq %Username%" /IM %%~A
)
GOTO :EOF

Batch Script 2

@ECHO ON
CD /D "%~DP0"
SET Exclusions=cmd.exe explorer.exe taskmgr.exe 

SET tmpfl=%~n0tmp.dat
IF EXIST "%tmpfl%" DEL /F /Q "%tmpfl%"
SET Exclusions=%Exclusions% taskkill.exe 

SETLOCAL ENABLEDELAYEDEXPANSION
FOR /F "DELIMS=: TOKENS=2" %%A IN ('TASKLIST /FI "USERNAME EQ %Username%" /FO LIST ^| FIND /I "Image name:"') DO (
    SET var=%%~A
    SET var=!var: =!
    ECHO !var! | FINDSTR /I /V "%Exclusions%">>"%tmpfl%"
)
FOR /F "USEBACKQ TOKENS=*" %%A IN ("%tmpfl%") DO (
    TASKKILL /F /FI "USERNAME eq %Username%" /IM %%~A
)
DEL /F /Q "%tmpfl%"
GOTO :EOF

Further Resources

Related Question