显示Windows命令提示符输出并将其重定向到文件

时间:2021-02-27 00:06:13

How can I run a command-line application in the Windows command prompt and have the output both displayed and redirected to a file at the same time?

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

If, for example, I were to run the command dir > test.txt, this would redirect output to a file called test.txt without displaying the results.

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

How could I write a command to display the output and redirect output to a file in the Windows command prompt, similar to the tee command on Unix?

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

28 个解决方案

#1


I was able to find a solution/workaround of redirecting output to a file and then to the console:

我能够找到将输出重定向到文件然后重定向到控制台的解决方案/解决方法:

dir > a.txt | type a.txt

where dir is the command which output needs to be redirected, a.txt a file where to store output.

其中dir是需要重定向输出的命令,a.txt是存储输出的文件。

#2


To expand on davor's answer, you can use PowerShell like this:

要扩展davor的答案,您可以像这样使用PowerShell:

powershell "dir | tee test.txt"

If you're trying to redirect the output of an exe in the current directory, you need to use .\ on the filename, eg:

如果您尝试在当前目录中重定向exe的输出,则需要在文件名上使用。\,例如:

powershell ".\something.exe | tee test.txt"

#3


There's a Win32 port of the Unix tee command, that does exactly that. See http://unxutils.sourceforge.net/ or http://getgnuwin32.sourceforge.net/

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

#4


Check this out: wintee

看看这个:wintee

No need for cygwin.

不需要cygwin。

I did encounter and report some issues though.

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

Also you might check unxutils because it contains tee (and no need for cygwin), but beware that output EOL's are UNIX-like here.

你也可以检查unxutils,因为它包含tee(并且不需要cygwin),但要注意输出EOL在这里类似于UNIX。

Last, but not least, is if you have PowerShell, you could try Tee-Object. Type get-help tee-object in PowerShell console for more info.

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

#5


@tori3852

I found that

我找到

dir > a.txt | type a.txt

didn't work (first few lines of dir listing only - suspect some sort of process forking and the second part, the 'type' command terminated before the dire listing had completed? ), so instead I used:

没有工作(前几行dir列表 - 怀疑某种过程分叉和第二部分,'type'命令在可怕列表完成之前终止?),所以相反我使用:

dir > z.txt && type z.txt

which did - sequential commands, one completes before the second starts.

做了 - 顺序命令,一个在第二个开始之前完成。

#6


Unfortunately there is no such thing.

不幸的是没有这样的事情。

Windows console applications only have a single output handle. (Well, there are two STDOUT, STDERR but it doesn't matter here) The > redirects the output normally written to the console handle to a file handle.

Windows控制台应用程序只有一个输出句柄。 (好吧,有两个STDOUT,STDERR但这里没关系)>将通常写入控制台句柄的输出重定向到文件句柄。

If you want to have some kind of multiplexing you have to use an external application which you can divert the output to. This application then can write to a file and to the console again.

如果你想要某种多路复用,你必须使用一个外部应用程序,你可以将输出转移到。然后,此应用程序可以再次写入文件和控制台。

#7


A simple C# console application would do the trick:

一个简单的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());
        }
    }
}

To use this you just pipe the source command into the program and provide the path of any files you want to duplicate the output to. For example:

要使用它,只需将source命令传递给程序,并提供要复制输出的任何文件的路径。例如:

dir | CopyToFiles files1.txt files2.txt 

Will display the results of dir as well as store the results in both files1.txt and files2.txt.

将显示dir的结果,并将结果存储在files1.txt和files2.txt中。

Note that there isn't much (anything!) in the way of error handling above, and supporting multiple files may not actually be required.

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

#8


This works, though it's a bit ugly:

虽然它有点难看,但这有效:

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

It's a little more flexible than some of the other solutions, in that it works statement-by-statement so you can use it to append as well. I use this quite a bit in batch files to log and display messages:

它比其他一些解决方案更灵活,因为它可以逐语句地工作,因此您也可以使用它进行追加。我在批处理文件中使用了相当多的东西来记录和显示消息:

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

Yes, you could just repeat the ECHO statement (once for the screen and the second time redirecting to the logfile), but that looks just as bad and is a bit of a maintenance issue. At least this way you don't have to make changes to messages in two places.

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

Note that _ is just a short filename, so you'll need to make sure to delete it at the end of your batch file (if you're using a batch file).

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

#9


mtee is a small utility which works very well for this purpose. It's free, source is open, and it Just Works.

mtee是一个很小的实用工具,可以很好地用于此目的。它是免费的,源是开放的,它只是工作。

You can find it at http://www.commandline.co.uk.

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

