问题描述
我在使用命令 TASKLIST 检查另一个批处理文件的运行状态时遇到问题,并根据结果继续处理批处理文件。
这是我的批处理文件的代码,它应该检查另一个批处理文件的运行状态:
@echo off
tasklist /FI "WINDOWTITLE eq C:\Windows\system32\cmd.exe - C:\ruta\ejecucion_prueba.bat" /FI "STATUS eq running"
if eq = running "not happening"
if ne = running "start C:\ruta\ejecucion_prueba.bat"
exit
信息:没有运行符合指定条件的任务。
= 在这个时候出乎意料。
有什么问题,如何正确进行批处理文件执行检查?
解决方法
tasklist.exe
不会写入 stdErr 或记录您可以使用的 ErrorLevel,以确定过滤器是否返回了任务。为了确定这一点,您需要使用 find.exe
或 findstr.exe
来检查成功输出中的已知字符或字符串。然后,您可以使用返回的 ErrorLevel 或 Success/Failure 进行验证。
使用 tasklist.exe
执行此任务的唯一“相对稳健”的方法是首先确保您最初使用以下命令运行批处理文件 C:\ruta\ejecucion_prueba.bat
:
Start "?" C:\ruta\ejecucion_prueba.bat
或(推荐):
Start "?" "C:\ruta\ejecucion_prueba.bat"
完成后,您可以运行验证批处理文件,在其内容中包含以下行:
%SystemRoot%\System32\tasklist.exe /Fi "ImageName Eq cmd.exe" /Fi "Status Eq Running" /Fi "WindowTitle Eq ? - C:\ruta\ejecucion_prueba.bat" | %SystemRoot%\System32\find.exe "=" 1> NUL || Start "?" "C:\ruta\ejecucion_prueba.bat"
但是,如果您的批处理文件路径包含空格:
C:\ruta\ejecucion prueba.bat
您最初需要使用以下命令运行它:
Start "?" "C:\ruta\ejecucion prueba.bat"
然后将批处理脚本中的命令更改为:
%SystemRoot%\System32\tasklist.exe /Fi "ImageName Eq cmd.exe" /Fi "Status Eq Running" /Fi "WindowTitle Eq ? - \"C:\ruta\ejecucion prueba.bat\"" | %SystemRoot%\System32\find.exe "=" 1> NUL || Start "?" "C:\ruta\ejecucion prueba.bat"
注意:关于您之前无限期运行此程序的意图,(我不推荐)。当您 start
您的 .bat
文件时,窗口标题不会立即在 tasklist.exe
内注册。这意味着,如果您在循环中或通过计划任务运行它,延迟可能会导致您的脚本认为批处理文件没有运行,而实际上它没有运行。