0

Scenario 1: calc.exe is running

taskkill /IM calc.exe /f | if "%ERRORLEVEL%"=="0" taskkill /IM calc.exe /f  

This sets 1 as the errorlevel.

Scenario 2: calc.exe is not running

taskkill /IM calc.exe /f  

This sets 128 as the errorlevel.

Can someone please explain me why this happens and if there is a way to get errorlevel as 128 in the first scenario as well similar to the second one?

aschipfl
  • 33,626
  • 12
  • 54
  • 99
sachin11
  • 1,087
  • 3
  • 13
  • 17

1 Answers1

0

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...

James L.
  • 9,384
  • 5
  • 38
  • 77