Used in a batch file to display output AND create a log file simultaneously, the syntax looks like this:

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

    someprocess | mtee /+ mylogfile.txt

Where /+ means to append output.

其中/ +表示附加输出。

This assumes that you have copied mtee into a folder which is in the PATH, of course.

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

#10


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.

我同意Brian Rasmussen的观点,unxutils端口是最简单的方法。在他的Scripting Pages的Batch Files部分中,Rob van der Woude提供了有关使用MS-DOS和CMD命令的大量信息。我认为他可能有一个解决你的问题的原生解决方案,并在那里挖掘后,我发现TEE.BAT,这似乎只是一个MS-DOS批量语言实现的发球台。这是一个非常复杂的批处理文件,我的倾向仍然是使用unxutils端口。

#11


I’d like to expand a bit on Saxon Druce’s excellent answer.

我想对Saxon Druce的优秀答案进行一些扩展。

As stated, you can redirect the output of an executable in the current directory like so:

如上所述,您可以在当前目录中重定向可执行文件的输出,如下所示:

powershell ".\something.exe | tee test.txt"

However, this only logs stdout to test.txt. It doesn’t also log stderr.

但是,这只会将stdout记录到test.txt。它也没有记录stderr。

The obvious solution would be to use something like this:

显而易见的解决方案是使用这样的东西:

powershell ".\something.exe 2>&1 | tee test.txt"

However, this won’t work for all something.exes. Some something.exes will interpret the 2>&1 as an argument and fail. The correct solution is to instead only have apostrophes around the something.exe and it’s switches and arguments, like so:

但是,这不适用于所有的东西.exes。 some.exes会将2>&1解释为参数并失败。正确的解决方案是在something.exe周围只有撇号,它的开关和参数如下:

powershell ".\something.exe --switch1 --switch2 … arg1 arg2 …" 2>&1 | tee test.txt

#12


If you have cygwin in your windows environment path you can use:

如果您在Windows环境路径中有cygwin,则可以使用:

 dir > a.txt | tail -f a.txt

#13


dir 1>a.txt 2>&1 | type a.txt

dir 1> a.txt 2>&1 |输入a.txt

This will help to redirect both STDOUT and STDERR

这将有助于重定向STDOUT和STDERR

#14


I was also looking for the same solution, after a little try, I was successfully able to achieve that in Command Prompt. Here is my solution :

我也在寻找相同的解决方案,经过一些尝试,我成功地在命令提示符中实现了这一点。这是我的解决方案:

@Echo off
for /f "Delims=" %%a IN (xyz.bat) do (
%%a > _ && type _ && type _ >> log.txt
)
@Echo on

It even captures any PAUSE command as well.

它甚至还捕获任何PAUSE命令。

#15


send output to console, append to console log, delete output from current command

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

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

#16


Here's a sample of what I've used based on one of the other answers

这是我根据其他答案之一使用的样本

@echo off
REM SOME CODE
set __ERROR_LOG=c:\errors.txt
REM set __IPADDRESS=x.x.x.x

REM Test a variable
if not defined __IPADDRESS (
     REM Call function with some data and terminate
     call :TEE %DATE%,%TIME%,IP ADDRESS IS NOT DEFINED
     goto :EOF
)

REM If test happens to be successful, TEE out a message and end script.
call :TEE Script Ended Successful
goto :EOF


REM THE TEE FUNCTION
:TEE
for /f "tokens=*" %%Z in ("%*") do (
     >  CON ECHO.%%Z
     >> "%__ERROR_LOG%" ECHO.%%Z
     goto :EOF
)

#17


@echo on

set startDate=%date%
set startTime=%time%

set /a sth=%startTime:~0,2%
set /a stm=1%startTime:~3,2% - 100
set /a sts=1%startTime:~6,2% - 100


fullprocess.bat > C:\LOGS\%startDate%_%sth%.%stm%.%sts%.LOG | fullprocess.bat

This will create a log file with the current datetime and you can the console lines during the process

这将创建一个包含当前日期时间的日志文件,您可以在此过程中使用控制台行

#18


I know this is a very old topic, but in previous answers there is not a full implementation of a real time Tee written in Batch. My solution below is a Batch-JScript hybrid script that use the JScript section just to get the output from the piped command, but the processing of the data is done in the Batch section. This approach have the advantage that any Batch programmer may modify this program to fit specific needs. This program also correctly process the output of CLS command produced by other Batch files, that is, it clear the screen when CLS command output is detected.

