如何为PowerShell输出着色

iszxjhcz  于 2023-11-18  发布在  Shell
关注(0)|答案(7)|浏览(218)

如果值大于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}}

字符串
x1c 0d1x的数据
我尝试使用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}}


btxsgosb

btxsgosb1#

从PowerShell 5.1或更高版本开始,您可以使用VT转义序列向单个列添加颜色,但前提是您的控制台支持VT转义序列(例如Windows 10 Fall Creators Update、Linux或Mac,但不支持Windows 8 w/o控制台模拟器(如ConEmu))。
下面是一个在表达式中指定格式的示例,尽管同样可以在ps1 xml文件中使用:

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

字符串
和结果输出,请注意,列宽看起来不错,没有多余的空格从转义序列字符。
x1c 0d1x的数据

r1zhe5dt

r1zhe5dt2#

接受的答案是不正确的,可以对列进行着色。获取条件列颜色的解决方案是使用Write-PSObject
Here are some wonderful examples带有文档代码和解释。
从上面的资源:

Write-PSObject $servers -MatchMethod Exact -Column "Manufacture" -Value "HP" -ValueForeColor Yellow -ValueBackColor Red -RowForeColor White -RowBackColor Blue;

字符串


的数据
我通过a GitHub issue to add color formatting to Format-Table发现了这个,这似乎是PowerShell开发人员希望在某个时候添加的功能。

lmyy7pcs

lmyy7pcs3#

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

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

字符串

输出:


的数据

omhiaaxx

omhiaaxx4#

快速的回答是你不能。可以使用Write-Host与颜色,但没有“输出”发送到格式表。
Write-Host的“输出”是一个副作用,它直接将数据发送到控制台,而不是像标准函数那样将数据返回给调用者。
结合@大卫马丁的评论,这里是a link与一个有趣的模式匹配格式颜色函数。

t40tm48m

t40tm48m5#

是的,您可以使用ANSI转义颜色并使颜色具有条件:

Get-Process | Format-Table @{ Label = "PID"; Expression={$_.Id}},
        @{ Label = "Name"; Expression={$_.Name}},
        @{ Label = "RAM (MB)"; Expression={if($_.WS/1MB -gt 100){"$([char]27)[0;31m$([System.Math]::Round($_.WS/1MB, 1))$([char]27)[0m"}else{"$([char]27)[0;32m$([System.Math]::Round($_.WS/1MB, 1))$([char]27)[0m"}}},
        @{ Label = "Responding"; Expression={if($_.Responding -eq $true){"$([char]27)[0;32m$($_.Responding)$([char]27)[0m"}else{"$([char]27)[0;31m$($_.Responding)$([char]27)[0m"}}}

字符串

dzhpxtsq

dzhpxtsq6#

这是一个不同版本的Jason Shirk's answer后,几年来,现在使用PSStyle在PowerShell 7.4


的数据

# Create a dummy data table with three columns: Name, Age, and Occupation
$data = @(
    [PSCustomObject]@{Name = 'Alice'; Age = 25; Occupation = 'Teacher' }
    [PSCustomObject]@{Name = 'Bob'; Age = 30; Occupation = 'Engineer' }
    [PSCustomObject]@{Name = 'Charlie'; Age = 35; Occupation = 'Doctor' }
    [PSCustomObject]@{Name = 'David'; Age = 40; Occupation = 'Lawyer' }
    [PSCustomObject]@{Name = 'Eve'; Age = 45; Occupation = 'Artist' }
)

$PSStyle.Formatting.TableHeader = "$($PSStyle.Foreground.FromRGB(218,112,214))"

