5

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!

Guiness
  • 277
  • 1
  • 4
  • 9

3 Answers3

15
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.

rogerdpack
  • 62,887
  • 36
  • 269
  • 388
Chad Nouis
  • 6,861
  • 1
  • 27
  • 28
  • What would be the change in the command above if I want to kill only the first pid in the list? i.e. if I have 2 notepad.exe open, I want to kill only the first pid in the list. – Jai Apr 06 '13 at 14:05
  • Never mind, I figured out the secret sauce. setlocal enabledelayedexpansion set flag=0 FOR /F "usebackq tokens=2" %%i IN (`tasklist ^| findstr /r /b "notepad.exe"`) DO ( if !flag! == 0 ( echo !flag! taskkill /pid %%i set flag=1 echo !flag! ) ) endlocal – Jai Apr 06 '13 at 14:42
0

If the processes name difference is not very complex, e.g. if the name is always the same you can use the /FI option of taskkill directly

taskkill /FI "IMAGENAME eq your_image_name_here.exe"

==> taskkill documentation

fab
  • 9
  • 1
0

I used this in command line: name variable can contains blank surround with "

SET name="process name you want to kill" && FOR /F "tokens=2,* delims=," %f IN ('TASKLIST /fo csv /v ^| FINDSTR /i /c:!name!') DO @TASKKILL /f /t /pid %f

Kim Ki Won
  • 1,795
  • 1
  • 22
  • 22