我知道这是一个非常古老的主题,但在以前的答案中,并没有完全实现以批处理方式编写的实时Tee。我的解决方案是Batch-JScript混合脚本,它使用JScript部分来获取管道命令的输出,但数据处理在Batch部分完成。这种方法的优点是任何Batch程序员都可以修改该程序以满足特定需求。该程序还可以正确处理其他批处理文件生成的CLS命令的输出,即在检测到CLS命令输出时清除屏幕。

@if (@CodeSection == @Batch) @then


@echo off
setlocal EnableDelayedExpansion

rem APATee.bat: Asynchronous (real time) Tee program, Batch-JScript hybrid version
rem Antonio Perez Ayala

rem The advantage of this program is that the data management is written in Batch code,
rem so any Batch programmer may modify it to fit their own needs.
rem As an example of this feature, CLS command is correctly managed

if "%~1" equ "" (
   echo Duplicate the Stdout output of a command in the screen and a disk file
   echo/
   echo anyCommand ^| APATee teeFile.txt [/A]
   echo/
   echo If /A switch is given, anyCommand output is *appended* to teeFile.txt
   goto :EOF
)

if "%2" equ ":TeeProcess" goto TeeProcess

rem Get the output of CLS command
for /F %%a in ('cls') do set "cls=%%a"

rem If /A switch is not provided, delete the file that receives Tee output
if /I "%~2" neq "/A" if exist %1 del %1

rem Create the semaphore-signal file and start the asynchronous Tee process
echo X > Flag.out
if exist Flag.in del Flag.in
Cscript //nologo //E:JScript "%~F0" | "%~F0" %1 :TeeProcess
del Flag.out
goto :EOF

