如何在Windows命令提示符中运行命令行应用程序,同时显示输出并将输出重定向到文件?

例如,如果我要运行命令dir > test.txt,这将把输出重定向到一个名为test.txt的文件,而不显示结果。

我如何写一个命令来显示输出并将输出重定向到Windows命令提示符中的文件,类似于Unix上的tee命令?


当前回答

发送输出到控制台,附加到控制台日志,从当前命令删除输出

dir  >> usb-create.1 && type usb-create.1 >> usb-create.log | type usb-create.1 && del usb-create.1

其他回答

如果你想在屏幕上真正看到一些东西,下面的步骤会有所帮助——即使批处理文件被重定向到一个文件。如果重定向到一个文件,也可以使用设备CON

例子:

ECHO first line on normal stdout. maybe redirected
ECHO second line on normal stdout again. maybe redirected
ECHO third line is to ask the user. not redirected  >CON
ECHO fourth line on normal stdout again. maybe redirected

另请参阅良好的重定向说明:http://www.p-dd.com/chapter7-page14.html

另一种选择是在程序中tee stdout到stderr:

在java中:

System.setOut(new PrintStream(new TeeOutputStream(System.out, System.err)));

然后,在你的dos批处理文件:java程序> log.txt

标准输出将转到日志文件,标准derr(相同的数据)将显示在控制台上。

有一个Win32端口的Unix tee命令,就是这样做的。见http://unxutils.sourceforge.net/或http://getgnuwin32.sourceforge.net/

我想对撒克逊德鲁斯的精彩回答进行一点扩展。

如上所述,您可以重定向当前目录中的可执行文件的输出,如下所示:

powershell ".\something.exe | tee test.txt"

但是,这只将stdout记录到test.txt。它也不记录stderr。

最明显的解决方法是使用如下内容:

powershell ".\something.exe 2>&1 | tee test.txt"

然而,这并不适用于所有的前任。一些东西。前任们会把2>&1解释为争吵而失败。正确的解决方案是在something.exe及其开关和参数周围只使用撇号,如下所示:

powershell ".\something.exe --switch1 --switch2 … arg1 arg2 …" 2^>^&1 ^| tee test.txt

但是请注意,在这种情况下,您必须转义特殊的cmd-shell字符“>&|”,每个字符都有一个“^”,这样它们只能由powershell解释。

这是MTS之前回答的一个变化,但是它增加了一些可能对其他人有用的功能。下面是我使用的方法:

A command is set as a variable, that can be used later throughout the code, to output to the command window and append to a log file, using set _Temp_Msg_Cmd= the command has escaped redirection using the carrot ^ character so that the commands are not evaluated initially A temporary file is created with a filename similar to the batch file being run called %~n0_temp.txt that uses command line parameter extension syntax %~n0 to get the name of the batch file. The output is appended to a separate log file %~n0_log.txt

下面是命令的顺序:

输出和错误消息被发送到临时文件^> %~n0_temp.txt 2^>^&1 临时文件的内容是: 附加到日志文件^&类型%~n0_temp.txt ^>^> %~n0_log.txt 输出到命令窗口^&键入%~n0_temp.txt 删除带有该消息的临时文件^& del /Q /F %~n0_temp.txt

下面是例子:

设置_Temp_Msg_Cmd = ^ > % ~ n0_temp.txt 2 ^ > ^ & 1 ^ & % ~型n0_temp.txt ^ > ^ > % ~ n0_log.txt ^ & % ~型n0_temp.txt ^ & del / Q / F % ~ n0_temp.txt

这样,命令就可以简单地附加在批处理文件中后面的命令之后,看起来更干净:

echo test message %_Temp_Msg_Cmd%

这也可以添加到其他命令的末尾。据我所知,当消息有多行时,它将工作。例如,如果有错误消息,以下命令将输出两行:

net使用M: /D /Y %_Temp_Msg_Cmd%