function hl { param ( [parameter(mandatory=$true,position=0)] [alias("s","ss")] [string]$SEARCHSTRING, [parameter()] [alias("c","cs","case")] [switch]$CASESENSITIVE, [parameter()] [alias("o","om","only")] [switch]$ONLYMATCHING, [parameter()] [alias("h","hl","hc")] [string]$HIGHLIGHTCOLOR="magenta", [parameter(valuefrompipeline=$true)] [alias("p","pi","pl","pli")] [string]$PIPELINEINPUT ) begin { } process { if (-not ($myinvocation.expectinginput)) { break } $ESC=[char][int]27 $COLORCODES=@{ magenta=35 cyan=96 red=31 green=92 yellow=93 blink=5 underline=4 bold=1 reverse=7 italic=3 } $PIPELINELENGTH=$PIPELINEINPUT.length $SEARCHLENGTH=$SEARCHSTRING.length $RESET="$ESC[0m" $MARK="$ESC[$($COLORCODES.$HIGHLIGHTCOLOR)m" $SEARCH=[regex]::escape($SEARCHSTRING) $MARKPOS=[System.Collections.Generic.List[int]]::new() $RESETPOS=[System.Collections.Generic.List[int]]::new() $LINEMATCHED=$false if (-not (($PIPELINELENGTH -eq 0) -or ($PIPELINELENGTH -lt $SEARCHLENGTH))) { if ($CASESENSITIVE) { if ($PIPELINEINPUT -cmatch $SEARCH) { $LINEMATCHED=$true for ($n=0;$n -le $PIPELINELENGTH;$n++) { if ($PIPELINEINPUT.indexof($SEARCHSTRING,$n,[System.StringComparison]"Ordinal") -eq $n) { $MARKPOS.add($n) } } } } else { if ($PIPELINEINPUT -imatch $SEARCH) { $LINEMATCHED=$true for ($n=0;$n -le $PIPELINELENGTH;$n++) { if ($PIPELINEINPUT.indexof($SEARCHSTRING,$n,[System.StringComparison]"OrdinalIgnoreCase") -eq $n) { $MARKPOS.add($n) } } } } for ($n=0;$n -lt ($MARKPOS.count-1);$n++) { if (($MARKPOS[$n+1]-$MARKPOS[$n]) -gt $SEARCHLENGTH) { $RESETPOS.add($MARKPOS[$n]+$SEARCHLENGTH) } } $RESETPOS.add($MARKPOS[$MARKPOS.count-1]+$SEARCHLENGTH) $PIPELINEINPUT=$PIPELINEINPUT.insert($PIPELINEINPUT.length,$RESET) for ($n=$PIPELINEINPUT.length;$n -ge 0;$n--) { if ($RESETPOS -contains $n) { $PIPELINEINPUT=$PIPELINEINPUT.insert($n,$RESET) } if ($MARKPOS -contains $n) { $PIPELINEINPUT=$PIPELINEINPUT.insert($n,$MARK) } } if (-not ($ONLYMATCHING -and (-not ($LINEMATCHED)))) { write-output $PIPELINEINPUT } } elseif (-not ($ONLYMATCHING)) { write-output $PIPELINEINPUT } } end { } }