尝试查看是否可以使用以下行更改输出的颜色。请注意,这不是完整的代码,只是其中的一部分:
$ADInfo `
| Format-List `
@{ Name = "Full Name"; Expression = { $_.name } },
@{ Name = "Display Name"; Expression = { $_.displayname } },
@{ Name = "User ID"; Expression = { $_.samaccountname } },
@{ Name = "Email"; Expression = { $_.mail } },
@{ Name = "Exchange Version"; Expression = { $_.msExchVersion } },
如果可能的话,我想彼此独立地改变名称和输出的颜色。
输出:
答案 0 :(得分:0)
Function Write-HostColoured{
[cmdletbinding()]
Param(
[parameter(Mandatory=$true,ValueFromPipeline=$true)]
$Input,
[parameter(Mandatory=$true)]
[string]$ColouredProperty,
[System.ConsoleColor]$Colour = "Red"
)
# Get all the note properties of the object which we need for output and determining conditional formatting.
$properties = $input | gm -MemberType NoteProperty | Select-Object -ExpandProperty name
# Find the property with the longest length. Used for aligning output.
$longestProperty = $properties | ForEach-Object{$_.Length} | Measure-Object -Maximum | Select-Object -ExpandProperty Maximum
# Check if the property to colour requested is in $properties
If($properties -notcontains $ColouredProperty){Write-Warning "Input object does not contain the property $ColouredProperty"}
# Insert Line break between objects.
Write-Host
ForEach($singleObject in $Input){
$properties | ForEach-Object{
Write-Host ("{0,-$longestProperty} : " -f $_) -NoNewline
# Check if the property requires a colour formatting
If($_ -eq $ColouredProperty){
Write-Host $singleObject.$_ -ForegroundColor $Colour
} Else {
Write-Host $singleObject.$_
}
}
# Insert Line break between objects.
Write-Host
}
}
Import-Csv C:\temp\data.csv -header "Col123fff1","cl2","col3","col4" | Write-HostColoured -ColouredProperty Col3
<强>解释强>
认为这需要根据您的评论发展,但让我们从此开始。它将从对象获取管道输入(使用Import-CSV
测试),然后模拟Format-List
的输出。如果正在处理的属性与Write-Host
匹配,则使用$ColouredProperty
输出,然后应用$colour
定义的前景色。
这当前只在你需要为一列着色时才有效但我可以看到这也为条件格式设置了一个哈希表输入。
如果我们走在正确的轨道上,请告诉我。
如果更改if语句并添加另一个子句
,则可以根据条件轻松制作着色条件库If($_ -eq $ColouredProperty -and $singleObject.$_ -match "\d")
它使功能不易转移,但它可以工作。我用它来突出显示包含数字的所有文件名。
Get-ChildItem C:\temp -filter *.txt | Select Name,Length,Directory | Write-HostColoured -ColouredProperty Name