Search code examples
batch-filewmic

batch file wmic usage


I need to get pid from below command which works if I use it in command line like below:

wmic process where "name="java.exe" and CommandLine like '%%cassandra%%'" get ProcessId | FINDSTR /v ProcessId | FINDSTR /r /v "^$"

but fails if used in .bat file:

FOR /F "tokens=2" %%G IN ('wmic process where ^(name^="java.exe"^ and CommandLine like '%%cassandra%%') get ProcessId ^| FINDSTR /v ProcessId ^| FINDSTR /r /v "^$"') DO (
   set PARENT_PID=%%G
)
echo !PARENT_PID!

Can anyone help in this?


Solution

  • Your escape points are incorrect and not sure if you enabled delayedexpansion, but I will not be using it in this example:

    @echo off
    for /F "tokens=2 delims==" %%G IN ('wmic process where (name^="java.exe" and commandline like '%%cassandra%%'^) get ProcessId /value') DO if not defined parent_pid set "parent_pid=%%G"
    echo %parent_pid%
    

    You will note that I used the /value switch for wmic and removed the findstr /v command, because I am using = as delimiter for splitting the value.

    Also note, if you have more than one process running with the same commandline and name, you will only get one result, because you only set a value once, so in that case, do not set a variable. i.e:

    @echo off
    for /F "tokens=2 delims==" %%G IN ('wmic process where (name^="java.exe" and commandline like '%%cassandra%%'^) get ProcessId /value') DO echo %%G