在Windows 10 Powershell中通过F7使命令历史记录弹出窗口起作用

How*_*man 2 powershell windows-10

在Powershell控制台中,在Windows 10(10.0.17134.0)上,F7不会像对CMD控制台那样弹出命令历史记录。有没有解决的办法?

Bil*_*art 9

正如您所发现的,这是因为Windows 10上默认安装了PSReadline模块。您可以F7通过Set-PSReadlineKeyHandler在脚本中使用cmdlet在PSReadline中添加自己的模块。例:

Set-PSReadlineKeyHandler -Key F7 -BriefDescription "History" -LongDescription "Show command history" -ScriptBlock {
  $pattern = $null
  [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref] $pattern, [ref] $null)
  if ( $pattern ) {
    $pattern = [Regex]::Escape($pattern)
  }
  $history = [System.Collections.ArrayList] @(
    $last = ""
    $lines = ""
    foreach ( $line in [System.IO.File]::ReadLines((Get-PSReadlineOption).HistorySavePath) ) {
      if ( $line.EndsWith('`') ) {
        $line = $line.Substring(0, $line.Length - 1)
        $lines = if ( $lines ) { "$lines`n$line" } else { $line }
        continue
      }
      if ( $lines ) {
        $line = "$lines`n$line"
        $lines = ""
      }
      if ( ($line -cne $last) -and ((-not $pattern) -or ($line -match $pattern)) ) {
        $last = $line
        $line
      }
    }
  )
  $command = $history | Out-GridView -Title History -PassThru
  if ( $command ) {
    [Microsoft.PowerShell.PSConsoleReadLine]::RevertLine()
    [Microsoft.PowerShell.PSConsoleReadLine]::Insert(($command -join "`n"))
  }
}
Run Code Online (Sandbox Code Playgroud)

使用此功能时,该F7键将显示在弹出的网格视图窗口中。选择一个历史记录条目,然后按Enter,PowerShell会将其放在命令行上进行编辑。

  • 上面的代码块的末尾还有一个额外的`}`。编辑出来会很好。 (2认同)

How*_*man 2

是的,一种解决方法是:https://www.reddit.com/r/PowerShell/comments/4x5iig/f7_history_no_longer_in_windows_10_au/

Remove-Module -Name PSReadLine从命令行运行。它将从该会话PSReadLine中删除该模块。让我们再次按F7来显示历史记录。

  • 我不推荐此解决方案,因为它会禁用所有“PSReadline”模块的优点并恢复为标准控制台输入功能。 (2认同)