在 powershell 会话结束时自动导出历史记录

sti*_*tib 6 windows powershell command-history conemu

我可以使用主题的 Technet 页面中概述的脚本导出我的 Powershell 历史记录,

Get-History | Export-Clixml ~\PowerShell\history.xml
Run Code Online (Sandbox Code Playgroud)

当我在我的 powershell 配置文件中使用这一行启动 Powershell 会话时,我可以自动加载保存的历史记录,

Import-Clixml ~\PowerShell\history.xml | Add-History
Run Code Online (Sandbox Code Playgroud)

但是有什么办法可以在我退出会话时自动保存我的历史记录?我使用ConEmu作为我的控制台。

use*_*825 5

另一种方法,以防万一它对任何人都有帮助。

Powershell 现在将命令历史自动存储在文件“%userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt”中

为了显示历史记录,我在我的个人资料中添加了一个功能,如下所示......

function h2 {
    $h = [System.Environment]::ExpandEnvironmentVariables("%userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt")
    cat $h;
}
Run Code Online (Sandbox Code Playgroud)

现在我可以输入“h2”来显示完整的历史记录。不是特别聪明,但有效。


Ror*_*ory 0

此答案仅适用于较旧的 PowerShell 版本。至少从版本开始 5 PowerShell自动将历史记录保存到文件中

\n

这是一种替代方法,可以保留您的历史记录,而无需使用不同的 PowerShell 快捷方式。

\n

摘自\n https://software.intel.com/en-us/blogs/2014/06/17/giving-powershell-a-persistent-history-of-commands

\n

在管理员模式下打开 PowerShell,并通过运行以下命令找出您拥有的 PowerShell 版本:

\n
$PSVersionTable.PSVersion\n
Run Code Online (Sandbox Code Playgroud)\n

您需要高于 3 的版本才能运行此程序,如果您有旧版本,请更新它。

\n

通过运行以下命令,允许 PowerShell 导入或使用包括模块的脚本:

\n
set-executionpolicy remotesigned\n
Run Code Online (Sandbox Code Playgroud)\n

安装PsGet并通过执行以下命令安装您需要的模块:

\n
(new-object Net.WebClient).DownloadString("http://psget.net/GetPsGet.ps1") | iex\nimport-module PsGet\ninstall-module PsUrl\ninstall-module PSReadline\n
Run Code Online (Sandbox Code Playgroud)\n

创建以下脚本

\n
$HistoryFilePath = Join-Path ([Environment]::GetFolderPath(\'UserProfile\')) .ps_history\nRegister-EngineEvent PowerShell.Exiting -Action { Get-History | Export-Clixml $HistoryFilePath } | out-null\nif (Test-path $HistoryFilePath) { Import-Clixml $HistoryFilePath | Add-History }\n# if you don\'t already have this configured...\nSet-PSReadlineKeyHandler -Key UpArrow -Function HistorySearchBackward\nSet-PSReadlineKeyHandler -Key DownArrow -Function HistorySearchForward\n
Run Code Online (Sandbox Code Playgroud)\n

将文件另存为C:\\Users\\<username>\\Documents\\WindowsPowerShell\\Microsoft.PowerShell_profile.ps1,您应将其中替换为 PC 上正确的文件夹名称。不要忘记将 \xe2\x80\x9csave as type\xe2\x80\x9d 选项更改为所有文件。

\n

关闭 PowerShell 并再次打开它,以便它开始使用我们保存的脚本。

\n

今后,

\n
get-history\n
Run Code Online (Sandbox Code Playgroud)\n

将检索您输入的最后几百个命令,您可以使用箭头键在它们之间滚动。

\n

  • 尽我所能解释,并更新为独立答案。我花了 5 分钟吃早餐。如果人们都修复了自己的答案,并在可能的情况下提供帮助,那就太好了,我已经得到了一些答案,这些答案被其他人极大地改进了,这就是为什么我们拥有编辑权,不是吗? (2认同)