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

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

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


当前回答

这是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%

其他回答

我刚刚找到了一种方法来使用perl作为替代,例如: CMD1 | perl -ne "print $_;打印STDERR $_;"2 >输出。三通

I agree with Brian Rasmussen, the unxutils port is the easiest way to do this. In the Batch Files section of his Scripting Pages Rob van der Woude provides a wealth of information on the use MS-DOS and CMD commands. I thought he might have a native solution to your problem and after digging around there I found TEE.BAT, which appears to be just that, an MS-DOS batch language implementation of tee. It is a pretty complex-looking batch file and my inclination would still be to use the unxutils port.

我如何显示和重定向输出 到一个文件。假设我使用dos dir > test.txt,执行此命令 将重定向输出到文件test.txt 不显示结果。如何 写一个命令来显示输出 并将输出重定向到文件使用 DOS,即windows命令提示符,而不是 在UNIX / LINUX。

您可能会发现biterscripting (http://www.biterscripting.com)中的这些命令很有用。

var str output
lf > $output
echo $output                            # Will show output on screen.
echo $output > "test.txt"               # Will write output to file test.txt.
system start "test.txt"                 # Will open file test.txt for viewing/editing.

https://cygwin.com/install 点击“setup- x86_exe”链接 运行安装程序 在~第二页,选择一个“镜像”来下载(我找了一个。edu域名) 我同意了标准选项 Cygwin快速完成安装 打开cmd 输入c:\cygwin64\bin\script.exe并输入 输入cmd并输入 运行程序 输入exit和enter(退出Cygwin的cmd.exe) 输入exit和enter(退出Cygwin的script.exe) 在名为“typescript”的文本文件中查看程序的屏幕输出

为了扩展davor的答案,你可以像这样使用PowerShell:

powershell "dir | tee test.txt"

如果你试图重定向当前目录下的exe的输出,你需要在文件名上使用。\,例如:

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