简体   繁体   English

Powershell表颜色结果

[英]powershell table color results

I have a simple array, $Results. 我有一个简单的数组,$ Results。 It has two columns: Task, Result. 它具有两列:任务,结果。 I output it to a table as follows: 我将其输出到表中,如下所示:

$(foreach($ht in $Results){new-object PSObject -Property $ht}) | Format-Table -AutoSize -Property Task, Result

The Result column will contain either "PASS" or "FAIL". 结果列将包含“通过”或“失败”。 I would like the PASS to be in green and the FAIL to be in red. 我希望“通过”显示为绿色,“失败”显示为红色。

Anyone know of a simple way to achieve this? 有人知道实现此目标的简单方法吗?

Ideally only the PASS/FAIL is colorized, but I can live with the entire row being done if necessary. 理想情况下,仅将“通过/失败”着色,但是如有必要,我可以完成整行。

While I thought about this one, I noticed something in the related questions on the side that looked similar "Color words in powershell script format-table output". 当我考虑这一点时,我注意到一侧的相关问题中的某些内容看起来类似“ powershell脚本格式表输出中的颜色单词”。 I took one of the answers to that question, and hacked it a little, and came up with the following: 回答了该问题,并对其做了一点修改,并提出了以下建议:

# Let's Build Some Sample Data To Play With...
$Results = @()
for( $j = 1; $j -le 25; ++$j ) {
    $ans = ( "PASS", "FAIL" ) | Get-Random
    $Results += [PSCustomObject]@{ Task = "Task{0:d2}" -f $j; Result = $ans }
}

# Here's The Important Part...
filter PassFail {
    # Adapted From: https://stackoverflow.com/a/7368884/3168105
    $Pattern = "PASS|FAIL"

    $split = $_ -split $Pattern
    $found = [regex]::Matches( $_, $Pattern, 'IgnoreCase' )
    for( $i = 0; $i -lt $split.Count; ++$i ) {
        Write-Host $split[$i] -NoNewLine
        # Just in case something else pops up...
        switch( $found[$i] ) {
            "Fail" { $Color = "Red" }
            "Pass" { $Color = "Green" }
            default { $Color = "White" }
        }
        Write-Host $found[$i] -NoNewline -ForegroundColor $Color
    }

    Write-Host
}

# And here we put it together...
$Results | Out-String | PassFail

This can be adopted to handle more results, it just needs additional lines added to the switch statement, and the additional results added to the $Pattern variable. 可以采用这种方式来处理更多结果,它只需要在switch语句中添加其他行,并在$Pattern变量中添加其他结果。 I won't begin to say this is the best solution (or even a particularly good solution), but it works and seems to behave fairly well. 我不会开始说这是最好的解决方案(甚至是一个特别好的解决方案),但是它可以正常工作并且表现还不错。

To use it like you're using it above, with the array of hashtables, you should be able to do something along these lines: 要像上面使用它一样使用它,并使用哈希表数组,您应该能够按照以下方式进行操作:

$(foreach($ht in $Results){new-object PSObject -Property $ht}) | Format-Table -AutoSize Task, Result | Out-String | PassFail

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM