Coloring array filters in PowerShell

Viewed 56

Trying to figure out how to color certain filters within an array for ease of reading on console. In other words, as the console progress forward, if "[Behaviour] OnPlayerJoined" appears, color that text green.

$filters = @(
################## FILTERS ##################
"[Behaviour] OnPlayerJoined",
"[Behaviour] OnPlayerLeft ",
"[API] Received Notification: <Notification"
#############################################
)
mode 300
$host.UI.RawUI.ForegroundColor = "White"
$host.UI.RawUI.BackgroundColor = "Black"
cd C:\Users\$env:UserName\AppData\LocalLow\VRChat\VRChat
$taco = Get-ChildItem -Attributes !Directory . | Sort-Object -Descending -Property LastWriteTime | select -First 1
Get-Content -Path $taco.name -Wait | Select-String -Pattern $filters -SimpleMatch
1 Answers
  • In PowerShell (Core) 7+, you get the desired behavior automatically: in the for-display output for each matching line, Select-String now highlights the part(s) that matched.

    • However, you don't get to control the color for highlighting, which is based on inverting (swapping) the current background and foreground colors; e.g., executing 'oof', 'barn', 'baz' | Select-String 'oo', 'ar', 'az' prints:
      • screenshot PSv7
    • You can opt-out of highlighting with -NoEmphasis.
  • In Windows PowerShell, you'll have to implement your own solution - see below.

The following is a limited solution that would work in your case:

'oof', 'barn', 'baz' |             # sample input
  Select-String 'oo', 'ar', 'az' | # search for sample patter
  ForEach-Object {                 # print the matching parts in green
    $m = $_.Matches[0]
    if ($m.Index -ge 1) { Write-Host -NoNewLine $_.Line.Substring(0, $m.Index) }
    Write-Host -NoNewline -ForegroundColor Green $_.Line.Substring($m.Index, $m.Length)
    Write-Host $_.Line.Substring($m.Index + $m.Length)
  }

Sample output:

screenshot custom implementation

Note:

  • Highlighting multiple matches per input string, in case the -AllMatches switch was specified, is not supported by the above.

  • The C# source code of PowerShell (Core) 7+'s built-in implementation, which does support -AllMatches is in method EmphasizeLine() in class MatchString.cs; permalink as of this writing is here. Note that coloring is achieved by embedding VT (ANSI) escape sequences in the output strings.

  • For a general-purpose pattern-based output-coloring solution, see this answer, which defines custom function Out-HostColored, also available as a Gist.

Related