Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 485
Patryk S Avatar asked Sep 02 '14 11:09

Patryk S


2 Answers

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.

like image 72
MC ND Avatar answered Oct 14 '22 06:10

MC ND


I had a similar problem where I had to stop a task only knowing the name of the running file. The solution was:

for /f "tokens=2 delims=," %%a in (
    'wmic service get name^,pathname^,state /format:csv ^| findstr /i /r /c:"SomeServer\.exe.*Running$"'
) do sc stop "%%a"

This will stop the process by name. Maybe you can use the file name instead of the PID?!?

like image 33
MichaelS Avatar answered Oct 14 '22 07:10

MichaelS