在Windows Server 2016中,我如何查看跨所有PowerShell会话的命令历史记录?

165

您在Windows Server 2016中可以查看所有会话的完整历史记录吗?

以下PowerShell命令仅包括当前会话的命令:

Get-History
7个回答

325
在PowerShell中输入以下命令:
(Get-PSReadlineOption).HistorySavePath

这会给你提供所有历史记录保存的路径。然后在文本编辑器中打开该路径。

尝试在PowerShell中使用cat (Get-PSReadlineOption).HistorySavePath列出历史记录。


3
实际上,在安装全新的Windows Server 2016时,默认情况下已经包含了该功能。 - Daniel Leach
3
这个功能是在我的Windows 10 Pro (1703)上。但我不知道它是否是默认存在的,还是由Visual Studio或其他类似的工具安装了一些模块。尽管如此,在我最近蓝屏后,它帮助了我。 - Martini Bianco
3
基本上,只需使用简单的命令 cat (Get-PSReadlineOption).HistorySavePath 就可以获取整个历史记录。谢谢 @DanielLeach。 - ulkas
5
使用cat (Get-PSReadlineOption).HistorySavePath | select -Last 10命令来获取最近的10条历史记录。如果你的历史记录很长,这个命令会非常有用。 - JWo
6
为什么这不是历史命令的默认行为? - wero026
显示剩余8条评论

24

我使用以下命令来从PowerShell获取完整的历史记录并将输出保存到文件:

Get-Content (Get-PSReadlineOption).HistorySavePath > D:\PowerShellHistory.txt

5
将历史文件的内容获取并倾倒到另一个文件似乎有点多余。您可以只需执行 copy (Get-PSReadlineOption).HistorySavePath d:\PowerShellHistory.txt - Adam Plocher

12

在Windows PowerShell中

要进入会话,您可以使用hhistory

但是要获取计算机中编写的所有命令,您需要使用

cat (Get-PSReadlineOption).HistorySavePath


10

既然你使用的是Windows系统,你也可以使用以下方式打开“记事本”。

notepad (Get-PSReadlineOption).HistorySavePath

5

虽然提到了Windows Server / Enterprise版本,但作为专业版(标准零售版)用户,HistorySavePath也对我可用。 我需要查看在旧会话中最近安装的Python软件包,并希望在此处为寻找历史记录中的特定内容的人添加一个答案。

# if you like file names and line numbers included in your output
Select-String "<search pattern>" (Get-PSReadlineOption).HistorySavePath

# if you Just want the text without any of the other information
Get-Content (Get-PSReadlineOption).HistorySavePath | Select-String "<search pattern>" 

在我的情况下,我运行了

Select-String 'pip install' (Get-PSReadlineOption).HistorySavePath

这给了我一个从以前会话中运行的pip安装命令列表。

...
[Path/To/File]:10401:pip install dash
[Path/To/File]:10824:pip install -r .\requirements.txt
[Path/To/File]:11296:pip install flask-mysqldb
[Path/To/File]:11480:pip install Flask-Markdown
[Path/To/File]:11486:pip install pygments
[Path/To/File]:11487:pip install py-gfm
[Path/To/File]:11540:pip install bs4

1

Psreadline模块2.1 beta1在Powershell gallery上(仅适用于Powershell 7)https://www.powershellgallery.com/packages/PSReadLine/2.1.0-beta1,使用保存的历史记录在命令行上进行智能感知:https://github.com/PowerShell/PSReadLine/issues/1468。它已经开始在Vscode中显示。https://www.reddit.com/r/PowerShell/comments/g33503/completion_on_history_in_vscode/

此外,在Psreadline中,您可以使用f8或control-R向后搜索保存的历史记录(在输入命令行后)。Get-psreadlinekeyhandler列出了键绑定。

get-psreadlinekeyhandler -bound -unbound | ? function -match history

有没有一种方法可以通过给出命令的ID来执行历史记录中的先前命令?就像在bash中,您输入“history”,然后说您想再次运行第20个命令,然后只需执行“!20”。 - leo
1
@leo 我不知道,这是文档链接,你可以查看键绑定 https://learn.microsoft.com/zh-cn/powershell/module/psreadline/?view=powershell-7.2 - js2010

0

你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心找到有关如何编写良好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接