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

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

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


当前回答

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”的文本文件中查看程序的屏幕输出

其他回答

一个简单的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中。

请注意,上面的错误处理方式并没有太多(任何东西!),实际上可能并不需要支持多个文件。

Mtee是一个小型实用程序,它非常适合这个目的。它是免费的,源代码是开放的,而且很好用。

你可以在http://www.commandline.co.uk上找到它。

在批处理文件中用于显示输出并同时创建日志文件,语法如下所示:

    someprocess | mtee /+ mylogfile.txt

其中/+表示附加输出。

当然,这假设您已经将mtee复制到PATH中的文件夹中。

这是可行的,尽管它有点丑陋:

dir >_ && type _ && type _ > a.txt

它比其他一些解决方案更灵活一些,因为它是一条一条地工作的,所以您也可以使用它来追加。我在批处理文件中经常使用这种方法来记录和显示消息:

ECHO Print line to screen and log to file.  >_ && type _ && type _ >> logfile.txt

是的,您可以只重复ECHO语句(一次用于屏幕,第二次重定向到日志文件),但这看起来同样糟糕,并且存在一些维护问题。至少这样您就不必在两个地方对消息进行更改。

注意_只是一个简短的文件名,所以你需要确保在批处理文件的末尾删除它(如果你使用的是批处理文件)。

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

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

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.