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

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

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


当前回答

另一种变化是分割管道,然后根据需要重新定向输出。

    @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

其他回答

有一个Win32端口的Unix tee命令,就是这样做的。见http://unxutils.sourceforge.net/或http://getgnuwin32.sourceforge.net/

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

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.

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

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

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

    someprocess | mtee /+ mylogfile.txt

其中/+表示附加输出。

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

看看这个:wintee

不需要cygwin。

不过,我确实遇到并报告了一些问题。

您还可以检查unxutils,因为它包含tee(不需要cygwin),但注意这里的输出EOL是类似unix的。

最后,但并非最不重要的是,如果你有PowerShell,你可以尝试Tee-Object。在PowerShell控制台中输入get-help tee-object获取更多信息。