[英]Check for errors, but don't show them
I have a tiny script for killing some processes.我有一个用于杀死某些进程的小脚本。 It works fine except when a process is not found it show the error message.它工作正常,除非找不到进程,它会显示错误消息。 Adding 2 > nul
won't solve the problem because the error is discarded ...添加2 > nul
不会解决问题,因为错误被丢弃...
How to prevent the error from showing, and show some meanningful message?如何防止错误显示,并显示一些有意义的消息?
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
)
)
Changing the syntax used for errorlevel
checking (the expression if errorlevel n
means if errorlevel is equal or greater to n )更改用于错误errorlevel
检查的语法(表达式if errorlevel n
表示错误级别是否等于或大于 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
)
)
Using conditional execution operators ( &&
= execute if the previous command was successful, ||
= execute if the previous command failed)使用条件执行运算符( &&
= 如果上一条命令成功则执行, ||
= 如果上一条命令失败则执行)
for %%i in (%procs%) do (
>nul 2>&1 TASKKILL /F /IM "%%~i" && (
echo %%i was stopped successfully
) || (
echo %%i was not started
)
)
Using delayed expansion (without it, with the errorlevel
read operation replaced with the value inside the variable when the full block was parsed, you can not retrieve the changed value)使用延迟扩展(没有它,当解析完整块时,错误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
)
)
But remember all this samples are a simplification.但请记住,所有这些示例都是一种简化。 Ex.前任。 taskkill
can also fail if the process can not be terminated.如果进程无法终止, taskkill
也可能失败。
Read EnableDelayedExpansion读取EnableDelayedExpansion
Delayed Expansion will cause variables to be expanded at execution time rather than at parse time, this option is turned on with the
SETLOCAL
command.延迟扩展将导致变量在执行时而不是在解析时扩展,此选项通过SETLOCAL
命令打开。 When delayed expansion is in effect variables can be referenced using!variable_name!
当延迟扩展生效时,可以使用!variable_name!
引用!variable_name!
(in addition to the normal%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
)
)
or或者
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.
)
)
Note that TASKKILL
command could fail for more reasons, not only for that a process is not runninq, eg if you are trying to kill an elevated process from an unelevated cmd
prompt.请注意, TASKKILL
命令可能会因更多原因而失败,不仅是因为进程未运行,例如,如果您试图从未提升的cmd
提示符处终止提升的进程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.