:TeeProcess
   rem Wait for "Data Available" signal
   if not exist Flag.in goto TeeProcess
   rem Read the line sent by JScript section
   set line=
   set /P line=
   rem Set "Data Read" acknowledgement
   ren Flag.in Flag.out
   rem Check for the standard "End Of piped File" mark
   if "!line!" equ ":_EOF_:" exit /B
   rem Correctly manage CLS command
   if "!line:~0,1!" equ "!cls!" (
      cls
      set "line=!line:~1!"
   )
   rem Duplicate the line in Stdout and the Tee output file
   echo(!line!
   echo(!line!>> %1
goto TeeProcess


@end


// JScript section

var fso = new ActiveXObject("Scripting.FileSystemObject");
// Process all lines of Stdin
while ( ! WScript.Stdin.AtEndOfStream ) {
   // Read the next line from Stdin
   var line = WScript.Stdin.ReadLine();
   // Wait for "Data Read" acknowledgement
   while ( ! fso.FileExists("Flag.out") ) {
      WScript.Sleep(10);
   }
   // Send the line to Batch section
   WScript.Stdout.WriteLine(line);
   // Set "Data Available" signal
   fso.MoveFile("Flag.out", "Flag.in");
}
// Wait for last "Data Read" acknowledgement
while ( ! fso.FileExists("Flag.out") ) {
      WScript.Sleep(10);
}
// Send the standard "End Of piped File" mark
WScript.Stdout.WriteLine(":_EOF_:");
fso.MoveFile("Flag.out", "Flag.in");

#19


Something like this should do what you need?

这样的事情应该做你需要的吗?

%DATE%_%TIME% > c:\a.txt & type c:\a.txt
ipconfig >> c:\a.txt & type c:\a.txt
ping localhost >> c:\a.txt & type c:\a.txt
pause

#20


This is a variation on a previous answer by MTS, however it adds some functionality that might be useful to others. Here is the method that I used:

这是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
    • 该命令已使用胡萝卜^字符转义重定向,因此最初不会评估命令

  • 命令被设置为变量,可以在以后的整个代码中使用,输出到命令窗口并附加到日志文件,使用set _Temp_Msg_Cmd =命令已使用胡萝卜^字符转义重定向,因此命令不是最初评估

  • 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.
  • 创建一个临时文件,其文件名类似于正在运行的批处理文件,名为%~n0_temp.txt,它使用命令行参数扩展语法%~n0来获取批处理文件的名称。

  • The output is appended to a separate log file %~n0_log.txt
  • 输出附加到单独的日志文件%~n0_log.txt

Here is the sequence of commands:

这是命令序列:

  1. The output and error messages are sent to the temporary file ^> %~n0_temp.txt 2^>^&1
  2. 输出和错误消息将发送到临时文件^>%~n0_temp.txt 2 ^> ^&1

  3. The content of the temporary file is then both:
    • appended to the logfile ^& type %~n0_temp.txt ^>^> %~n0_log.txt
    • 附加到日志文件^&type%~n0_temp.txt ^> ^>%~n0_log.txt

    • output to the command window ^& type %~n0_temp.txt
    • 输出到命令窗口^&键入%~n0_temp.txt

  4. 然后临时文件的内容:附加到日志文件^&输入%~n0_temp.txt ^> ^>%~n0_log.txt输出到命令窗口^&type%~n0_temp.txt

  5. The temporary file with the message is deleted ^& del /Q /F %~n0_temp.txt
  6. 带有消息的临时文件将被删除^&del / Q / F%~n0_temp.txt

Here is the example:

这是一个例子:

set _Temp_Msg_Cmd= ^> %~n0_temp.txt 2^>^&1 ^& type %~n0_temp.txt ^>^> %~n0_log.txt ^& type %~n0_temp.txt ^& del /Q /F %~n0_temp.txt

set _Temp_Msg_Cmd = ^>%~n0_temp.txt 2 ^> ^&1 ^&type%~n0_temp.txt ^> ^>%~n0_log.txt ^&type%~n0_temp.txt ^&del / Q / F%~n0_temp 。文本

This way then the command can simply be appended after later commands in a batch file that looks a lot cleaner:

这样,命令可以简单地在批处理文件中的后续命令之后附加,该批处理文件看起来更清晰:

echo test message %_Temp_Msg_Cmd%

echo测试消息%_Temp_Msg_Cmd%

This can be added to the end of other commands as well. As far as I can tell it will work when messages have multiple lines. For example the following command outputs two lines if there is an error message:

这也可以添加到其他命令的末尾。据我所知,当消息有多行时它将起作用。例如,如果出现错误消息,则以下命令输出两行:

net use M: /D /Y %_Temp_Msg_Cmd%

净使用M:/ D / Y%_Temp_Msg_Cmd%

#21


I use a batch subroutine with a "for" statement to get the command output one line at a time and both write that line to a file and output it to the console.

我使用带有“for”语句的批处理子例程来一次获取一行命令输出,并将该行写入文件并将其输出到控制台。

@echo off
set logfile=test.log

call :ExecuteAndTee dir C:\Program Files

Exit /B 0

:ExecuteAndTee
setlocal enabledelayedexpansion
echo Executing '%*'
  for /f "delims=" %%a in ('%* 2^>^&1') do (echo.%%a & echo.%%a>>%logfile%)
endlocal
Exit /B 0

#22


Following helps if you want something really seen on the screen - even if the batch file was redirected to a file. The device CON maybe used also if redirected to a file

如果你想要在屏幕上看到的东西,即使批量文件被重定向到文件,以下内容也会有所帮助。如果重定向到文件,也可以使用设备CON

Example:

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

Also see good redirection description: http://www.p-dd.com/chapter7-page14.html

另请参阅良好的重定向说明:http://www.p-dd.com/chapter7-page14.html

#23


How do I display and redirect output to a file. Suppose if I use dos command, dir > test.txt ,this command will redirect output to file test.txt without displaying the results. how to write a command to display the output and redirect output to a file using DOS i.e., windows command prompt, not in UNIX/LINUX.

如何显示输出并将其重定向到文件。假设我使用dos命令dir> test.txt,此命令将输出重定向到文件test.txt而不显示结果。如何编写命令来显示输出并使用DOS将输出重定向到文件,即Windows命令提示符,而不是在UNIX / LINUX中。

You may find these commands in biterscripting ( http://www.biterscripting.com ) useful.

您可能会发现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.

#24


This works in real time but is also kind a ugly and the performance is slow. Not well tested either:

这实时工作,但也很难看,性能很慢。尚未经过充分测试:

@echo off
cls
SET MYCOMMAND=dir /B
ECHO File called 'test.bat' > out.txt
for /f "usebackq delims=" %%I in (`%MYCOMMAND%`) do (
  ECHO %%I
  ECHO %%I >> out.txt
) 
pause

#25


An alternative is to tee stdout to stderr within your program:

另一种方法是在程序中将stdout发送到stderr:

in java:

System.setOut(new PrintStream(new TeeOutputStream(System.out, System.err)));

Then, in your dos batchfile: java program > log.txt

然后,在dos batchfile中:java program> log.txt

The stdout will go to the logfile and the stderr (same data) will show on the console.

stdout将转到日志文件,stderr(相同的数据)将显示在控制台上。

#26


Just like unix

就像unix一样

dir | tee a.txt

dir | tee a.txt

does work On windows XP, it requires mksnt installed

工作在Windows XP上,它需要安装mksnt

It displayes on the promt as well as appends to the file

它显示在promt上并附加到文件中

#27


I install perl on most of my machines so an answer using perl: tee.pl

我在我的大多数机器上安装了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;

dir | perl tee.pl or dir | perl tee.pl dir.bat

dir | perl tee.pl或dir | perl tee.pl dir.bat

crude and untested.

原油和未经测试。

#28


try this:
dir > test.txt & type test.txt

试试这个:dir> test.txt&type test.txt

#1


I was able to find a solution/workaround of redirecting output to a file and then to the console:

我能够找到将输出重定向到文件然后重定向到控制台的解决方案/解决方法:

dir > a.txt | type a.txt

where dir is the command which output needs to be redirected, a.txt a file where to store output.

其中dir是需要重定向输出的命令,a.txt是存储输出的文件。

#2


To expand on davor's answer, you can use PowerShell like this:

要扩展davor的答案,您可以像这样使用PowerShell:

powershell "dir | tee test.txt"

If you're trying to redirect the output of an exe in the current directory, you need to use .\ on the filename, eg:

如果您尝试在当前目录中重定向exe的输出,则需要在文件名上使用。\,例如:

powershell ".\something.exe | tee test.txt"

#3


There's a Win32 port of the Unix tee command, that does exactly that. See http://unxutils.sourceforge.net/ or http://getgnuwin32.sourceforge.net/

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

#4


Check this out: wintee

看看这个:wintee

No need for cygwin.

不需要cygwin。

I did encounter and report some issues though.

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

Also you might check unxutils because it contains tee (and no need for cygwin), but beware that output EOL's are UNIX-like here.

你也可以检查unxutils,因为它包含tee(并且不需要cygwin),但要注意输出EOL在这里类似于UNIX。

Last, but not least, is if you have PowerShell, you could try Tee-Object. Type get-help tee-object in PowerShell console for more info.

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

#5


@tori3852

I found that

我找到

dir > a.txt | type a.txt

didn't work (first few lines of dir listing only - suspect some sort of process forking and the second part, the 'type' command terminated before the dire listing had completed? ), so instead I used:

没有工作(前几行dir列表 - 怀疑某种过程分叉和第二部分,'type'命令在可怕列表完成之前终止?),所以相反我使用:

dir > z.txt && type z.txt

which did - sequential commands, one completes before the second starts.

做了 - 顺序命令,一个在第二个开始之前完成。

#6


Unfortunately there is no such thing.

不幸的是没有这样的事情。

Windows console applications only have a single output handle. (Well, there are two STDOUT, STDERR but it doesn't matter here) The > redirects the output normally written to the console handle to a file handle.

Windows控制台应用程序只有一个输出句柄。 (好吧,有两个STDOUT,STDERR但这里没关系)>将通常写入控制台句柄的输出重定向到文件句柄。

If you want to have some kind of multiplexing you have to use an external application which you can divert the output to. This application then can write to a file and to the console again.

如果你想要某种多路复用,你必须使用一个外部应用程序,你可以将输出转移到。然后,此应用程序可以再次写入文件和控制台。

#7


A simple C# console application would do the trick:

一个简单的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());
        }
    }
}

