如何为PowerShell格式化表的颜色 [英] How to colorise PowerShell output of Format-Table
本文介绍了如何为PowerShell格式化表的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果值大于100 MB,我尝试将列RAM着色为红色:
I try to colorise the column RAM in red if the value is greater than 100 MB:
Get-Process | Format-Table @{ Label = "PID"; Expression={$_.Id}},
@{ Label = "Name"; Expression={$_.Name}},
@{ Label = "RAM (MB)"; Expression={[System.Math]::Round($_.WS/1MB, 1)}},
@{ Label = "Responding"; Expression={$_.Responding}}
我尝试使用 Write-Host -nonewline ,但是结果是错误的。
I try with Write-Host -nonewline, but the result is wrong.
Get-Process | Format-Table @{ Label = "PID"; Expression={$_.Id}},
@{ Label = "Name"; Expression={$_.Name}},
@{ Label = "RAM (MB)"; Expression={write-host -NoNewline $([System.Math]::Round($_.WS/1MB, 1)) -ForegroundColor red}},
@{ Label = "Responding"; Expression={ write-host -NoNewline $_.Responding -fore red}}
推荐答案
您可以使用正则表达式为行着色...
You could colorize the row making use of a regular expression...
filter colorize-row{
Get-Process | Select-Object Id, Name, WS, Responding | foreach {
# Print 'red' row if WS greater than 100 MB
if([System.Math]::Round($_.WS/1MB,1) -match "^([0-9]|[0-9][0-9]|[1-9][0-9]?$|^100$)$"){
[console]::ForegroundColor="white"; $_;
} else {
[console]::ForegroundColor="red"; $_;
}
}
}
colorize-row
输出:
Output:
这篇关于如何为PowerShell格式化表的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文