如何使Windows批处理脚本完全静音? [英] How do I make a Windows batch script completely silent?

查看:575
本文介绍了如何使Windows批处理脚本完全静音?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题的变体问世了几代人,但是尽管编写了一些相当复杂的Windows脚本,但我似乎仍然找不到如何使它们保持沉默的方法.

There has been variants of this question asked for generations, but despite writing some quite complicated Windows scripts, I can't seem to find out how to make them actually silent.

以下是我当前脚本之一的摘录:

The following is an excerpt from one of my current scripts:

@ECHO OFF
SET scriptDirectory=%~dp0
COPY %scriptDirectory%test.bat %scriptDirectory%test2.bat
FOR /F %%f IN ('dir /B "%scriptDirectory%*.noext"') DO (
del "%scriptDirectory%%%f"
)
ECHO

其结果是:

C:\Temp> test.bat
        1 file(s) copied.
File Not Found
Echo is off.

C:\Temp>

而已复制1个文件".只是令人讨厌,找不到文件"使用户认为出了点问题(没有错-没有文件是可以的).

Whereas the "1 file(s) copied." is just annoying, the "File Not Found" makes the user think that something has gone wrong (which it hasn't - no files is fine).

推荐答案

要抑制输出,请使用重定向到NUL.

To suppress output, use redirection to NUL.

控制台命令使用两种输出:

There are two kinds of output that console commands use:

  • 标准输出或stdout

标准错误或stderr.

在这两个中,stdout被更频繁地使用,既被内部命令(例如copy)使用,又被控制台实用程序使用,或者被 external 命令(例如find等)使用.就像第三方控制台程序一样.

Of the two, stdout is used more often, both by internal commands, like copy, and by console utilities, or external commands, like find and others, as well as by third-party console programs.

>NUL抑制标准输出并正常工作,例如用于禁止copy命令的1 file(s) copied.消息.另一种语法是1>NUL.所以,

>NUL suppresses the standard output and works fine e.g. for suppressing the 1 file(s) copied. message of the copy command. An alternative syntax is 1>NUL. So,

COPY file1 file2 >NUL

COPY file1 file2 1>NUL

>NUL COPY file1 file2

1>NUL COPY file1 file2

禁止所有COPY的标准输出.

要禁止显示通常打印到stderr的错误消息,请改用2>NUL.因此,要抑制在找不到指定文件时显示DELFile Not Found消息,只需在命令行的开头或结尾添加2>NUL即可:

To suppress error messages, which are typically printed to stderr, use 2>NUL instead. So, to suppress a File Not Found message that DEL prints when, well, the specified file is not found, just add 2>NUL either at the beginning or at the end of the command line:

DEL file 2>NUL

2>NUL DEL file

尽管有时候,最好像在自己的解决方案中一样,在删除文件之前先实际验证文件是否存在.但是请注意,您不需要使用循环逐个删除文件.您可以使用一个命令来删除批次:

Although sometimes it may be a better idea to actually verify whether the file exists before trying to delete it, like you are doing in your own solution. Note, however, that you don't need to delete the files one by one, using a loop. You can use a single command to delete the lot:

IF EXIST "%scriptDirectory%*.noext" DEL "%scriptDirectory%*.noext"

这篇关于如何使Windows批处理脚本完全静音?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