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

前端 未结 8 1921
栀梦
栀梦 2020-11-30 13:48

Is there a way to do this purely in a .bat file?

The purpose is to launch iexplore.exe, then kill just that instance when it\'s finished.

8条回答
  •  眼角桃花
    2020-11-30 14:20

    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
    

提交回复
热议问题