filebatch-fileexitstatustasklist

Exit status of tasklist in batch file?


I am executing following command in a label inside a batch file:

tasklist.exe /FI "USERNAME eq %USERDOMAIN%\%USERNAME%" /FI "IMAGENAME eq %1" /FI "PID eq %2" 2>nul && echo errorl:%errorlevel%

%1 is process running and %2 is its PID. Even if process and its PID matches or doesnt matches, I m getting "errorl:1" in o/p.

I am not sure whats wrong here. Any idea?


Solution

  • 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
    )