【问题标题】:Powershell - disable colored command outputPowershell - 禁用彩色命令输出
【发布时间】:2021-04-20 10:56:07
【问题描述】:

我正在 Powershell(或 Powershell Core,两者都是此处的选项)中运行一个命令 (New-AzResourceGroupDeployment -WhatIf),它会产生一些非常丰富多彩的输出,如下所示:

问题是,当我在 Azure DevOps 管道中运行它时,那里的日志记录会被颜色混淆并产生大量乱码:

所以我的问题是:由于此命令本身没有这样的选项,因此 PowerShell(核心)中是否有通用方法来禁用命令产生彩色输出?

【问题讨论】:

标签: powershell azure-devops


【解决方案1】:

使用 PowerShell 7.2 可能会有适合您的新解决方案:

$PSStyle.OutputRendering = [System.Management.Automation.OutputRendering]::PlainText;

来自about_ANSI_Terminals 文档:

以下成员控制使用 ANSI 格式的方式或时间:

  • $PSStyle.OutputRendering 是一个 System.Management.Automation.OutputRendering 枚举,其值为:
    • ANSI:ANSI 始终按原样传递
    • PlainText:ANSI 转义序列总是被剥离,因此它只是纯文本
    • 主机:这是默认行为。 ANSI 转义序列在重定向或管道输出中被删除。

您也可以尝试查询 PowerShell 帮助系统:

Get-Help -Name 'about_ANSI_Terminals';

一个完整的例子,使用你拥有的东西,不管模块等。这个:

$PSStyle.OutputRendering = [System.Management.Automation.OutputRendering]::Ansi;
$PSVersionTable | Format-List;

会产生一个彩色输出,用这个:

$PSStyle.OutputRendering = [System.Management.Automation.OutputRendering]::PlainText;
$PSVersionTable | Format-List;

将生成纯文本。 如果你试试这个:

$PSStyle.OutputRendering = [System.Management.Automation.OutputRendering]::Host;
$PSVersionTable | Format-Table | Tee-Object -FilePath '.\output.txt';

您应该在终端/控制台中获得彩色输出,但在 output.txt 文件中获得纯文本。

我刚刚还发现,here 已经回答了这个问题,并进行了更详细的描述。

【讨论】:

    猜你喜欢
    • 2020-08-31
    • 2014-01-21
    • 2014-03-02
    • 2010-10-08
    • 2020-07-13
    • 2019-05-06
    • 2012-06-26
    • 2019-08-17
    • 2013-05-20
    相关资源
    最近更新 更多