简体   繁体   English

2>&1 的正确用法| 三通或| 带 Powershell 的 T 恤

[英]Right usage of 2>&1 | tee or | tee with powershell

I want to see the output of the command in the console and save it in a file so I have these two options:我想在控制台中查看命令的输出并将其保存在一个文件中,因此我有以下两个选项:

When I use command | tee output.txt当我使用command | tee output.txt command | tee output.txt somehow it generates no output file at all but it works as usual in the console. command | tee output.txt以某种方式它根本不生成输出文件,但它在控制台中照常工作。

When I use command 2>&1 | tee output.txt当我使用command 2>&1 | tee output.txt command 2>&1 | tee output.txt it generates a fine output file but the text in the console appears in red. command 2>&1 | tee output.txt它生成一个很好的输出文件,但控制台中的文本显示为红色。 在此处输入图片说明

Is there any way to either fix the first option or let the text appear as usual in the second one?有没有办法修复第一个选项或让文本像往常一样出现在第二个选项中? I am using Windows PowerShell (Windows 10) and the Programm I am using this for is liquibase 3.5.5.我正在使用 Windows PowerShell (Windows 10),我使用它的程序是 liquibase 3.5.5。 just for the case that this is important.只是因为这很重要。

In PowerShell, redirecting stderr lines from an external program to PowerShell's success stream via 2>&1 wraps those lines in [System.Management.Automation.ErrorRecord] instances, which is why you're seeing the red output (without the redirection, the stderr lines are passed through to the console, without coloring).在 PowerShell 中,通过2>&1将 stderr 行从外部程序重定向到 PowerShell 的成功流会将这些行包装在[System.Management.Automation.ErrorRecord]实例中,这就是为什么您会看到红色输出(没有重定向,stderr行被传递到控制台,没有着色)。

A simple workaround is to convert these objects to strings explicitly, which outputs the original lines (PSv3+ syntax; built-in alias % for ForEach-Object used for brevity):一个简单的解决方法是将这些对象显式转换为字符串,它输出原始行(PSv3+ 语法;为简洁起见, ForEach-Object内置别名% ):

... 2>&1 | % ToString | Tee-Object output.txt

If you are in DOS then you can leverage powershell (from DOS) and use tee-object do more or less a tee like in Linux.如果您在 DOS 中,那么您可以利用 powershell(来自 DOS)并使用 tee-object 或多或少地像在 Linux 中那样做一个 tee。

C:> powershell some_command ^| C:> powershell some_command ^| tee-object -FilePath some_outputfile tee-object -FilePath some_outputfile

The '^' escapes the pipe so that the pipe applies to powershell and not DOS. '^' 对管道进行转义,以便管道适用于 powershell 而不是 DOS。

Powershell and tee-object should come with Windows as standard so nothing to install! Powershell 和 tee-object 应该作为标准随 Windows 一起提供,因此无需安装!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM