Search code examples
batch-filewindows-7taskkill

Wildcard in taskkill windowtitle


When I want to close the following two (fictional...) applications using taskkill...

Two hello-sayers

...I would use taskkill /FI "WINDOWTITLE eq Hello*".

But how about these two:

Alcoholic programs

taskkill /FI "WINDOWTITLE eq * wine" gives me FEHLER: Der Suchfilter wurde nicht erkannt., which can be translated as ERROR: The search filter could not be recognized.

So, how can I filter with a wildcard at the beginning?


Solution

  • The wildcard at the beginning does not work. You would need to incorporate findstr using a bit of initiative.

    for /f "tokens=2 delims=," %%a in ('tasklist /fi "imagename eq notepad.exe" /v /fo:csv /nh ^| findstr /r "wine"') do taskkill /pid %%a
    

    So we search for imagenames with wine in the name. Use /fo to csv format, /nh for no header, then search for the string "wine" in imagename, then kill by process ID if found.

    To not be imagename specific do:

    for /f "tokens=2 delims=," %%a in ('tasklist /v /fo:csv /nh ^| findstr /r "wine"') do taskkill /pid %%a
    

    Edit

    As for the concern in killing incorrect tasks:

    @echo off
    set "images=notepad.exe,calc.exe,winword.exe,excel.exe"
    for %%i in (%images%) do (
       for /f "tokens=2 delims=," %%a in ('tasklist /fi "imagename eq %%i" /v /fo:csv /nh ^| findstr /r "wine"') do taskkill /pid %%a
    )
    

    Just add a list of possible image names that would contain the title, it will only loop these as per below and not touch the other processes/tasks:

    tasklist /fi "imagename eq notepad.exe"
    tasklist /fi "imagename eq calc.exe"
    tasklist /fi "imagename eq winword.exe"
    tasklist /fi "imagename eq excel.exe"