Leptonator
Leptonator

Reputation: 3499

WMIC Process List and then terminate?

EDIT @aschipfl - You response is perfect! Answer is below.

HISTORY.. Why do this? 99.9% of the time, we are able to simply just perform the following:

WMIC service where "name like 'tomcat%%'" CALL stopservice

And it works fine. However, there has been an occasion, where we would have Tomcat stay in memory and not stop. So we have to terminate it. I have to add "signature" files provided from our vendor in once a month on about 40 servers and I must be 100% sure that I am able to do so without issue. Most of our issues seem to be with Tomcat7 and JDK7 with some memory tweaking.

I have the following in my batch script, which both of these work great.

WMIC Path win32_process WHERE "CommandLine Like '%%tomcat%%'" CALL Terminate
WMIC Path win32_process WHERE "CommandLine Like '%%java%%'" CALL Terminate

However, I would really prefer not to terminate tomcat6w.exe or tomcat7w.exe. What I really want to do is to terminate tomcat?.exe, but not terminate: tomcat?w.exe

When I tried the following, I just killed my server - doh!!

WMIC service where "name like 'tomcat%%'" get processid | WMIC Path win32_process WHERE "processid = processid" CALL Terminate

I think I can do the following, but is not working yet:

for /F "skip=1" %%a in ('WMIC service where "name like 'tomcat%%'" get processid') do set pid=%%a
WMIC Path win32_process WHERE "processid = %pid%" CALL Terminate

However, since I am doing a wildcard with tomcat, I think it is adding an extra Carriage return..

Ref.. I did find some interesting info here: http://www.dostips.com/forum/viewtopic.php?f=3&t=3815

Hope this makes sense?

Answer

FOR /F "skip=1" %%a IN ('WMIC service where "name like 'tomcat%%'" get processid') DO (
FOR /F "delims=" %%b IN ("%%a") DO SET pid=%%b
)
WMIC Path win32_process WHERE "processid = %pid%" CALL Terminate
pause

Thanks!

Upvotes: 0

Views: 6548

Answers (1)

aschipfl
aschipfl

Reputation: 34899

The extra carriage-return comes from the wmic command (independent on whether you are using wildcards or not). wmic outputs Unicode text, the conversion to ASCII by for /F does not work perfectly.

To get rid of the additional carriage-return, simply wrap another for /F loop around:

for /F "skip=1" %%a in ('WMIC service where "name like 'tomcat%%'" get processid') do for /F "delims=" %%b in ("%%a") do set pid=%%b

So the variable pid contains the pure process ID value.

Upvotes: 2

Related Questions