我可以使用正则表达式通过 CTRL+R 反向搜索来搜索 PowerShell 命令历史记录吗?

Tre*_*van 5 powershell

我运行了一系列 PowerShell 命令,我想通过CTRL + R使用正则表达式的后退搜索功能搜索历史记录。要么它现在没有实施,要么我做错了什么。

想象一下,您的历史记录中有一条命令: ssh username@host.name

我想按下CTRL+R并键入ssh.*host以将此命令返回到我的 PowerShell 提示符。现在,这似乎不起作用。

问题:我可以使用正则表达式通过 CTRL+R 反向搜索来搜索 PowerShell 命令历史记录吗?

预期结果

反向搜索返回基于正则表达式的结果。

back-i-search: <expression>
Run Code Online (Sandbox Code Playgroud)

实际结果

向后搜索失败。

failed-bck-i-search: <expression>
Run Code Online (Sandbox Code Playgroud)

rad*_*row 0

yyyyeach,你可以。shell 不会给您太多帮助,但没有什么可以阻止您开发自己的脚本来模拟这种行为。 PSReadLine在这里可以派上用场。看一下这个:

Set-PSReadlineKeyHandler -Chord Ctrl+r -ScriptBlock {
    $currentInput = $null
    [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref] $currentInput, [ref] $null)

    $entries = [Microsoft.PowerShell.PSConsoleReadLine]::GetHistoryItems() | Where-Object CommandLine -match $currentInput | Select-Object CommandLine | ForEach-Object {$_.CommandLine.ToString()}
    $pointer = $entries.Count - 1

    while($pointer -ge 0 -and $pointer -lt $entries.Count) {
         [Microsoft.PowerShell.PSConsoleReadLine]::BeginningOfLine()
         [Microsoft.PowerShell.PSConsoleReadLine]::KillLine()
         [Microsoft.PowerShell.PSConsoleReadLine]::Replace(0, 0, $entries[$pointer])

        $userInp = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown").VirtualKeyCode

        if($userInp -eq 38) {
            $pointer -= 1;
        } elseif($userInp -eq 40) {
            $pointer += 1;
        } elseif($userInp -eq 13) {
            [Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine()
            break;
        } else {
            break;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

用法

输入你的表情

PS> ssh.*host
Run Code Online (Sandbox Code Playgroud)

ctrl+r。输入应替换为与正则表达式匹配的最后一个条目。

PS> ssh cobolcourse@mainserver.host
Run Code Online (Sandbox Code Playgroud)

现在您可以使用向上和向下箭头来浏览历史记录。按enter接受或按其他按钮取消。

怎么运行的

该脚本只是读取所有PSReadLine历史记录,用您需要的内容对其进行过滤并将其提供给一个数组$entries。然后,它会扫描按下的按键以捕捉箭头以进行导航,并将当前提示替换为上次访问的条目。

它非常简单,而且很可能容易出现边缘情况,但我认为您可以进一步修改它。如果你想提高性能,你可以尝试利用管道,但使其交互会变得更具挑战性。无论如何,祝你好运!