如何在Windows命令提示符中运行命令行应用程序,同时显示输出并将输出重定向到文件?
例如,如果我要运行命令dir > test.txt,这将把输出重定向到一个名为test.txt的文件,而不显示结果。
我如何写一个命令来显示输出并将输出重定向到Windows命令提示符中的文件,类似于Unix上的tee命令?
如何在Windows命令提示符中运行命令行应用程序,同时显示输出并将输出重定向到文件?
例如,如果我要运行命令dir > test.txt,这将把输出重定向到一个名为test.txt的文件,而不显示结果。
我如何写一个命令来显示输出并将输出重定向到Windows命令提示符中的文件,类似于Unix上的tee命令?
当前回答
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.
为了扩展davor的答案,你可以像这样使用PowerShell:
powershell "dir | tee test.txt"
如果你试图重定向当前目录下的exe的输出,你需要在文件名上使用。\,例如:
powershell ".\something.exe | tee test.txt"
不幸的是,没有这样的东西。
Windows控制台应用程序只有一个输出句柄。(嗯,有两个STDOUT, STDERR,但在这里不重要)>重定向输出通常写入控制台句柄到文件句柄。
如果你想要有某种多路复用,你必须使用一个外部应用程序,你可以将输出转移到它。然后,该应用程序可以再次写入文件和控制台。
有一个Win32端口的Unix tee命令,就是这样做的。见http://unxutils.sourceforge.net/或http://getgnuwin32.sourceforge.net/
另一种变化是分割管道,然后根据需要重新定向输出。
@echo off
for /f "tokens=1,* delims=:" %%P in ('findstr /n "^"') do (
echo(%%Q
echo(%%Q>&3
)
@exit/b %errorlevel%
将上述内容保存到.bat文件中。它还将文件流1上的文本输出分割到文件流3,您可以根据需要重定向。在下面的例子中,我将上面的脚本称为splitPipe.bat…
dir | splitPipe.bat 1>con 2>&1 3>my_stdout.log
splitPipe.bat 2>nul < somefile.txt