使用 PowerShell 7.2,你可能会有一个新的解决方案:
$PSStyle.OutputRendering = [System.Management.Automation.OutputRendering]::PlainText;
从about_ANSI_Terminals文档中可知:
以下成员控制何时或如何使用ANSI格式:
$PSStyle.OutputRendering
是一个System.Management.Automation.OutputRendering
枚举,其包含以下值:
- ANSI:始终按原样传递ANSI
- PlainText:始终剥离ANSI转义序列,只保留纯文本
- Host:这是默认行为。在重定向或管道输出中删除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
文件中只能看到纯文本。
另外我刚才发现这个问题已经在这里得到了回答,并且有更详细的描述。