How to capture the PID of a process when launching it from command line?

Here’s what I use:

@echo off

rem there is a tab in the file at the end of the line below
set tab=    
set cmd=javaw -jar lib\MyProg.jar
set dir=%~dp0

echo Starting MyProg
set pid=notfound

for /F "usebackq tokens=1,2 delims=;=%tab% " %%i in (
    `wmic process call create "%cmd%"^, "%dir%"`
) do (
    if /I %%i EQU ProcessId (
        set pid=%%j
    )
)

echo %pid% > MyProg.pid

The directory is set to the directory that the cmd file is located in. Change dir to alter that. Modify cmd to change which command is run.

If you want a stop.cmd that kills it, it would look like this

@echo off
for /F %%i in (%~dsp0MyProg.pid) do taskkill /F /PID %%i
del %~dsp0MyProg.pid

Leave a Comment