$data | Format-Table @{
    Label      = 'Name'
    Expression =
    { switch ($_.Name) {
            { $_ } { $color = "$($PSStyle.Foreground.FromRGB(255,255,49))$($PSStyle.Blink)" } # Use PSStyle to set the color
        }
        "$color$($_.Name)$($PSStyle.Reset)" # Use PSStyle to reset the color
    }
}, @{
    Label      = 'Age'
    Expression =
    { switch ($_.age) {
            { $_ -gt 30 } { $color = "$($PSStyle.Foreground.FromRGB(255,20,147))$($PSStyle.Blink)" } # Use PSStyle to set the color
        }
        "$color$($_.age)$($PSStyle.Reset)" # Use PSStyle to reset the color
    }
}, @{
    Label      = 'Occupation'
    Expression =
    { switch ($_.Occupation) {
            { $_ } { $color = "$($PSStyle.Foreground.FromRGB(152,255,152))$($PSStyle.Blink)" } # Use PSStyle to set the color
        }
        "$color$($_.Occupation)$($PSStyle.Reset)" # Use PSStyle to reset the color
    }
}

字符串

ttisahbt

ttisahbt7#

这个例子显示了事件记录的行的交替背景颜色(感谢this post)。根据TimeCreated字段,文本颜色将是蓝色(一个月或更少),黄色(一周或更少)或红色(今天)。请参阅维基百科上的'ANSI转义码'主题以获取颜色转义码。

# constants
$e=[char]27                                             # escape character
[string]$_Reset     = $($e+"[0m")
[string]$_bSapphire1= $($e+"[48;2;1;36;86m")        # ESC[48;2;r;g;bm Select RGB background colour
[string]$_bSapphire2= $($e+"[48;2;3;55;155m")
[string]$_fBRed     = $($e+"[91m")
[string]$_fBYellow  = $($e+"[93m")
[string]$_fBCyan    = $($e+"[96m")
$Today              = [datetime]::today
$OneWeek            = $Today.AddDays(-7)
$OneMonth           = $Today.AddDays(-30)
# variable
[ref]$bToggle       = $True                         # makes the background colour of the row alternate
# script block
$ExtractScript={
    param([array]$Events,[enum]$Level)
    $Events|
    Where-Object { $Level -eq $_.Level }|
    Sort-Object -Property @{ Expression="ProviderName"; Ascending=$True },
                          @{ Expression="TimeCreated" ; Ascending=$True }|
    Format-Table @{
            Label="TimeCreated"
            Expression= {
                # rows have an alternating background colour
                if($bToggle.Value) { $bcolour=[string]::copy($_bSapphire1) } else { $bcolour=[string]::copy($_bSapphire2) }
                $bToggle.Value = $(-not $bToggle.Value)
                
                # TimeCreated has effect on the foreground colour of the row 
                $fcolour = [string]::copy($_Reset)
                if( $OneMonth -lt $_.TimeCreated ) { $fcolour = [string]::copy($_fBCyan) }
                if( $OneWeek  -lt $_.TimeCreated ) { $fcolour = [string]::copy($_fBYellow) }
                if( $Today    -lt $_.TimeCreated ) { $fcolour = [string]::copy($_fBRed) }
                $($fcolour+$bcolour+$("{0:d} {0:HH}:{0:mm}:{0:ss}" -f $($_.TimeCreated)))
            }
            Alignment='Right'
        },
        ProviderName,
        ID,
        @{
            Name='Level'
            Expression={$_.LevelDisplayName}
            Alignment='Right'
        },
        @{
            Name='Message'
            Expression={
                # Colours are reset
                $($_.Message+$_Reset)
            }
        }       
}
# code
$EventArray=Get-WinEvent -LogName System -MaxEvents 10000
& $ExtractScript -Events $EventArray -Level $([System.Diagnostics.Eventing.Reader.StandardEventLevel]::Error)
$($_Reset+"Legend:")|Out-Default
$($_fBCyan+"After "+$("{0:d} {0:HH}:{0:mm}:{0:ss}" -f $OneMonth))|Out-Default
$($_fBYellow+"After "+$("{0:d} {0:HH}:{0:mm}:{0:ss}" -f $OneWeek))|Out-Default
$($_fBRed+"Today")|Out-Default   
$_Reset|Out-Default

字符串

相关问题