Search code examples
windowsbatch-filecmdtasklist

How would I check if a named program is running in a batch script?


For some reason it says awesome even when the program is not open, and even if I put in a window name like "asdfsd" or something random. Can anyone help?

@echo off
:start
tasklist | find /I "WINDOWNAME"
if errorlevel 1 (
    echo awesome
)
goto :start

Solution

  • At first, let me recommend not to use find just to find a certain window title in the whole output of tasklist, because the search string might occur somewhere else, like the image name, for example, which could lead to false matches.

    Anyway, the tasklist command does not set the exit code (ErrorLevel) when the filter /FI does not find a match, but you could check whether the output begins with INFO:, which is the case when no match was encountered:

    :start
    timeout /T 1
    tasklist /FI "WindowTitle eq WindowName" | findstr /B "INFO:" > nul && (echo goto :start) || (echo awesome)`.
    

    This depends on the returned single line in case of no matches:

    INFO: No tasks are running which match the specified criteria.
    

    This text depends on the locale/region/language settings of the system. To make this even locale-independent, you could use the a trick: tasklist, with default output format (/FO TABLE), returns more than a single line when at least a match is encountered, because there is a two-line header followed by the actual matching items; if there is no match, the aforementioned line is the only one returned. So capture the output of tasklist by a for /F loop, using the option skip=1. The for /F loop will then set the exit code to 1 (not the ErrorLevel though) when it does not iterate, and to 0 when it iterates at least once. This exit code can be checked using the conditional execution operators && and ||:

    :start
    timeout /T 1
    (for /F "skip=1" %%I in ('tasklist /FI "WindowTitle eq WindowName"') do rem/) && (echo awesome) || (goto :start)
    

    I inserted the timeout command in order to avoid heavy CPU loads by the goto :start loop.