Ser*_*sev 27 windows scripting batch-file
在Windows批处理脚本中,有一个start
命令可以启动一个新进程.
是否有可能刚刚启动过程的PID?
And*_*ndi 17
你可以批量但不是直接说.您需要解析tasklist.exe的输出或使用wmic.exe.两者都要求你知道你刚开始做什么,当然你会.
使用tasklist.exe:
for /F "TOKENS=1,2,*" %a in ('tasklist /FI "IMAGENAME eq powershell.exe"') do set MyPID=%b
echo %MyPID%
Run Code Online (Sandbox Code Playgroud)
要在批处理脚本中使用它,请将百分号加倍.
使用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%
Run Code Online (Sandbox Code Playgroud)
Oli*_*del 14
如果正在运行的进程具有相同的名称,则首先需要获取当前pid的列表,而不是启动本地进程,然后再次检查pid.下面是一个示例代码,它启动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
Run Code Online (Sandbox Code Playgroud)
zap*_*pee 14
这是一个老帖子,但我认为值得分享以下"易于使用"的解决方案,现在在Windows上工作正常.
并行启动多个进程:
start "<window title>" <command will be executed>
Run Code Online (Sandbox Code Playgroud)
例:
start "service1" mvn clean spring-boot:run
start "service2" mvn clean spring-boot:run
Run Code Online (Sandbox Code Playgroud)
获取进程的PID(可选):
tasklist /V /FI "WindowTitle eq service1*"
tasklist /V /FI "WindowTitle eq service2*"
Run Code Online (Sandbox Code Playgroud)
杀死进程:
taskkill /FI "WindowTitle eq service1*" /T /F
taskkill /FI "WindowTitle eq service2*" /T /F
Run Code Online (Sandbox Code Playgroud)
你可以尝试
wmic process call create "notepad"
Run Code Online (Sandbox Code Playgroud)
这将返回创建的进程的 pid。
用 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
Run Code Online (Sandbox Code Playgroud)