I experimented with taskkill
, tasklist
and find
. All return inconsistent errorlevels. That makes it impossible to reliably use errorlevel to know if the process is running or if it has truly been terminated. However, I did find a way to do it without using errorlevel:
@echo off
setlocal ENABLEDELAYEDEXPANSION
set _i=0
for /f "delims=" %%i in ('tasklist ^| find /i "%1"') do set /a _i+=1
if !_i! GTR 0 (
echo Found !_i! instances of %1. Terminating all instances...
taskkill /im "%1" /f > nul 2>&1
echo Verifying that %1 has been terminated...
set _i=0
for /f "delims=" %%i in ('tasklist ^| find /i "%1"') do set /a _i+=1
if !_i! EQU 0 (
echo %1 was successfully terminated.
) else (
echo %1 was *not* teriminated. There are still !_i! instances running.
)
) else (
echo %1 is not running.
)
set _i=
endlocal
You need to enable delayed expansion, so that the _i
variable can be properly evaluated.
The for ... %%i
line of code sets _i
equal to the number of instances that the process is in memory. Since find
doesn't return a consistent errorlevel, we can use this technique to reliably find the # of times it is in memory...