等待进程结束并继续CMD / BATCH中的代码

时间:2015-03-20 19:41:05

标签: batch-file cmd wait

我正在尝试等待过程结束,不能使用"开始/ W"因为该过程从另一个程序打开。

总而言之,我需要某种扫描程序来查找 WaitSession 中的进程,然后将代码继续到 KillSession

@echo off
color 02
cd /D C:\Windows\System32
timeout -t 1

***WaitSession***
(Wait for this process to end) MightyQuest.exe

***KillSession***
taskkill /f /im PublicLauncher.exe
taskkill /f /im AwesomiumProcess.exe

由于

3 个答案:

答案 0 :(得分:2)

这应该这样做:

@echo off
color 02
cd /D C:\Windows\System32
timeout -t 1

SET TempFile="%Temp%\%RANDOM%.txt"

:WaitSession
REM Fetch the current process list. Store in a temp file for easy searching.
TASKLIST > %TempFile%

REM Reset the process "flag" variable.
SET "Process="

REM Check for a process with the target name by searching the task list for the target process name.
REM If output is returned, it will be put into the Process "flag" variable.
FOR /F "usebackq tokens=1 delims=-" %%A IN (`FINDSTR /I "MightyQuest.exe" %TempFile%`) DO SET Process=%%A

REM If nothing was returned, it means the process isn't running.
IF "%Process%"=="" GOTO KillSession

ECHO Process is still running.

REM Wait and then try again.
TIMEOUT /T 20
GOTO WaitSession

:KillSession
taskkill /f /im PublicLauncher.exe
taskkill /f /im AwesomiumProcess.exe

REM Cleanup.
DEL %TempFile% > nul

这里的想法是你继续轮询活动的任务列表,当找到目标进程时,你会延迟几秒钟,然后再试一次。

在任务列表中找不到后,跳转到KillSession步骤。

答案 1 :(得分:1)

使用wmic Windows Management Instrumentation Command

@echo off
color 02
rem why? cd /D C:\Windows\System32
timeout -t 1

:wait
TIMEOUT -t 3 /NOBREAK>nul
rem ***WaitSession***
rem (Wait for this process to end) MightyQuest.exe
for /F "tokens=*" %%G in (
    'wmic process where "name='MightyQuest.exe'" get name'
) do if /i not "%%G"=="No Instance(s) Available."  goto :wait

rem ***KillSession***
taskkill /f /im PublicLauncher.exe
taskkill /f /im AwesomiumProcess.exe

答案 2 :(得分:0)

一个vbscript

Set WshShell = WScript.CreateObject("WScript.Shell")
Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2") 
Set objEvents = objWMIService.ExecNotificationQuery _
    ("SELECT * FROM Win32_ProcessTrace")

Do
    Set objReceivedEvent = objEvents.NextEvent
    msgbox objReceivedEvent.ProcessName
Loop

使用Win32_ProcessTraceStop仅捕获终止。