PowerShell - Out-ColourMatch

#Out-ColourMatch.ps1
Set-StrictMode -Version Latest
function Out-ColourMatch {

<#
.Synopsis
Outputs coloured matches from Select-String
.Description
Outputs the matched string, with the match section(s) highlighted in colour.
.INPUTS
a [Microsoft.PowerShell.Commands.MatchInfo] object.
.OUTPUTS
None. Write-Host displays the colourised string.
.Example
Get-Content .\LoremIpsum.txt | Select-String -Pattern 'dolor' -AllMatches | Out-ColourMatch
.Example
$b = Get-Content .\LoremIpsum.txt | Select-String -Pattern 'dolor' -AllMatches
Out-ColourMatch -MatchInfo $b
.Example
Get-Content .\LoremIpsum.txt | Select-String -Pattern 'expedita' -AllMatches | Out-ColourMatch -Verbose -Colour Red
.LINK
Select-String
#>

[CmdletBinding()]
[Alias('Out-ColorMatch')]
[OutputType([string])]
PARAM([Parameter(Mandatory=$true,ValueFromPipeline=$true,Position=0)]
[Microsoft.PowerShell.Commands.MatchInfo[]] $MatchInfo,
[Parameter(Mandatory=$false)] [alias('Color')] [System.ConsoleColor] $Colour='Yellow')

 PROCESS {
   foreach ($matchObj in $MatchInfo) {
     Write-Verbose -Message "Processing $($matchObj.Matches.Count) matches"
     for ($start=$i=0; $i -lt ($matchObj.Matches.Count); $i++) {
       $match=$matchObj.Matches[$i]
       Write-Host -NoNewline $($matchObj.Line.Substring($start, ($match.Index - $start))) # display a chunk of line
       Write-Host -NoNewline -ForegroundColor $colour $match.Value # now the matched item
       $start = ($match.Index + $match.Length) # move past this item
     }
    Write-Host $($matchObj.Line.Substring($start)) # and lastly, the remainder of the line
   }
}

}

Comments

  • Anonymous
    June 21, 2016
    NiceThanks