Home > Mobile >  Colorizing Get-Help output: how to use Regex to select exact string that starts with a hyphen(-) and
Colorizing Get-Help output: how to use Regex to select exact string that starts with a hyphen(-) and

Time:06-10

I'm currently trying to color my PowerShell's Get-Help cmdlet output. I successfully colored the output that shows the name of the cmdlet that I'm trying to use Get-Help on. I've also managed to color the output that shows all the headings of manual page. However, I'm unable to consistently color the output of the options shown on the manual page as you can see below:

#!/usr/bin/env powershell

$GREEN = "$([char]0x1b)[92m"
$RED = "$([char]0x1b)[91m"
$CYAN = "$([char]0x1b)[96m"
$BLUE = "$([char]0x1b)[94m" 
$YELLOW = "$([char]0x1b)[93m" 
$PURPLE = "$([char]0x1b)[95m" 
$RESET = "$([char]0x1b)[0m"

 
Get-Help @args > man_text.txt
$WORD = $args[0]

cat man_text.txt | `
    % {$_ `
         -creplace "^[A-Z \d\W] $", "$GREEN`$0$RESET" `
         -creplace "\b$WORD\b", "$YELLOW`$0$RESET" `
         -replace "-[a-z]*\b", "$CYAN`$0$RESET" `
    }

enter image description here

In other words, I need the regex that matches a string that starts with a "-" and ends with an alphabet.

I would really appreciate if someone could help me with this. Thanks in advance.

CodePudding user response:

This is something you could put into your $Profile file to automatically colorize output of Get-Help. It fixes the problem of colorizing the parameters using RegEx \B-\w (see Console Output

Remarks:

  • By defining a function with the same name as an existing command, we effectively override it.
  • We can call the original command by specifying its fully qualified name, with module prefix like Microsoft.PowerShell.Core\Get-Help. To get the module prefix, type (Get-Command TheCommand).ModuleName.
  • Using the automatic $PSStyle variable as a handy way to get ANSI escape codes for coloring.
  • This even works when we call a command with -? parameter, as this calls Get-Help internally.
  • Requires PS 7.2
  • Related