Search notes:

PowerShell: Coloring the output of a command

This example tries to demonstrate how the output of a PowerShell command can be colorized with ANSI escape sequences.

create-file.ps1

For this example, we need a dummy file (xyz.txt) which is created with the following set-content cmdlet:
set-content  `
   xyz.txt   `
  -noNewLine `
  "one`r`ntwo`nthree`r`nfour`r`nfive`n"
Github repository about-PowerShell, path: /host/ANSI/color-output/create-file.ps1

format-hex

We then use format-hex on this file.
A regular expression finds new line (byte) characters (0x0a and 0x0d); the replacement part embeds these characters into the escape secuences for red and reset:
format-hex xyz.txt |
out-string -stream |
foreach-object {
   $line = $_
 #
 #  Only apply coloring replacement on lines that don't start
 #  with a white spce;
 #
   if ($line -match '^\S') {
      $line = $line -replace '(\b0[AD]\b)', "$([char]27)[38;5;9m`$1$([char]27)[0m"
   }
   $line
}
Github repository about-PowerShell, path: /host/ANSI/color-output/format-hex.ps1

Result

In the result, the new line characters are now highlighted, which makes it easier, for example, to spot DOS or Unix line endings:

See also

SQL*Plus/Powershell: Color error messages when running a script
PowerShell: ANSI colors

Index