To use this you just pipe the source command into the program and provide the path of any files you want to duplicate the output to. For example:

要使用它,只需将source命令传递给程序,并提供要复制输出的任何文件的路径。例如:

dir | CopyToFiles files1.txt files2.txt 

Will display the results of dir as well as store the results in both files1.txt and files2.txt.

将显示dir的结果,并将结果存储在files1.txt和files2.txt中。

Note that there isn't much (anything!) in the way of error handling above, and supporting multiple files may not actually be required.

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

#8


This works, though it's a bit ugly:

虽然它有点难看,但这有效:

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

It's a little more flexible than some of the other solutions, in that it works statement-by-statement so you can use it to append as well. I use this quite a bit in batch files to log and display messages:

它比其他一些解决方案更灵活,因为它可以逐语句地工作,因此您也可以使用它进行追加。我在批处理文件中使用了相当多的东西来记录和显示消息:

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

Yes, you could just repeat the ECHO statement (once for the screen and the second time redirecting to the logfile), but that looks just as bad and is a bit of a maintenance issue. At least this way you don't have to make changes to messages in two places.

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

Note that _ is just a short filename, so you'll need to make sure to delete it at the end of your batch file (if you're using a batch file).

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

#9


mtee is a small utility which works very well for this purpose. It's free, source is open, and it Just Works.

mtee是一个很小的实用工具,可以很好地用于此目的。它是免费的,源是开放的,它只是工作。

You can find it at http://www.commandline.co.uk.

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

Used in a batch file to display output AND create a log file simultaneously, the syntax looks like this:

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

    someprocess | mtee /+ mylogfile.txt

Where /+ means to append output.

其中/ +表示附加输出。

