2& 1的正确用法|三通或|T恤配Powershell [英] Right usage of 2>&1 | tee or | tee with powershell

查看:32
本文介绍了2& 1的正确用法|三通或|T恤配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:

当我使用 command |tee output.txt 会以某种方式完全不生成输出文件,但在控制台中仍会像往常一样工作.

When I use command | tee output.txt somehow it generates no output file at all but it works as usual in the console.

当我使用命令2>& 1 |tee output.txt 会生成一个很好的输出文件,但控制台中的文本显示为红色.

When I use command 2>&1 | tee output.txt it generates a fine output file but the text in the console appears in red.

有什么办法可以解决第一个选项,还是让文本照常出现在第二个选项中?我正在使用Windows PowerShell(Windows 10),而我正在使用的程序是liquibase 3.5.5.只是在这很重要的情况下.

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. just for the case that this is important.

推荐答案

在PowerShell中,通过 2>& 1 将stderr行从外部程序重定向到PowerShell的成功流,将这些行包装在 [System.Management.Automation.ErrorRecord] 实例,这就是为什么您看到红色输出的原因(没有重定向,stderr行会通过传递到控制台,而不会着色).

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

一个简单的解决方法是将这些对象显式转换为字符串,然后输出原始行(PSv3 +语法;为简短起见的 ForEach-Object 使用内置别名):

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

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

这篇关于2& 1的正确用法|三通或|T恤配Powershell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