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

查看:41
本文介绍了如何使 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 抑制标准输出并正常工作,例如用于抑制 1 个文件复制. copy 命令的消息.另一种语法是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.因此,要抑制 DEL 在未找到指定文件时打印的 File 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天全站免登陆