PoshCode Archive  Artifact [611c1b6c5e]

Artifact 611c1b6c5e2d8d886c2562a4aa2baf330ef2f25e68c6f64560caf46769e6ffad:

  • File Out-ColorMatchInfo.ps1 — part of check-in [d27c03882c] at 2018-06-10 12:56:25 on branch trunk — Formats and highlights matches in a MatchInfo object which (user: unknown size: 1631)

# encoding: ascii
# api: powershell
# title: Out-ColorMatchInfo
# description: Formats and highlights matches in a MatchInfo object which
# version: 0.1
# type: script
# license: CC0
# function: Get-RelativePath
# x-poshcode-id: 1095
# x-archived: 2009-10-25T15:24:52
#
# is the result of a Select-String call.
#
<#
.Synopsis
	Highlights MatchInfo objects similar to the output from grep.
.Description
	Highlights MatchInfo objects similar to the output from grep.
#>
#requires -version 2
param ( 
	[Parameter(Mandatory=$true, ValueFromPipeline=$true)] 
	[Microsoft.PowerShell.Commands.MatchInfo] $match
)

begin {}
process { 
	function Get-RelativePath([string] $path) {
		$path = $path.Replace($pwd.Path, '')
		if ($path.StartsWith('\') -and (-not $path.StartsWith('\\'))) { 
			$path = $path.Substring(1) 
		}
		$path
	}

	function Write-PathAndLine($match) {
		Write-Host (Get-RelativePath $match.Path) -foregroundColor DarkMagenta -nonewline
		Write-Host ':' -foregroundColor Cyan -nonewline
		Write-Host $match.LineNumber -foregroundColor DarkYellow
	}

	function Write-HighlightedMatch($match) {
		$index = 0
		foreach ($m in $match.Matches) {
			Write-Host $match.Line.SubString($index, $m.Index - $index) -nonewline
			Write-Host $m.Value -ForegroundColor Red -nonewline
			$index = $m.Index + $m.Length
		}
		if ($index -lt $match.Line.Length) {
			Write-Host $match.Line.SubString($index) -nonewline
		}
		''
	}
	
	Write-PathAndLine $match

	$match.Context.DisplayPreContext

	Write-HighlightedMatch $match

	$match.Context.DisplayPostContext
	''
}
end {}