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.


Solution 1:

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

Solution 2:

you can use vbscript, here's an example creating notepad, then terminating it using its pid

strComputer = "."
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objStartup = objWMIService.Get("Win32_ProcessStartup")
Set objConfig = objStartup.SpawnInstance_
Set objProcess = GetObject("winmgmts:root\cimv2:Win32_Process")
errReturn = objProcess.Create("notepad.exe", null, objConfig, PID)
If errReturn = 0 Then
    WScript.Echo "Process ID is: " & PID
End If 

WScript.Echo "Ready to kill process: " & PID & "? [Y|y]"
Do While Not WScript.StdIn.AtEndOfLine
   strInput = strInput & WScript.StdIn.Read(1)
Loop
If LCase(strInput) = "y" Then
    WScript.Echo "Select * from Win32_Process Where ProcessId = '" & PID & "'"
    Set colProcessList = objWMIService.ExecQuery("Select * from Win32_Process Where ProcessId = '" & PID & "'")
    For Each objProcess in colProcessList
        objProcess.Terminate()
    Next
End If 

save as myscript.vbs and on command line

c:\test> cscript /nologo myscript.vbs

Solution 3:

A slight variation on the answer provided by @kybernetikos since it has a parsing issue. Note the line if %%j gr 0 (

@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 %%j gtr 0 (
        set pid=%%j
    )
)

echo %pid% > MyProg.pid