javawindowsparsingbatch-filepid

Parse executable console output in batch file


So im running this command to find the java process thats running my JAR.

wmic.exe process where "name like '%java%'" get processid,commandline | find "myjar.jar"

The console output of the above command looks like this:

javaw  -jar "\myjar.jar"  1932

How can i parse this output so I can use the process id 1932 to kill it using:

TASKKILL /PID 1932

Solution

  • You shouldn't need to get the PID, or use TaskKill, WMIC can do it directly for you.

    From the command line:

    WMIC Process Where "CommandLine Like '%myjar.jar%'" Call Terminate >Nul 2>&1
    

    From a batch file you need to double the percent characters:

    @WMIC Process Where "CommandLine Like '%%myjar.jar%%'" Call Terminate >Nul 2>&1
    

    For an extra degree of safety and a small speed increase, please consider using %SystemRoot%\System32\wbem\WMIC.exe instead of WMIC.