Matt
Matt

Reputation: 67

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

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

Upvotes: 1

Views: 37

Answers (2)

MC ND
MC ND

Reputation: 70923

Changing the syntax used for errorlevel checking (the expression if errorlevel n means if errorlevel is equal or greater to 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)

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.

Upvotes: 1

JosefZ
JosefZ

Reputation: 30113

Read 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. When delayed expansion is in effect variables can be referenced using !variable_name! (in addition to the normal %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, e.g. if you are trying to kill an elevated process from an unelevated cmd prompt.

Upvotes: 0

Related Questions