powershell 自定义快捷键F7搜索弹窗展示历史记录

Install-Module Microsoft.PowerShell.ConsoleGuiTools
code $profile
添加一下代码

# 按f7显示历史记录
function ocgv_history {
  $line = $null
  $cursor = $null
  [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor)
  $selection = $input | Out-ConsoleGridView -Title "Select CommandLine from History" -OutputMode Single -Filter $line
  if ($selection) {
    [Microsoft.PowerShell.PSConsoleReadLine]::DeleteLine()
    [Microsoft.PowerShell.PSConsoleReadLine]::Insert($selection)
    if ($selection.StartsWith($line)) {
      [Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($cursor)
    }
    else {
      [Microsoft.PowerShell.PSConsoleReadLine]::SetCursorPosition($selection.Length)
    }
  }
}

$parameters = @{
  Key = 'F7'
  BriefDescription = 'ShowMatchingHistoryOcgv'
  LongDescription = 'Show Matching History using Out-ConsoleGridView'
  ScriptBlock = {
    param($key, $arg)   # The arguments are ignored in this example
    Get-History | Sort-Object -Descending -Property Id -Unique | Select-Object CommandLine -ExpandProperty CommandLine |  ocgv_history
  }
}
Set-PSReadLineKeyHandler @parameters

$parameters = @{
  Key = 'Shift-F7'
  BriefDescription = 'ShowMatchingGlobalHistoryOcgv'
  LongDescription = 'Show Matching History for all PowerShell instances using Out-ConsoleGridView'
  ScriptBlock = {
    param($key, $arg)   # The arguments are ignored in this example
    $hist = [Microsoft.PowerShell.PSConsoleReadLine]::GetHistoryItems().CommandLine
    # reverse the items so most recent is on top
    [array]::Reverse($hist)
    $hist | Select-Object -Unique -First 1000 | ocgv_history
  }
}
Set-PSReadLineKeyHandler @parameters

自带psreadline的搜索

Set-PSReadLineOption -EditMode Emacs
Set-PSReadLineKeyHandler -Key UpArrow -Function HistorySearchBackward # 设置向上键为后向搜索历史记录
Set-PSReadLineKeyHandler -Key DownArrow -Function HistorySearchForward # 设置向下键为前向搜索历史纪录
posted @ 2021-09-04 11:19  whiter001  阅读(164)  评论(1编辑  收藏  举报