简体   繁体   English

如何从批处理文件中获取刚刚启动的进程的PID?

[英]How to get PID of process just started from within a batch file?

In Windows batch scripting there is start command which starts a new process.在 Windows 批处理脚本中有start新进程的start命令。

Is it possible to get PID of the process just started?是否可以获取刚刚启动的进程的 PID?

This is an old post but I think that it worth to share the following 'easy to use' solution which works fine nowadays on Windows.这是一篇旧帖子,但我认为值得分享以下“易于使用”的解决方案,该解决方案如今在 Windows 上运行良好。

Start multiple processes in parallel:并行启动多个进程:

start "<window title>" <command will be executed>

Example:例子:

start "service1" mvn clean spring-boot:run
start "service2" mvn clean spring-boot:run

Obtain the PID of the processes (optional):获取进程的PID(可选):

tasklist /V /FI "WindowTitle eq service1*"
tasklist /V /FI "WindowTitle eq service2*"

Kill the processes:杀死进程:

taskkill /FI "WindowTitle eq service1*" /T /F
taskkill /FI "WindowTitle eq service2*" /T /F

You can in batch but not directly per say.你可以批量但不能直接说。 You need to either parse the output of tasklist.exe or use wmic.exe.您需要解析 tasklist.exe 的输出或使用 wmic.exe。 Both require you to know what you just started which of course you will.两者都要求您知道您刚刚开始的内容,当然您会知道。

Using tasklist.exe:使用 tasklist.exe:

for /F "TOKENS=1,2,*" %a in ('tasklist /FI "IMAGENAME eq powershell.exe"') do set MyPID=%b
echo %MyPID%

To use this in a batch script double up the percent signs.要在批处理脚本中使用它,请将百分号加倍。

Using wmic.exe:使用 wmic.exe:

for /f "TOKENS=1" %a in ('wmic PROCESS where "Name='powershell.exe'" get ProcessID ^| findstr [0-9]') do set MyPID=%a
echo  %MyPID%

If there are processes already running with the same name, you first need to get a list of the current pids, than start your local process(es) and then check the pids again.如果已经有同名进程在运行,您首先需要获取当前 pid 的列表,然后启动本地进程,然后再次检查 pid。 Here is a sample code that starts 3 process and kills them at the end (specifically the ones started locally):这是一个示例代码,它启动 3 个进程并在最后杀死它们(特别是在本地启动的那些):

@echo off
set PROCESSNAME=notepad.exe

::First save current pids with the wanted process name
setlocal EnableExtensions EnableDelayedExpansion
set "RETPIDS="
set "OLDPIDS=p"
for /f "TOKENS=1" %%a in ('wmic PROCESS where "Name='%PROCESSNAME%'" get ProcessID ^| findstr [0-9]') do (set "OLDPIDS=!OLDPIDS!%%ap")

::Spawn new process(es)
start %PROCESSNAME%
start %PROCESSNAME%
start %PROCESSNAME%

::Check and find processes missing in the old pid list
for /f "TOKENS=1" %%a in ('wmic PROCESS where "Name='%PROCESSNAME%'" get ProcessID ^| findstr [0-9]') do (
if "!OLDPIDS:p%%ap=zz!"=="%OLDPIDS%" (set "RETPIDS=/PID %%a !RETPIDS!")
)

::Kill the new threads (but no other)
taskkill %RETPIDS% /T > NUL 2>&1
endlocal

PowerShell can be used for this: PowerShell 可用于:

powershell -executionPolicy bypass -command "& {$process = start-process $args[0] -passthru -argumentlist $args[1..($args.length-1)]; exit $process.id}" notepad test.txt

echo Process ID of new process: %errorlevel%

you can try with你可以试试

wmic process call create "notepad"

which will return the pid of the created process.这将返回创建的进程的 pid。

Processing this with FOR用 FOR 处理这个

setlocal
set "ReturnValue="
set "ProcessId="
for /f "eol=} skip=5 tokens=1,2 delims=;= " %%a in ('wmic process call create "notepad"') do (
    set "%%a=%%b"
)
echo %ReturnValue%
echo %ProcessId%
endlocal

This is the code that i use to get a PID这是我用来获取PID的代码

for /f "tokens=2 delims=," %%a in ('tasklist /FO CSV ^| findstr /I /C:"entertheprocess.here"') do (
    echo PID:%%a
)

Thanks a lot to user - npocmaka.非常感谢用户 - npocmaka。

There are examples of how to start Mozilla Firefox and get PID of the started process.有一些示例说明如何启动 Mozilla Firefox 并获取已启动进程的 PID。

:: Example for cmd window

set AppCmdLine="C:\Program Files (x86)\Mozilla Firefox\firefox.exe -new-window http://www.google.com/"
set ProcessCmd=wmic process call create %AppCmdLine%
for /f "tokens=3 delims=; " %a in ('%ProcessCmd% ^| find "ProcessId"') do set PID=%a

echo %PID%

The same example for bat script bat脚本的相同示例

set AppCmdLine="C:\Program Files (x86)\Mozilla Firefox\firefox.exe -new-window http://www.google.com/"
set ProcessCmd=wmic process call create %AppCmdLine%
for /f "tokens=3 delims=; " %%a in ('%ProcessCmd% ^| find "ProcessId"') do set PID=%%a
echo %PID%

@ECHO OFF
SETLOCAL EnableDelayedExpansion EnableExtensions
::
::weil es mehrere Sessions für UltraCompare gleichzeitig geben kann, es wird hier die
::neueste Instanz (soeben gestartet) ermittelt, um später mit ProcessId diese Instanz 
::aktivieren zu können...
::
set "CreationDate="
set /A "ProcessIdUltraCompare=0"
::
set /A "lineno=0"
FOR /F %%T IN ('Wmic process where^(Name^="uc.exe"^) get CreationDate^|sort /r') DO (
set /A lineno+=1
rem echo %%T
rem echo !lineno!
if !lineno! equ 2 (
    rem ECHO %%T   
    set CreationDate=%%T
    rem echo !CreationDate!
    set /A "lineno=0"
    FOR /F %%P IN ('Wmic process where^(CreationDate^="!CreationDate!"^) get ProcessId') DO (
          set /A lineno+=1
          rem echo %%P
          if !lineno! equ 2 (
              set "ProcessIdUltraCompare=%%P"
              rem echo ProcessIdUltraCompare=!ProcessIdUltraCompare!
              goto :l_pid_uc_got
          )
      )
 )
)  
:l_pid_uc_got
    echo ProcessIdUltraCompare=!ProcessIdUltraCompare!
PAUSE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM