如何在Windows命令提示符中运行命令行应用程序,同时显示输出并将输出重定向到文件?
例如,如果我要运行命令dir > test.txt,这将把输出重定向到一个名为test.txt的文件,而不显示结果。
我如何写一个命令来显示输出并将输出重定向到Windows命令提示符中的文件,类似于Unix上的tee命令?
如何在Windows命令提示符中运行命令行应用程序,同时显示输出并将输出重定向到文件?
例如,如果我要运行命令dir > test.txt,这将把输出重定向到一个名为test.txt的文件,而不显示结果。
我如何写一个命令来显示输出并将输出重定向到Windows命令提示符中的文件,类似于Unix上的tee命令?
当前回答
一个简单的c#控制台应用程序就可以做到这一点:
using System;
using System.Collections.Generic;
using System.IO;
namespace CopyToFiles
{
class Program
{
static void Main(string[] args)
{
var buffer = new char[100];
var outputs = new List<TextWriter>();
foreach (var file in args)
outputs.Add(new StreamWriter(file));
outputs.Add(Console.Out);
int bytesRead;
do
{
bytesRead = Console.In.ReadBlock(buffer, 0, buffer.Length);
outputs.ForEach(o => o.Write(buffer, 0, bytesRead));
} while (bytesRead == buffer.Length);
outputs.ForEach(o => o.Close());
}
}
}
要使用该命令,只需将source命令导入程序,并提供要将输出复制到的任何文件的路径。例如:
dir | CopyToFiles files1.txt files2.txt
将显示dir的结果,并将结果存储在files1.txt和files2.txt中。
请注意,上面的错误处理方式并没有太多(任何东西!),实际上可能并不需要支持多个文件。
其他回答
这是可行的,尽管它有点丑陋:
dir >_ && type _ && type _ > a.txt
它比其他一些解决方案更灵活一些,因为它是一条一条地工作的,所以您也可以使用它来追加。我在批处理文件中经常使用这种方法来记录和显示消息:
ECHO Print line to screen and log to file. >_ && type _ && type _ >> logfile.txt
是的,您可以只重复ECHO语句(一次用于屏幕,第二次重定向到日志文件),但这看起来同样糟糕,并且存在一些维护问题。至少这样您就不必在两个地方对消息进行更改。
注意_只是一个简短的文件名,所以你需要确保在批处理文件的末尾删除它(如果你使用的是批处理文件)。
不幸的是,没有这样的东西。
Windows控制台应用程序只有一个输出句柄。(嗯,有两个STDOUT, STDERR,但在这里不重要)>重定向输出通常写入控制台句柄到文件句柄。
如果你想要有某种多路复用,你必须使用一个外部应用程序,你可以将输出转移到它。然后,该应用程序可以再次写入文件和控制台。
这是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,所以答案使用perl: tee.pl
my $file = shift || "tee.dat";
open $output, ">", $file or die "unable to open $file as output: $!";
while(<STDIN>)
{
print $_;
print $output $_;
}
close $output;
目录| perl tee.pl 或 目录| perl tee.pl Dir .bat
粗糙且未经检验。
@tori3852
我发现
dir > a.txt | type a.txt
没有工作(仅dir列表的前几行-怀疑某种进程分叉和第二部分,'type'命令在可怕的列表完成之前终止?), 所以我用了:
dir > z.txt && type z.txt
顺序命令,一个在第二个开始之前完成。