Exit status of tasklist in batch file?

You could pipe tasklist through the find command and get an errorlevel off of it.

Example:

tasklist | find "firefox.exe"
echo Error level = %ERRORLEVEL%

REM If firefox is running, the errorlevel is set to 0
REM If firefox is not running, errorlevel is set to 1

In my opinion, you can't use errorlevel at all,
because tasklist always returns a 0 even if the pid isn't found.

I suppose, you have to parse the output of tasklist.
To fetch the output of a command, FOR /F is a good choice.

To avoid problems wth the quoting in the FOR /F, I build first a cmd variable which is expanded with delayed expansion to avoid any side effects of special characters.

@echo off
setlocal enableDelayedExpansion

set "cmd=tasklist.exe /FI "USERNAME eq %USERDOMAIN%\%USERNAME%" /FI "IMAGENAME eq %1" /FI "PID eq %2""

for /F "delims=*" %%p in ('!cmd! ^| findstr "%2" ') do (
  echo found %%p
)

%variables% are expanded before executing the line, so %errorlevel% will expand to some old value. (The fact that the code after && executes at all is your clue that the command returned 0)

You options are:

  • Use %errorlevel% or the more correct IF errorlevel 1 ... on the next line
  • Call setlocal ENABLEDELAYEDEXPANSION first and then use !errorlevel!

Edit: I guess tasklist is buggy and/or stupid when it comes to exit codes, I wrote some code that does not use the exit code at all:

@echo off
if "%~1"=="SOTEST" (
    start calc
    ping -n 2 localhost >nul
    for /F "tokens=1,2 skip=3" %%A in ('tasklist /FI "IMAGENAME eq calc.exe"') do (
        call "%~0" %%A %%B
    )
    call "%~0" dummy.exe 666
    goto :EOF
)
goto main


:IsTaskRunning
setlocal ENABLEEXTENSIONS&set _r=0
>nul 2>&1 (for /F "tokens=1,2" %%A in ('tasklist /FO LIST %*') do (
    if /I "%%~A"=="PID:" set _r=1
))
endlocal&set IsTaskRunning=%_r%&goto :EOF

:main
call :IsTaskRunning /FI "USERNAME eq %USERDOMAIN%\%USERNAME%" /FI "IMAGENAME eq %1" /FI "PID eq %2"
if %IsTaskRunning% gtr 0 (echo.%1:%2 is running) else (echo.%1:%2 is NOT running)

Run it as test.cmd SOTEST and it prints:

calc.exe:4852 is running
dummy.exe:666 is NOT running