Search code examples
windowslistbatch-filefor-looptaskkill

For Loop, List, and TaskKill in Windows Batch Commands


I want to create a list of executables and then create a for loop to taskkill all of the executables in the list. I used this as reference: Create list or arrays in Windows Batch , but I still cannot figure it out.

This is what I tried...

set list = A B C D
for %%a in (%list%) do ( 
taskkill /F %%a
)

Solution

  • Method 1: setting the list from within the batch file:

    @echo off
    setlocal enabledelayedexpansion
    :assuming you want to kill the calc.exe, paint.exe and notepad.exe processes
    set list=calc paint notepad
    for %%a in (!list!) do (
    set process=%%a
    taskkill /f /im !process!.exe
    )
    endlocal
    

    save the above batch file as method1.bat or include it in your batch file somewhere suitable.

    Method 2: have an external list of executables: make a list of the executables you want to terminate, name it list.txt and make sure the list and the batch file are both in the same folder. e.g

    List.txt:

    notepad.exe
    paint.exe
    calc.exe
    

    your batch file:

    @echo off
    ::save this batch file as method2.bat or include in your existing batch file
    setlocal enabledelayedexpansion
    for /f "delims=" %%e in (list.txt) do (
    set process=%%e
    taskkill /f /im !process!
    )
    endlocal
    

    hope that helped!