Master_Roshy February 2016

getting pid of process in windows server

I was looking for a script to get PID of a java process based on CommandLine value of task manager. ALl these java processes have similar COmmandLine value but differ in a keyword within the CommandLine. The process can't be identified by the image name because they all have same java.exe. Is there a way? I've placed below code based on npocmaka's answer

@echo off
setlocal enableDelayedExpansion

set "command_line="%1""

set "command_line=!command_line:"=%%!"

echo ~~!command_line!~~

for /f "usebackq tokens=* delims=" %%# in (
    `wmic process where 'CommandLine like "%command_line%"' get /format:value`
) do (
    for /f %%$ in ("%%#") do (
        set "%%$"
    )
)

echo %ProcessId%

I'm using a keyword in CommandLine to identify the PID. Yet when I execute this script, I get the wrong PID. I'm assuming its returning the scripts PID as the script may also contain the keyword. The argument while executing the script is taken as keyword

Answers


npocmaka February 2016

WMIC PROCESS is what you need.Though you'll need some tricks to use it from batch.I've used more complex command line which contains quotes ,brackets,spaces, file separators.... You'll need to change it and set the value you want.

First you'll need to double every backslash in the command line(the script should do it I mean).Quotes also can be a problem and need to be replaced with % or escaped with \" (WMIC uses WQL a subset of SQL commands and % is used as wildcard).Another thing is you need to process the result twice with FOR loop to rid-off unwanted special characters./Format:Value can be used for direct declaring variable/value pairs.So here it is:

@echo off
setlocal enableDelayedExpansion

:: !!!!!!!!!
set "command_line="C:\Program Files (x86)\Dropbox\Client\Dropbox.exe" /systemstartup"
:: !!!!!!!!

set "command_line=!command_line:\=\\!"
set "command_line=!command_line:"=%%!"
::or
::set "command_line=!command_line:"=\"!"


rem echo ~~!command_line!~~

for /f "usebackq tokens=* delims=" %%# in (
    `wmic process where 'CommandLine^="!command_line!"' get /format:value`
) do (
    for /f %%$ in ("%%#") do (
        set "%%$"
    )
)

echo %ProcessId%

Post Status

Asked in February 2016
Viewed 2,744 times
Voted 10
Answered 2 times

Search




Leave an answer