Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass PIDs from tasklist and kill processes with tasklist

I am trying to get windows processes matching some certain criteria, e.g. they are like "123456.exe" and trying to kill them with tasklist. I am trying to do it like that:

FOR /F "usebackq tokens=2 skip=2" %i IN (`tasklist |findstr /r "[0-9].exe") DO taskkill /PID %i

which is not right and I don't know why.... Can anyone give me a hint? Thanx in advance!

like image 438
Guiness Avatar asked Mar 15 '12 00:03

Guiness


1 Answers

FOR /F "usebackq tokens=2" %i IN (`tasklist ^| findstr /r /b "[0-9][0-9]*[.]exe"`) DO taskkill /pid %i

Several changes:

  • The command_to_process needs back quotes (``) on both sides of the command.
  • Pipes ("|") inside of the command_to_process need to be escaped with a caret ("^").
  • Your findstr command would match all processes that have a digit before the ".exe". For example, "myapp4.exe" would also have been killed. The version I provide will match process names solely containing numbers.
  • The "skip=2" option would skip the first two lines output from findstr, not tasklist. Since the regular expression won't match anything in the first two lines output from tasklist, you're safe to remove the skip option.

By the way, if you place this command in a batch script, remember to use "%%i" instead of "%i" for your parameters, or you'll get an error message like i was unexpected at this time.

  • FOR /F documentation
  • Findstr documentation
like image 140
Chad Nouis Avatar answered Oct 17 '22 18:10

Chad Nouis