启动程序并获取进程ID

时间:2017-09-12 17:45:05

标签: windows batch-file command-line

在批处理文件中,我可以通过

与当前会话并行启动程序
start "" notepad.exe

但是我需要掌握我已经开始的过程。我怎么能得到它?

2 个答案:

答案 0 :(得分:2)

@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%

此行for /f "tokens=1,3 delims=; "中的delim应为for /f "tokens=1,3 delims=;<tab><space>",如果选项卡正确复制,则不会。我还需要检查编辑器是否用空格替换制表符。同时检查{{3} }。

答案 1 :(得分:1)

基于@npocmaka answer找到了另一个解决方案:

@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%