我用taskkill
,tasklist
和find
進行了實驗。所有返回不一致的錯誤級別。這使得不可能可靠地使用errorlevel來知道進程是否正在運行或者它是否真正被終止。但是,我沒有找到一個方法來做到這一點,而無需使用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
您需要啓用延遲擴展,從而使_i
變量可以適當地評估。
for ... %%i
代碼行集_i
等於進程在內存中的實例數。由於find
不會返回一致的錯誤級別,因此我們可以使用此技術可靠地查找它在內存中的次數...