This assumes that you have copied mtee into a folder which is in the PATH, of course.

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

#10


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.

我同意Brian Rasmussen的观点,unxutils端口是最简单的方法。在他的Scripting Pages的Batch Files部分中,Rob van der Woude提供了有关使用MS-DOS和CMD命令的大量信息。我认为他可能有一个解决你的问题的原生解决方案,并在那里挖掘后,我发现TEE.BAT,这似乎只是一个MS-DOS批量语言实现的发球台。这是一个非常复杂的批处理文件,我的倾向仍然是使用unxutils端口。

#11


I’d like to expand a bit on Saxon Druce’s excellent answer.

我想对Saxon Druce的优秀答案进行一些扩展。

As stated, you can redirect the output of an executable in the current directory like so:

如上所述,您可以在当前目录中重定向可执行文件的输出,如下所示:

powershell ".\something.exe | tee test.txt"

However, this only logs stdout to test.txt. It doesn’t also log stderr.

但是,这只会将stdout记录到test.txt。它也没有记录stderr。

The obvious solution would be to use something like this:

显而易见的解决方案是使用这样的东西:

powershell ".\something.exe 2>&1 | tee test.txt"

However, this won’t work for all something.exes. Some something.exes will interpret the 2>&1 as an argument and fail. The correct solution is to instead only have apostrophes around the something.exe and it’s switches and arguments, like so:

但是,这不适用于所有的东西.exes。 some.exes会将2>&1解释为参数并失败。正确的解决方案是在something.exe周围只有撇号,它的开关和参数如下:

powershell ".\something.exe --switch1 --switch2 … arg1 arg2 …" 2>&1 | tee test.txt

#12


If you have cygwin in your windows environment path you can use:

如果您在Windows环境路径中有cygwin,则可以使用:

 dir > a.txt | tail -f a.txt

#13


dir 1>a.txt 2>&1 | type a.txt

dir 1> a.txt 2>&1 |输入a.txt

This will help to redirect both STDOUT and STDERR

这将有助于重定向STDOUT和STDERR

#14


I was also looking for the same solution, after a little try, I was successfully able to achieve that in Command Prompt. Here is my solution :

我也在寻找相同的解决方案,经过一些尝试,我成功地在命令提示符中实现了这一点。这是我的解决方案:

@Echo off
for /f "Delims=" %%a IN (xyz.bat) do (
%%a > _ && type _ && type _ >> log.txt
)
@Echo on

It even captures any PAUSE command as well.

它甚至还捕获任何PAUSE命令。

#15


send output to console, append to console log, delete output from current command

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

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

#16


Here's a sample of what I've used based on one of the other answers

这是我根据其他答案之一使用的样本

@echo off
REM SOME CODE
set __ERROR_LOG=c:\errors.txt
REM set __IPADDRESS=x.x.x.x

REM Test a variable
if not defined __IPADDRESS (
     REM Call function with some data and terminate
     call :TEE %DATE%,%TIME%,IP ADDRESS IS NOT DEFINED
     goto :EOF
)

REM If test happens to be successful, TEE out a message and end script.
call :TEE Script Ended Successful
goto :EOF


REM THE TEE FUNCTION
:TEE
for /f "tokens=*" %%Z in ("%*") do (
     >  CON ECHO.%%Z
     >> "%__ERROR_LOG%" ECHO.%%Z
     goto :EOF
)

#17


@echo on

set startDate=%date%
set startTime=%time%

set /a sth=%startTime:~0,2%
set /a stm=1%startTime:~3,2% - 100
set /a sts=1%startTime:~6,2% - 100


fullprocess.bat > C:\LOGS\%startDate%_%sth%.%stm%.%sts%.LOG | fullprocess.bat

This will create a log file with the current datetime and you can the console lines during the process

这将创建一个包含当前日期时间的日志文件,您可以在此过程中使用控制台行

#18


I know this is a very old topic, but in previous answers there is not a full implementation of a real time Tee written in Batch. My solution below is a Batch-JScript hybrid script that use the JScript section just to get the output from the piped command, but the processing of the data is done in the Batch section. This approach have the advantage that any Batch programmer may modify this program to fit specific needs. This program also correctly process the output of CLS command produced by other Batch files, that is, it clear the screen when CLS command output is detected.

我知道这是一个非常古老的主题,但在以前的答案中,并没有完全实现以批处理方式编写的实时Tee。我的解决方案是Batch-JScript混合脚本,它使用JScript部分来获取管道命令的输出,但数据处理在Batch部分完成。这种方法的优点是任何Batch程序员都可以修改该程序以满足特定需求。该程序还可以正确处理其他批处理文件生成的CLS命令的输出,即在检测到CLS命令输出时清除屏幕。

@if (@CodeSection == @Batch) @then


@echo off
setlocal EnableDelayedExpansion

rem APATee.bat: Asynchronous (real time) Tee program, Batch-JScript hybrid version
rem Antonio Perez Ayala

rem The advantage of this program is that the data management is written in Batch code,
rem so any Batch programmer may modify it to fit their own needs.
rem As an example of this feature, CLS command is correctly managed

if "%~1" equ "" (
   echo Duplicate the Stdout output of a command in the screen and a disk file
   echo/
   echo anyCommand ^| APATee teeFile.txt [/A]
   echo/
   echo If /A switch is given, anyCommand output is *appended* to teeFile.txt
   goto :EOF
)

if "%2" equ ":TeeProcess" goto TeeProcess

rem Get the output of CLS command
for /F %%a in ('cls') do set "cls=%%a"

rem If /A switch is not provided, delete the file that receives Tee output
if /I "%~2" neq "/A" if exist %1 del %1

rem Create the semaphore-signal file and start the asynchronous Tee process
echo X > Flag.out
if exist Flag.in del Flag.in
Cscript //nologo //E:JScript "%~F0" | "%~F0" %1 :TeeProcess
del Flag.out
goto :EOF

:TeeProcess
   rem Wait for "Data Available" signal
   if not exist Flag.in goto TeeProcess
   rem Read the line sent by JScript section
   set line=
   set /P line=
   rem Set "Data Read" acknowledgement
   ren Flag.in Flag.out
   rem Check for the standard "End Of piped File" mark
   if "!line!" equ ":_EOF_:" exit /B
   rem Correctly manage CLS command
   if "!line:~0,1!" equ "!cls!" (
      cls
      set "line=!line:~1!"
   )
   rem Duplicate the line in Stdout and the Tee output file
   echo(!line!
   echo(!line!>> %1
goto TeeProcess


@end


// JScript section

var fso = new ActiveXObject("Scripting.FileSystemObject");
// Process all lines of Stdin
while ( ! WScript.Stdin.AtEndOfStream ) {
   // Read the next line from Stdin
   var line = WScript.Stdin.ReadLine();
   // Wait for "Data Read" acknowledgement
   while ( ! fso.FileExists("Flag.out") ) {
      WScript.Sleep(10);
   }
   // Send the line to Batch section
   WScript.Stdout.WriteLine(line);
   // Set "Data Available" signal
   fso.MoveFile("Flag.out", "Flag.in");
}
// Wait for last "Data Read" acknowledgement
while ( ! fso.FileExists("Flag.out") ) {
      WScript.Sleep(10);
}
// Send the standard "End Of piped File" mark
WScript.Stdout.WriteLine(":_EOF_:");
fso.MoveFile("Flag.out", "Flag.in");

#19


Something like this should do what you need?

这样的事情应该做你需要的吗?

%DATE%_%TIME% > c:\a.txt & type c:\a.txt
ipconfig >> c:\a.txt & type c:\a.txt
ping localhost >> c:\a.txt & type c:\a.txt
pause

#20


This is a variation on a previous answer by MTS, however it adds some functionality that might be useful to others. Here is the method that I used:

这是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
    • 该命令已使用胡萝卜^字符转义重定向,因此最初不会评估命令

  • 命令被设置为变量,可以在以后的整个代码中使用,输出到命令窗口并附加到日志文件,使用set _Temp_Msg_Cmd =命令已使用胡萝卜^字符转义重定向,因此命令不是最初评估

  • 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.
  • 创建一个临时文件,其文件名类似于正在运行的批处理文件,名为%~n0_temp.txt,它使用命令行参数扩展语法%~n0来获取批处理文件的名称。

  • The output is appended to a separate log file %~n0_log.txt
  • 输出附加到单独的日志文件%~n0_log.txt

Here is the sequence of commands:

这是命令序列:

  1. The output and error messages are sent to the temporary file ^> %~n0_temp.txt 2^>^&1
  2. 输出和错误消息将发送到临时文件^>%~n0_temp.txt 2 ^> ^&1

  3. The content of the temporary file is then both:
    • appended to the logfile ^& type %~n0_temp.txt ^>^> %~n0_log.txt
    • 附加到日志文件^&type%~n0_temp.txt ^> ^>%~n0_log.txt

    • output to the command window ^& type %~n0_temp.txt
    • 输出到命令窗口^&键入%~n0_temp.txt

  4. 然后临时文件的内容:附加到日志文件^&输入%~n0_temp.txt ^> ^>%~n0_log.txt输出到命令窗口^&type%~n0_temp.txt

  5. The temporary file with the message is deleted ^& del /Q /F %~n0_temp.txt
  6. 带有消息的临时文件将被删除^&del / Q / F%~n0_temp.txt

Here is the example:

这是一个例子:

set _Temp_Msg_Cmd= ^> %~n0_temp.txt 2^>^&1 ^& type %~n0_temp.txt ^>^> %~n0_log.txt ^& type %~n0_temp.txt ^& del /Q /F %~n0_temp.txt

set _Temp_Msg_Cmd = ^>%~n0_temp.txt 2 ^> ^&1 ^&type%~n0_temp.txt ^> ^>%~n0_log.txt ^&type%~n0_temp.txt ^&del / Q / F%~n0_temp 。文本

This way then the command can simply be appended after later commands in a batch file that looks a lot cleaner:

这样,命令可以简单地在批处理文件中的后续命令之后附加,该批处理文件看起来更清晰:

echo test message %_Temp_Msg_Cmd%

echo测试消息%_Temp_Msg_Cmd%

This can be added to the end of other commands as well. As far as I can tell it will work when messages have multiple lines. For example the following command outputs two lines if there is an error message:

这也可以添加到其他命令的末尾。据我所知,当消息有多行时它将起作用。例如,如果出现错误消息,则以下命令输出两行:

net use M: /D /Y %_Temp_Msg_Cmd%

净使用M:/ D / Y%_Temp_Msg_Cmd%

#21


I use a batch subroutine with a "for" statement to get the command output one line at a time and both write that line to a file and output it to the console.

我使用带有“for”语句的批处理子例程来一次获取一行命令输出,并将该行写入文件并将其输出到控制台。

@echo off
set logfile=test.log

call :ExecuteAndTee dir C:\Program Files

Exit /B 0

:ExecuteAndTee
setlocal enabledelayedexpansion
echo Executing '%*'
  for /f "delims=" %%a in ('%* 2^>^&1') do (echo.%%a & echo.%%a>>%logfile%)
endlocal
Exit /B 0

#22


Following helps if you want something really seen on the screen - even if the batch file was redirected to a file. The device CON maybe used also if redirected to a file

如果你想要在屏幕上看到的东西,即使批量文件被重定向到文件,以下内容也会有所帮助。如果重定向到文件,也可以使用设备CON

Example:

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

Also see good redirection description: http://www.p-dd.com/chapter7-page14.html

另请参阅良好的重定向说明:http://www.p-dd.com/chapter7-page14.html

#23


How do I display and redirect output to a file. Suppose if I use dos command, dir > test.txt ,this command will redirect output to file test.txt without displaying the results. how to write a command to display the output and redirect output to a file using DOS i.e., windows command prompt, not in UNIX/LINUX.

如何显示输出并将其重定向到文件。假设我使用dos命令dir> test.txt,此命令将输出重定向到文件test.txt而不显示结果。如何编写命令来显示输出并使用DOS将输出重定向到文件,即Windows命令提示符,而不是在UNIX / LINUX中。

You may find these commands in biterscripting ( http://www.biterscripting.com ) useful.

您可能会发现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.

#24


This works in real time but is also kind a ugly and the performance is slow. Not well tested either:

这实时工作,但也很难看,性能很慢。尚未经过充分测试:

@echo off
cls
SET MYCOMMAND=dir /B
ECHO File called 'test.bat' > out.txt
for /f "usebackq delims=" %%I in (`%MYCOMMAND%`) do (
  ECHO %%I
  ECHO %%I >> out.txt
) 
pause

#25


An alternative is to tee stdout to stderr within your program:

另一种方法是在程序中将stdout发送到stderr:

in java:

System.setOut(new PrintStream(new TeeOutputStream(System.out, System.err)));

Then, in your dos batchfile: java program > log.txt

然后,在dos batchfile中:java program> log.txt

The stdout will go to the logfile and the stderr (same data) will show on the console.

stdout将转到日志文件,stderr(相同的数据)将显示在控制台上。

#26


Just like unix

就像unix一样

dir | tee a.txt

dir | tee a.txt

does work On windows XP, it requires mksnt installed

工作在Windows XP上,它需要安装mksnt

It displayes on the promt as well as appends to the file

它显示在promt上并附加到文件中

#27


I install perl on most of my machines so an answer using perl: tee.pl

我在我的大多数机器上安装了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;

dir | perl tee.pl or dir | perl tee.pl dir.bat

dir | perl tee.pl或dir | perl tee.pl dir.bat

crude and untested.

原油和未经测试。

#28


try this:
dir > test.txt & type test.txt

试试这个:dir> test.txt&type test.txt