senpost
1/11/2013 - 6:40 PM

gistfile1.ps1

 #Usage dir "c:\" | Out-String -Stream | Highlight "users|temp"
 
filter Highlight( [string]$Pattern, [ConsoleColor]$Color) 
{   if( $Color -eq $null) { $Color = [ConsoleColor]::DarkMagenta }
    $inputString = $_    

    $matches =  $inputString  | select-string  $Pattern -AllMatches 
    #If nothing matches, just write it to host
    if($matches.Matches.Length -eq 0)
    {
        Write-Host $inputString 
    }
    else
    {
        $firstMatch = $matches.Matches[0]
        $lastMatch = $matches.Matches[$matches.Matches.count-1]
        #If match is in the middle, print the begining of the line
        $inputString.Substring(0, $firstMatch.Index) | Write-Host -NoNewline

        for ($i = 0; $i -lt $matches.Matches.Count; $i++)
        { 
            $iMatch = $matches.Matches[$i]
            Write-Host $iMatch.Value -NoNewline -BackgroundColor $Color
            
            #Print string between the matches

            if ($i+1 -eq $matches.Matches.Count) { break }

            $nextMatch = $matches.Matches[$i+1] 

            $GapIndex = $iMatch.Index + $iMatch.Length
            if($nextMatch.Index -ne $GapIndex)
            {
                $inputString.Substring($GapIndex, $nextMatch.Index-$GapIndex) | Write-Host -NoNewline
            }
        }   
        #Print end string after all matches
        $inputString.Substring($lastMatch.Index+ $lastMatch.Length) 
    }
}