Quantcast
Channel: TechNet Blogs
Viewing all articles
Browse latest Browse all 34890

PowerShell – Out-ColourMatch

$
0
0

#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

}

}

}

 


Viewing all articles
Browse latest Browse all 34890

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>