I like Rynant . Here is an alternative 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 lines if the line starts or ends with the given word, therefore, the additional logic is "if not the first".
Edit: Following Rynant's comment, here is another implementation that supports both simple and regular 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 result from the following examples shows the difference:
PS> '\d00\d!' | ColorPattern '\d' 'Magenta' -Simple
\d 00 \d !
PS> '\d00\d!' | ColorPattern '\d' 'Magenta'
\d 00 \d!
Emperor XLII
source share