Batch file to search for and optionally kill tasks

Name: tk.bat
Usage: tk name

The batch file will search running tasks for the parameter(s) provided and list any that are found. (If none are found, it will terminate)

After listing any found, it will prompt the user to hit ENTER to continue or CTRL-C to abort. If the user presses ENTER, the batch file will attempt to end the tasks with the PIDs found, and output the status as it tries.

@echo off
REM Check if a search term was provided
if "%1"=="" (
    echo Please provide a task name to search and kill.
    exit /b 1
)

REM Initialize a flag to check if any tasks are found
set found=0

REM Display the list of tasks matching the search term
echo Searching for tasks matching "%*":
for /f "delims=" %%i in ('tasklist ^| findstr /i "%*"') do (
    set found=1
    echo %%i
)

REM Check if any tasks were found
if "%found%"=="0" (
    echo No matching tasks found, exiting...
    exit /b 1
)

REM Prompt the user to press ENTER to continue or CTRL+C to abort
echo.
echo Press ENTER to continue or CTRL+C to abort.
pause

REM Get the list of tasks matching the search term and kill them
for /f "tokens=2 delims= " %%i in ('tasklist ^| findstr /i "%*"') do (
    echo Killing task %%i
    taskkill /f /pid %%i
)

Here’s my tk2.bat, which can be run without parameters (optionally with), so you can save this and just double-click to run it:

@echo off
REM Check if a search term was provided, prompt if not
if "%1"=="" (
    set /p searchTerm=Please provide a task name to search and kill:
) else (
    set searchTerm=%*
)

REM Initialize a flag to check if any tasks are found
set found=0

REM Display the list of tasks matching the search term
echo Searching for tasks matching "%searchTerm%":
for /f "delims=" %%i in ('tasklist ^| findstr /i "%searchTerm%"') do (
    set found=1
    echo %%i
)

REM Check if any tasks were found
if "%found%"=="0" (
    echo No matching tasks found, exiting...
    echo.
    echo Press ENTER to continue...
    pause
    exit /b 1
)

REM Prompt the user to press ENTER to continue or CTRL+C to abort
echo.
echo Press ENTER to continue or CTRL+C to abort.
pause

REM Get the list of tasks matching the search term and kill them
for /f "tokens=2 delims= " %%i in ('tasklist ^| findstr /i "%searchTerm%"') do (
    echo Killing task %%i
    taskkill /f /pid %%i
)

echo.
echo Process complete. Press ENTER to exit...
pause