如何从以前的会话中搜索 Powershell 命令历史记录

sha*_*2na 32 windows powershell

我使用当前的 Windows 10 和 Powershell 5.1。通常,我想查找我过去使用过的命令来修改和/或重新运行它们。不可避免地,我正在寻找的命令是在以前的或不同的 PowerShell 窗口/会话中运行的。

当我敲击?钥匙时,我可以浏览许多来自许多会话的许多命令,但是当我尝试使用 搜索它们时Get-History | Where-Object {$_.CommandLine -Like "*docker cp*"},我没有得到任何结果。基本的故障排除显示Get-History没有显示以前会话中的任何内容,如下所示:

C:\Users\Me> Get-History

  Id CommandLine
  -- -----------
   1 Get-History | Where-Object {$_.CommandLine -Like "*docker cp*"}
Run Code Online (Sandbox Code Playgroud)

如何?使用密钥Get-History或其他 Cmdlet搜索先前提供的命令?

jsc*_*ott 40

您提到的持久历史记录由PSReadLine提供。它与 session-bound 分开Get-History

历史记录存储在由属性定义的文件中(Get-PSReadlineOption).HistorySavePath。使用Get-Content (Get-PSReadlineOption).HistorySavePath或文本编辑器等查看此文件。使用 来检查相关选项Get-PSReadlineOption。PSReadLine 还通过ctrl+执行历史搜索r

使用您提供的示例:

Get-Content (Get-PSReadlineOption).HistorySavePath | ? { $_ -like '*docker cp*' }


Moh*_*han 25

  • Ctrl+R然后开始输入,以交互方式在历史记录中向后搜索。这匹配来自命令行中任何位置的文本。再次按Ctrl+R查找下一个匹配项。
  • Ctrl+S像上面一样工作,但在历史中向前搜索。您可以使用Ctrl+ R/ Ctrl+S在搜索结果中来回切换。
  • 键入文本,然后按F8。这将搜索历史记录中以当前输入开始的前一项。
  • Shift+ 的F8作用类似于F8,但向前搜索。

更多信息

正如@jscott 在他/她的回答中提到的,Windows 10 中的 PowerShell 5.1 或更高版本使用该PSReadLine模块来支持命令编辑环境。可以使用Get-PSReadLineKeyHandlercmdlet检索此模块的完整键映射。要查看与历史记录相关的所有键映射,请使用以下命令:

Get-PSReadlineKeyHandler | ? {$_.function -like '*hist*'}
Run Code Online (Sandbox Code Playgroud)

这是输出:

History functions
=================
Key       Function              Description
---       --------              -----------
Alt+F7    ClearHistory          Remove all items from the command line history (not PowerShell history)
Ctrl+s    ForwardSearchHistory  Search history forward interactively
F8        HistorySearchBackward Search for the previous item in the history that starts with the current input - like
                                PreviousHistory if the input is empty
Shift+F8  HistorySearchForward  Search for the next item in the history that starts with the current input - like
                                NextHistory if the input is empty
DownArrow NextHistory           Replace the input with the next item in the history
UpArrow   PreviousHistory       Replace the input with the previous item in the history
Ctrl+r    ReverseSearchHistory  Search history backwards interactively
Run Code Online (Sandbox Code Playgroud)

  • 超级好用!请注意,多次按“Ctrl+R”将循环显示结果。 (2认同)
  • 这非常有用。你是个天才,谢谢你。 (2认同)