Search code examples
windowsbatch-filecmdtasklist

Why is my usage of command TASKLIST not working as expected?


I have a problem on checking the running state of another batch file using the command TASKLIST and continue processing the batch file depending on the result.

This is the code of my batch file which should check the running state of the other batch file:

@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

This code does not work as expected. The output on execution is:

INFO: No tasks are running which match the specified criteria.
= was unexpected at this time.

What is wrong and how to do the batch file execution check correct?


Solution

  • tasklist.exe does not write to stdErr or record an ErrorLevel you can use, to determine whether the filters returned a task. In order to determine that, you need to use find.exe or findstr.exe to check for a known character or string in a successful output. You can then use the returned ErrorLevel or Success/Failure of that to validate instead.

    The only 'relatively robust' way to perform this task using tasklist.exe is to first ensure that you initially ran your batch file, C:\ruta\ejecucion_prueba.bat using the following command:

    Start "?" C:\ruta\ejecucion_prueba.bat
    

    Or (recommended):

    Start "?" "C:\ruta\ejecucion_prueba.bat"
    

    With that done, you could run your verification batch file, with the following line in its content:

    %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"
    

    However, if your batch file path contains spaces:

    C:\ruta\ejecucion prueba.bat
    

    You'd need to have initially ran it using:

    Start "?" "C:\ruta\ejecucion prueba.bat"
    

    Then change the command in your batch script to:

    %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"
    

    Note: Regarding your previous intention to run this indefinitely, (which I do not recommend). When you start your .bat file, the Window Title, does not immediately register within tasklist.exe. That means, were you to run this in a loop or through a scheduled task, it is possible that the delay may cause your script to believe that the batch file isn't running, when in fact it is.