Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 libMyProg.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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...