Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Color words in powershell script format-table output

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 and then output the result with format-table.

dir -r -i *.* | Select-String $args[0] |
format-table -Property @{label="Line #"; Expression={$_.LineNumber}; width=6},
Path, Line -wrap

It would be nice to be able to format the word we are searching for with a specific color, so that you can see exactly where it was found on the line.

like image 322
EtienneT Avatar asked Sep 09 '11 13:09

EtienneT


1 Answers

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
like image 61
Rynant Avatar answered Nov 16 '22 00:11

Rynant