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

前端 未结 8 1936
栀梦
栀梦 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:18

    For some reason your approach of getting process id did not work for me, but since I'm expert in batches, I've coded my own approach, attaching here:

    @echo off
    
    call:AsyncCmd
    rem call:AsyncCmd "echo hello world"
    rem call:AsyncCmd "call build.bat"
    exit /b
    
    rem ------------------------------------------------------------------------------------------
    rem Starts asynchronous command execution 
    rem %1 is command, if empty - only aborts existing build.
    rem ------------------------------------------------------------------------------------------
    :AsyncCmd
    if exist %~dp0SetupBuild_Completed.txt (
        del /f %~dp0SetupBuild_Pid.txt >nul 2>&1
        del /f %~dp0SetupBuild_Completed.txt >nul 2>&1
    )
    
    if not exist %~dp0SetupBuild_Pid.txt goto lStartProc
        rem --------------------------------------------------
        rem Abort build process
        rem --------------------------------------------------
        set /p pid=<%~dp0SetupBuild_Pid.txt
        echo Cancelling setup build process, process id %pid%
        pskill -t %pid%
        del /f %~dp0SetupBuild_Pid.txt >nul 2>&1
    
    :lStartProc
    if "%~1" == "" exit /b 0
    
    rem --------------------------------------------------
    rem Starts asyncronous build process
    rem --------------------------------------------------
    set dir=%~dp0
    set dir=%dir:~0,-1%
    for /f "tokens=2 delims==; " %%a in ('wmic process call create "cmd /c mincon.exe && %~1 && echo 1>%~dp0SetupBuild_Completed.txt"^, "%dir%" ^| findstr /r "ProcessId"') do set pid=%%a
    echo Setup build started, process id: %pid%
    echo %pid%>%~dp0SetupBuild_Pid.txt
    exit /b 0
    

提交回复
热议问题