Color words in powershell script format-table output

后端 未结 4 2039
梦如初夏
梦如初夏 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:17

    You could pipe the table into Out-String, then write the string in parts using Write-Host with the -NoNewLine switch.

    Something like this:

    filter ColorWord {
        param(
            [string] $word,
            [string] $color
        )
        $line = $_
        $index = $line.IndexOf($word, [System.StringComparison]::InvariantCultureIgnoreCase)
        while($index -ge 0){
            Write-Host $line.Substring(0,$index) -NoNewline
            Write-Host $line.Substring($index, $word.Length) -NoNewline -ForegroundColor $color
            $used = $word.Length + $index
            $remain = $line.Length - $used
            $line = $line.Substring($used, $remain)
            $index = $line.IndexOf($word, [System.StringComparison]::InvariantCultureIgnoreCase)
        }
        Write-Host $line
    }
    
    Get-Process| Format-Table| Out-String| ColorWord -word 1 -color magenta
    

提交回复
热议问题