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
I like Rynant's approach. Here is an alternate implementation, using -split instead of IndexOf:
filter ColorWord( [string]$word, [ConsoleColor]$color ) {
$later = $false
$_ -split [regex]::Escape( $word ) | foreach {
if( $later ) { Write-Host "$word" -NoNewline -ForegroundColor $color }
else { $later = $true }
Write-Host $_ -NoNewline
}
Write-Host
}
Split includes empty strings if the line starts or ends with the given word, hence the extra "if not first" logic.
Edit: Following Rynant's comment, here's another implementation that supports both simple and regex patterns:
filter ColorPattern( [string]$Pattern, [ConsoleColor]$Color, [switch]$SimpleMatch ) {
if( $SimpleMatch ) { $Pattern = [regex]::Escape( $Pattern ) }
$split = $_ -split $Pattern
$found = [regex]::Matches( $_, $Pattern, 'IgnoreCase' )
for( $i = 0; $i -lt $split.Count; ++$i ) {
Write-Host $split[$i] -NoNewline
Write-Host $found[$i] -NoNewline -ForegroundColor $Color
}
Write-Host
}
The output from the following examples shows the difference:
PS> '\d00\d!' | ColorPattern '\d' 'Magenta' -Simple
\d00\d!
PS> '\d00\d!' | ColorPattern '\d' 'Magenta'
\d00\d!