How to find a process pid with wmic and kill it with taskkill

Patryk S picture Patryk S · Sep 2, 2014 · Viewed 20.7k times · Source

I need to find a process PID with WMIC command, and then kill this process with taskkill. I've almost achieved that, but the only problem is there is a newline on the end of the PID variable. So far i made this:

c:\patryk>for /F "skip=1 tokens=*" %a in ('wmic process where "CommandLine like '%sourceprocessor%' and name like '%java%'" get ProcessId') do taskkill /pid | set /p pid=%a

So this is looping through the output of wmic which contains 3 lines: title (ProcessId), found PID (a number) and an empty line. I'm skipping first line, because it's just title. Now i want to kill a process with pid found in second line. And there is a problem, that it has an newline mark at the end of the line, so whole command does not work. Can anybody give me some advice how can i achieve that? How can i remove this newline mark?

Answer

MC ND picture MC ND · Sep 2, 2014
for /F "skip=2 tokens=2 delims=," %a in (
  'wmic process where " .... " get ProcessID^,Status /format:csv'
) do taskkill /pid %a

Now you have an output from wmic with an aditional line at the start (from here the skip), with fields separated with commas (the delim), and three fields included: the node (computername) that is automatically added, the processid (the second token) and a final status field that will not be used but allows us to retrieve the second token in the line without the ending CR

Or you can add an aditional for command to your initial line

for /f ... %a in ( ... ) do for %b in (%a) do taskkil /pid %b

This aditional for loop will remove the CR character from the retrieved wmic data that is in %a.