简体   繁体   中英

Batch file still prints error messages after using @echo off and >nul

I wrote a batch file to close all programs before the computer attempts to shut down, using the taskkill function to end specific programs. I used @echo off at the start, and wrote >null at the end of my taskkill function, but I still got a command prompt window detailing errors where taskkill did not find a program that was told to be closed. I am running Windows 10, if that helps.

Here are the two lines of code that are misbehaving:

@echo off 
taskkill -f -t -im chrome.exe -im skype.exe -im WINWORD.exe >nul

And here is the full batch file if you want to see it:

REM Closes all programs, THEN turns off computer
@echo off 
::  If you want to make a command prompt window appear, change this to “@echo on”
taskkill -f -t -im chrome.exe -im skype.exe -im WINWORD.exe >nul
::  Add all your program names here and an “/im” before them. Also if you want them to give you prompts before 
::  shutting down, delete the "-f". Delete the ">nul"s if you want error messages
timeout 4 >nul
::  This will make the computer wait for between 3 and 4 seconds. This is designed for slower computers,
::  you can make the time delay less if you want
shutdown.exe -p -f >nul
::  This shuts down computer. -p makes it not have a time delay or display a message, -f quits programs just in case
exit 
::  Exits in case it prevents computer from shutting down

Thanks

StdOut and StdError are different. You have only redirected StdOut.

To redirect StdError to wherever StdOut is going, put somewhere on the line

2>&1

Cmd actually changes > to 1> (you'll see this in your batch if you remove echo off ).

To redirect StdError to somewhere different

2> filename.txt

0=keyboard
1=screen for normal output
2=screen for error
3-9=whatever other files Cmd has open

The >nul discards output sent to stdout, or file descriptor 1. Most commands send error messages to a separate channel, stderr (2). You can redirect stderr to nul using 2> nul . (Make sure there is no space between the 2 and the > ; otherwise, the 2 will be taken as a parameter to the command.) To discard both stderr and stdout at the same time it is usual to do this:

taskkill ... >nul 2>&1

which means redirect stdout to nul and also treat stderr the same way as stdout.

Try like that :

@echo off
set process=mshta.exe,chrome.exe,calc.exe,skype.exe,iexplore.exe
For %%a in (%process%) Do Call :KillMyProcess %%a

:KillMyProcess
Taskkill /IM "%1" /F >nul 2>&1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM