Qwertiy
Qwertiy

Reputation: 21400

Start program and get process id

In batch file I can start a program in parallel to current session via

start "" notepad.exe

but I need to get a handle of the process I've started. How can I get it?

Upvotes: 3

Views: 5046

Answers (2)

npocmaka
npocmaka

Reputation: 57252

@echo off

:: set your own command here
set "command=notepad"
set "workdir=."

set "ReturnValue="
set "ProcessId="
for /f " skip=5 eol=} tokens=* delims=" %%a in ('wmic process call create "%command%"^,"%workdir%"') do (
    for /f "tokens=1,3 delims=;  " %%c in ("%%a") do (
        set "%%c=%%d"
    )
)



if not %ReturnValue%==0 (
    echo some kind of error - error code %ReturnValue%
) else if defined ProcessId echo PID -^> %ProcessId%

delims in this line for /f "tokens=1,3 delims=; " should be for /f "tokens=1,3 delims=;<tab><space>" and I don't know if the tab will correctly copied.You also need to check if your editor replaces tab with spaces.Check also this.

Upvotes: 3

Qwertiy
Qwertiy

Reputation: 21400

Based on @npocmaka answer found the other solution:

@echo off

set pid=0
for /f "tokens=2 delims==; " %%a in ('wmic process call create "notepad.exe"^,"%~dp0." ^| find "ProcessId"') do set pid=%%a
echo %pid%

timeout 5
taskkill /pid %pid%

Upvotes: 1

Related Questions