检查错误,但不要显示错误

时间:2016-10-16 14:14:58

标签: windows cmd command-prompt

我有一个小脚本可以杀死一些进程。它工作正常,除非找不到进程时显示错误消息。添加2 > nul无法解决问题,因为错误被丢弃了......

如何防止错误显示,并显示一些有意义的消息?

for %%i in (%procs%) do (
    TASKKILL /F /IM %%i > nul
    if "%ERRORLEVEL%"=="0" (
        echo %%i was stopped successfully
        echo.
    ) else (
        echo %%i was not started
    )
)

2 个答案:

答案 0 :(得分:1)

更改用于errorlevel检查的语法(表达式if errorlevel n表示如果errorlevel等于或大于n

for %%i in (%procs%) do (
    >nul 2>&1 TASKKILL /F /IM "%%~i" 
    if not errorlevel 1 (
        echo %%i was stopped successfully
    ) else (
        echo %%i was not started
    )
)

使用条件执行运算符(&& =如果上一个命令成功则执行,|| =如果上一个命令失败则执行

for %%i in (%procs%) do (
    >nul 2>&1 TASKKILL /F /IM "%%~i" && (
        echo %%i was stopped successfully
    ) || (
        echo %%i was not started
    )
)

使用延迟扩展(没有它,在解析完整个块时,将errorlevel读取操作替换为变量内的值,您无法检索更改的值)

setlocal enabledelayedexpansion
for %%i in (%procs%) do (
    >nul 2>&1 TASKKILL /F /IM "%%~i" 
    if !errorlevel!==0 (
        echo %%i was stopped successfully
    ) else (
        echo %%i was not started
    )
)

但请记住,所有这些样本都是简化。防爆。如果无法终止进程,taskkill也会失败。

答案 1 :(得分:0)

阅读EnableDelayedExpansion

  

延迟扩展将导致变量在执行时扩展   时间而不是在解析时,这个选项打开了   SETLOCAL命令。当延迟扩展实际上变量可以   使用!variable_name!引用(除了正常情况   %variable_name%)。

Setlocal EnableDelayedExpansion
for %%i in (%procs%) do (
    TASKKILL /F /IM %%i 1>nul 2>&1
    if "!ERRORLEVEL!"=="0" (
        echo %%i was stopped successfully
        echo.
    ) else (
        echo %%i was not started
    )
)

for %%i in (%procs%) do (
    TASKKILL /F /IM %%i 1>nul 2>&1
    if ERRORLEVEL 1 (
        echo %%i was not started
    ) else (
        echo %%i was stopped successfully
        echo.
    )
)

请注意,TASKKILL命令可能由于更多原因而失败,不仅因为进程不是runninq,例如如果你试图从一个未提升的cmd提示中杀死一个提升的进程。