等待.bat文件在Windows批处理文件中关闭

时间:2016-05-26 11:13:11

标签: windows batch-file

我需要创建一个Windows批处理文件(* .bat)文件,该文件仅在某些进程(和批处理文件)未运行时才运行其命令。

我在这里查看了适用于进程(* .exe)的解决方案: How to wait for a process to terminate to execute another process in batch file

我想做一些非常相似的事情,但是,有一个难点:批处理文件在“TASKLIST”命令中显示为“cmd.exe”。

我想检查特定的bat文件是否正在运行,例如:“C:\ mybatch.bat”,如果是,请等到它关闭。

2 个答案:

答案 0 :(得分:0)

默认情况下你说的是什么。

要测试,创建一个新的.bat文件(假设为1.bat)并放入其中

计算值

MSPAINT

保存并运行它。 计算器将启动。您会注意到Paitbrush只有在您关闭计算器时才会启动。

答案 1 :(得分:0)

检查特定的bat文件mybatch.bat是否正在运行可能比一见即时更艰巨的任务。

tasklist /V中查找特定窗口标题以及在CommandLine 中测试wmic process where "name='cmd.exe'" get CommandLine属性可能会在某些可以想象的情况下失败

<强>第一即可。你能

吗?
  • title ThisIsDistinguishingString 开头添加mybatch.bat命令和
  • title
  • 中删除所有其他mybatch.bat个命令
  • 确保mybatch.bat 调用包含title命令的其他批处理脚本?

然后检查从find command返回的errorlevel,如下所示:

:testMybatch
tasklist /V /FI "imagename eq cmd.exe" | find "ThisIsDistinguishingString" > nul
if errorlevel 1 (
    rem echo mybatch.bat batch not found
) else (
    echo mybatch.bat is running %date% %time%
    timeout /T 10 /NOBREAK >NUL 2>&1
    goto :testMybatch
)

<强>第二即可。否则,请检查wmic Windows Management Instrumentation command输出是否有帮助

wmic process where "name='cmd.exe'" get /value

然后你可以在其输出中检测到mybatch.bat缩小为

wmic process where "name='cmd.exe'" get CommandLine, ProcessID

请注意wmic可能会返回一些Win32_Process class属性,特别是CommandLine为空,如果某个特定进程是在另一个用户帐户下启动或已提升(运行为管理员)。
提升wmic完整返回所有属性。

相关问题