如何在Windows命令提示符中运行命令行应用程序,同时显示输出并将输出重定向到文件?
例如,如果我要运行命令dir > test.txt,这将把输出重定向到一个名为test.txt的文件,而不显示结果。
我如何写一个命令来显示输出并将输出重定向到Windows命令提示符中的文件,类似于Unix上的tee命令?
如何在Windows命令提示符中运行命令行应用程序,同时显示输出并将输出重定向到文件?
例如,如果我要运行命令dir > test.txt,这将把输出重定向到一个名为test.txt的文件,而不显示结果。
我如何写一个命令来显示输出并将输出重定向到Windows命令提示符中的文件,类似于Unix上的tee命令?
当前回答
@tori3852
我发现
dir > a.txt | type a.txt
没有工作(仅dir列表的前几行-怀疑某种进程分叉和第二部分,'type'命令在可怕的列表完成之前终止?), 所以我用了:
dir > z.txt && type z.txt
顺序命令,一个在第二个开始之前完成。
其他回答
我想对撒克逊德鲁斯的精彩回答进行一点扩展。
如上所述,您可以重定向当前目录中的可执行文件的输出,如下所示:
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解释。
Mtee是一个小型实用程序,它非常适合这个目的。它是免费的,源代码是开放的,而且很好用。
你可以在http://www.commandline.co.uk上找到它。
在批处理文件中用于显示输出并同时创建日志文件,语法如下所示:
someprocess | mtee /+ mylogfile.txt
其中/+表示附加输出。
当然,这假设您已经将mtee复制到PATH中的文件夹中。
如果你想在屏幕上真正看到一些东西,下面的步骤会有所帮助——即使批处理文件被重定向到一个文件。如果重定向到一个文件,也可以使用设备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
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”的文本文件中查看程序的屏幕输出
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.