Color words in powershell script format-table output

后端 未结 4 2038
梦如初夏
梦如初夏 2021-01-12 11:03

Is it possible to color only certain words (not complete lines) for a powershell output using format-table. For example, this script scans a folder recursively for a string

4条回答
  •  时光取名叫无心
    2021-01-12 11:24

    I love answer @Ryant gave. I have a modified version here that can be used for colouring multiple words in an output by passing in arrays or words and colours. The trick is that you have to split the input text into lines based on the newline separator.

    filter ColorWord2 {
    param(
        [string[]] $word,
        [string[]] $color
    )
    $all = $_
    $lines = ($_ -split '\r\n')
    
    $lines | % {
        $line = $_      
        $x = -1
    
        $word | % {
            $x++
            $item = $_      
    
            $index = $line.IndexOf($item, [System.StringComparison]::InvariantCultureIgnoreCase)                            
                while($index -ge 0){
                    Write-Host $line.Substring(0,$index) -NoNewline                 
                    Write-Host $line.Substring($index, $item.Length) -NoNewline -ForegroundColor $color[$x]
                    $used =$item.Length + $index
                    $remain = $line.Length - $used
                    $line =$line.Substring($used, $remain)
                    $index = $line.IndexOf($item, [System.StringComparison]::InvariantCultureIgnoreCase)
                }
            }
    
        Write-Host $line
    } }
    

    and would be executed as follows

    Get-Service | Format-Table| Out-String| ColorWord2 -word 'Running','Stopped' -color 'Green','Red'
    

提交回复
热议问题