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

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

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


当前回答

如果你的windows环境路径中有cygwin,你可以使用:

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

其他回答

如果你在CLI中,为什么不用FOR循环来“DO”你想做的事情:

for /F "delims=" %a in ('dir') do @echo %a && echo %a >> output.txt

Great resource on Windows CMD for loops: https://ss64.com/nt/for_cmd.html The key here is setting the delimeters (delims), that would break up each line of output, to nothing. This way it won't break on the default of white-space. The %a is an arbitrary letter, but it is used in the "do" section to, well... do something with the characters that were parsed at each line. In this case we can use the ampersands (&&) to execute the 2nd echo command to create-or-append (>>) to a file of our choosing. Safer to keep this order of DO commands in case there's an issue writing the file, we'll at least get the echo to the console first. The at sign (@) in front of the first echo suppresses the console from showing the echo-command itself, and instead just displays the result of the command which is to display the characters in %a. Otherwise you'd see:

echo驱动器[x]中的卷为Windows

UPDATE: /F跳过空行,唯一的修复是预过滤输出,向每一行添加一个字符(可能通过命令find使用行号)。在CLI中解决这个问题既不快速也不漂亮。此外,我没有包括STDERR,所以这里捕获错误:

for /F "delims=" %a in ('dir 2^>^&1') do @echo %a & echo %a >> output.txt

重定向错误消息

插入符号(^)用于转义后面的符号,因为命令是一个正在被解释的字符串,而不是直接在命令行中输入它。

这是实时工作,但也是一种丑陋和性能缓慢。也没有经过很好的测试:

@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

下面是我使用的一个基于其他答案的例子

@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
)

就像unix一样。

目录 |茶A.txt

在windows XP上,它需要安装mksnt。

它显示在提示符上,并附加到文件中。

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