Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Batch file - taskkill if window title contains text

I want to write a simple batch file to kill a process that contains certain text in the window title. Right now I have:

taskkill /fi "Windowtitle eq XXXX*" /im cmd.exe  

And that works, except what I want to do is use the wildcard both at the beginning AND end of the title. So something like:

taskkill /fi "Windowtitle eq \*X*" /im cmd.exe  

But I tried this and it does not work. Is there something I'm missing or is this not possible?

like image 508
uesports135 Avatar asked Oct 24 '14 16:10

uesports135


2 Answers

No, wildcards are not allowed at the start of the filter.

for /f "tokens=2 delims=," %%a in ('
    tasklist /fi "imagename eq cmd.exe" /v /fo:csv /nh 
    ^| findstr /r /c:".*X[^,]*$"
') do taskkill /pid %%a

This will retrieve the list of tasks, in csv and verbose format (that will include window title as the last field in the output).

The list is filtered by findstr with a regular expression that will search the indicated text (the X) in the last field.

If any line matches the filter, the for will tokenize it, retrieving the second field (the PID) that will be used in taskkill to end the process.

like image 81
MC ND Avatar answered Nov 01 '22 12:11

MC ND


In the special case you have started the command window from a batch file yourself, you can specify the window title using the command

START MyWindowTitle c:/MyProcess.exe 

That way it is easy to kill the process again using just

taskkill /fi "WindowTitle eq MyWindowTitle"
like image 27
Godsmith Avatar answered Nov 01 '22 13:11

Godsmith