首页 > 解决方案 > 在 Powershell 中输出具有颜色和背景颜色的对象

问题描述

我有一个名为的对象$myObject

@{attr1=My first attribut;attr2=My second attribut;....}

当我只使用对象名称时,对象会正确显示:

PS > $myObject
attr1 : My first attribut
attr2 : My second attribut

我想用特定颜色显示我的对象。我尝试使用 write-host重现示例 #4 。

背景和前景色有效,但我的对象显示为“对象”:

@{attr1=My first attribut;attr2=My second attribut;....}

我尝试了这样的多种组合:

$myObject | write-host -ForegroundColor DarkGreen
write-output $myObject -ForegroundColor DarkGreen
write-output $myObject | write-host -ForegroundColor DarkGreen
write-host  $myObject -ForegroundColor DarkGreen

没有人工作。

知道怎么做吗?谢谢!

标签: powershell

解决方案


Write-Host接受一个输入对象,将其转换为字符串并将其写入主机应用程序的屏幕缓冲区 - 因此,如果您不希望它打印对象的默认字符串表示形式(即。@{prop=value;...}),我们必须将其转换为将其传递给Write-Host.

要获得一个反映默认格式的字符串,PowerShell 会以其他方式应用于对象,请使用Out-String

Write-Host ($myObject |Out-String) -ForegroundColor DarkGreen

推荐阅读