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?
Easy solution to this, given that
Just write it to a file using output redirection and use FIND to check the file. Each time this is run, it will overwrite the previous iteration, so no need to even do any file cleanup. Amazing how many bat/cmd file limitations can be overcome with a simple scratchpad file!!
You could pipe tasklist through the find command and get an errorlevel off of it.
Example:
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 acmd
variable which is expanded with delayed expansion to avoid any side effects of special characters.%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:
%errorlevel%
or the more correctIF errorlevel 1 ...
on the next linesetlocal 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:
Run it as test.cmd SOTEST and it prints: