着色求助输出:如何使用正则判处选择以连字符( - )开头的精确字符串,并以字母结尾

发布于 2025-02-05 04:47:55 字数 921 浏览 2 评论 0原文

我目前正在尝试为PowerShell的Get-Help cmdlet输出上色。我成功地涂上了显示我试图使用Get-Help上的CMDLET名称的输出。我还设法为显示手动页面的所有标题的输出进行了着色。但是,我无法始终看到手动页面上显示的选项的输出,如下所示:

#!/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" `
    }

“在此处输入图像说明”

换句话说,我需要匹配以“ a”的字符串的正则态度 - ”并以字母结尾。

如果有人可以帮助我,我真的很感激。提前致谢。

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]+
quot;, "$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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

财迷小姐 2025-02-12 04:47:55

这是您可以将其放入$ profile文件中,以自动化着Get-Help的输出。它解决了使用REGEX \ b- \ w+(请参阅 REGEX101演示)。

# Overrides the original Get-Help command to colorize its output.

Function Get-Help {
    [CmdletBinding(DefaultParameterSetName='AllUsersView', HelpUri='https://go.microsoft.com/fwlink/?LinkID=2096483')]
    param(
        [Parameter(Position=0, ValueFromPipelineByPropertyName=$true)]
        [ValidateNotNullOrEmpty()]
        [string] ${Name},

        [string] ${Path},

        [ValidateSet('Alias','Cmdlet','Provider','General','FAQ','Glossary','HelpFile','ScriptCommand','Function','Filter','ExternalScript','All','DefaultHelp','DscResource','Class','Configuration')]
        [string[]] ${Category},

        [Parameter(ParameterSetName='DetailedView', Mandatory=$true)]
        [switch] ${Detailed},

        [Parameter(ParameterSetName='AllUsersView')]
        [switch] ${Full},

        [Parameter(ParameterSetName='Examples', Mandatory=$true)]
        [switch] ${Examples},

        [Parameter(ParameterSetName='Parameters', Mandatory=$true)]
        [string[]] ${Parameter},

        [string[]] ${Component},

        [string[]] ${Functionality},

        [string[]] ${Role},

        [Parameter(ParameterSetName='Online', Mandatory=$true)]
        [switch] ${Online},

        [Parameter(ParameterSetName='ShowWindow', Mandatory=$true)]
        [switch] ${ShowWindow}
    )

    process {
        # Call the original Get-Help command by its fully qualified path.
        $help = Microsoft.PowerShell.Core\Get-Help @PSBoundParameters

        # Define the styles for colorization.
        $style = @{
            SECTION = $PSStyle.Formatting.FormatAccent
            COMMAND = $PSStyle.Foreground.BrightYellow
            PARAM   = $PSStyle.Foreground.FromRgb(64,200,230)
        }

        # Escape the command name for use in RegEx
        $commandNameEscaped = [regex]::Escape( $help.Name )

        # Define a RegEx for doing the formatting. The names of the RegEx groups have to match the keys of the $style hashtable.
        $regEx = @(
            "(?m)(?<=^[ \t]*)(?<SECTION>[A-Z][A-Z \t\d\W]+$)"
            "(?<COMMAND>\b$commandNameEscaped\b)"
            "(?<PARAM>\B-\w+)"
        ) -join '|'

        # Format the help object
        $help | Out-String | ForEach-Object {
            [regex]::Replace( $_, $regEx, {  
                # Get the RegEx group that has matched.
                $matchGroup = $args.Groups.Where{ $_.Success }[ 1 ]
                # Use the RegEx group name to select associated style for colorizing the match.
                $style[ $matchGroup.Name ] + $matchGroup.Value + $PSStyle.Reset
            })
        }
    }
}

输出:

“

备注:

  • 通过定义具有与现有命令相同名称的函数,我们有效地覆盖了它。
  • 我们可以通过指定其完全合格的名称来调用原始命令,并使用模块前缀(例如Microsoft.powershell.core \ get-help)来调用原始命令。要获取模块前缀,请键入(get-command thecommand).modulename
  • 使用自动$ PSSTYLE变量作为获取ANSI逃生代码的方便方式。
  • 当我们使用- ?参数调用命令时,这甚至可以工作,因为此调用get-help内部。
  • Regex101 的演示和解释完整模式的解释。
  • 需要 PS 7.2+

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 regex101 demo).

# Overrides the original Get-Help command to colorize its output.

Function Get-Help {
    [CmdletBinding(DefaultParameterSetName='AllUsersView', HelpUri='https://go.microsoft.com/fwlink/?LinkID=2096483')]
    param(
        [Parameter(Position=0, ValueFromPipelineByPropertyName=$true)]
        [ValidateNotNullOrEmpty()]
        [string] ${Name},

        [string] ${Path},

        [ValidateSet('Alias','Cmdlet','Provider','General','FAQ','Glossary','HelpFile','ScriptCommand','Function','Filter','ExternalScript','All','DefaultHelp','DscResource','Class','Configuration')]
        [string[]] ${Category},

        [Parameter(ParameterSetName='DetailedView', Mandatory=$true)]
        [switch] ${Detailed},

        [Parameter(ParameterSetName='AllUsersView')]
        [switch] ${Full},

        [Parameter(ParameterSetName='Examples', Mandatory=$true)]
        [switch] ${Examples},

        [Parameter(ParameterSetName='Parameters', Mandatory=$true)]
        [string[]] ${Parameter},

        [string[]] ${Component},

        [string[]] ${Functionality},

        [string[]] ${Role},

        [Parameter(ParameterSetName='Online', Mandatory=$true)]
        [switch] ${Online},

        [Parameter(ParameterSetName='ShowWindow', Mandatory=$true)]
        [switch] ${ShowWindow}
    )

    process {
        # Call the original Get-Help command by its fully qualified path.
        $help = Microsoft.PowerShell.Core\Get-Help @PSBoundParameters

        # Define the styles for colorization.
        $style = @{
            SECTION = $PSStyle.Formatting.FormatAccent
            COMMAND = $PSStyle.Foreground.BrightYellow
            PARAM   = $PSStyle.Foreground.FromRgb(64,200,230)
        }

        # Escape the command name for use in RegEx
        $commandNameEscaped = [regex]::Escape( $help.Name )

        # Define a RegEx for doing the formatting. The names of the RegEx groups have to match the keys of the $style hashtable.
        $regEx = @(
            "(?m)(?<=^[ \t]*)(?<SECTION>[A-Z][A-Z \t\d\W]+$)"
            "(?<COMMAND>\b$commandNameEscaped\b)"
            "(?<PARAM>\B-\w+)"
        ) -join '|'

        # Format the help object
        $help | Out-String | ForEach-Object {
            [regex]::Replace( $_, $regEx, {  
                # Get the RegEx group that has matched.
                $matchGroup = $args.Groups.Where{ $_.Success }[ 1 ]
                # Use the RegEx group name to select associated style for colorizing the match.
                $style[ $matchGroup.Name ] + $matchGroup.Value + $PSStyle.Reset
            })
        }
    }
}

Output:

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.
  • Demo and explanation of the complete pattern at regex101.
  • Requires PS 7.2+
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文