如何着色Format-Table的PowerShell输出

Alb*_*ban 11 console powershell colors

如果值大于100 MB,我尝试将列RAM着色为红色:

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}}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我尝试使用Write-Host -nonewline,但结果是错误的.

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}}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Jas*_*irk 20

从PowerShell 5.1或更高版本开始,您可以使用VT转义序列为单个列添加颜色,但前提是您的控制台支持VT转义序列(例如Windows 10 Fall Creators Update,Linux或Mac,但不支持Windows 8 w/oa控制台模拟器)像ConEmu).

下面是一个在表达式中指定格式的示例,尽管可以在ps1xml文件中使用相同的格式:

dir -Exclude *.xml $pshome | Format-Table Mode,@{
    Label = "Name"
    Expression =
    {
        switch ($_.Extension)
        {
            '.exe' { $color = "93"; break }
            '.ps1xml' { $color = '32'; break }
            '.dll' { $color = "35"; break }
           default { $color = "0" }
        }
        $e = [char]27
       "$e[${color}m$($_.Name)${e}[0m"
    }
 },Length
Run Code Online (Sandbox Code Playgroud)

结果输出,请注意列宽看起来很好,转义序列字符没有多余的空格.

带有彩色名称的dir输出的屏幕截图


Bjo*_*orn 14

接受的答案不正确,可以对列进行着色.获取条件列颜色的解决方案是使用Write-PSObject.

以下是一些带有文档代码和解释的精彩示例.

从以上资源:

Write-PSObject $servers -MatchMethod Exact -Column "Manufacture" -Value "HP" -ValueForeColor Yellow -ValueBackColor Red -RowForeColor White -RowBackColor Blue;
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我发现这是通过GitHub问题向Format-Table添加颜色格式,这似乎是PowerShell开发人员想要在某些时候添加的功能.


The*_*mus 10

您可以使用正则表达式对行进行着色...

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
Run Code Online (Sandbox Code Playgroud)

输出:

在此输入图像描述


Mik*_*ard 5

快速的答案是你不能。可以将Write-Host与颜色一起使用,但没有“输出”要发送到格式表。

Write-Host 的“输出”是一种副作用,它将数据直接发送到控制台,而不是像标准函数那样将数据返回给调用者。

在与@大卫·马丁的评论相结合,这里是一个链接一个有趣的模式匹配格式彩色功能。