本文介绍了如何为 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}}

推荐答案

您可以使用正则表达式为着色...

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

输出:

这篇关于如何为 Format-Table 的 PowerShell 输出着色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 12:30