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

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

我可以使用以下脚本导出我的 Powershell 历史记录有关该主题的 Technet 页面

Get-History | Export-Clixml ~\PowerShell\history.xml

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

Import-Clixml ~\PowerShell\history.xml | Add-History

但是,有什么方法可以在我退出会话时自动保存我的历史记录吗?我正在使用康埃穆作为我的控制台。

答案1

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

这是无需使用其他 PowerShell 快捷方式即可保留历史记录的替代方法。

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

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

$PSVersionTable.PSVersion

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

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

set-executionpolicy remotesigned

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

(new-object Net.WebClient).DownloadString("http://psget.net/GetPsGet.ps1") | iex
import-module PsGet
install-module PsUrl
install-module PSReadline

创建以下脚本

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

将文件另存为C:\Users\<username>\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1,其中应替换为您电脑上的正确文件夹名称。不要忘记将“另存为类型”选项更改为所有文件。

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

今后,

get-history

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

答案2

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

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;
}

现在我只需输入“h2”即可显示完整历史记录。虽然不是特别聪明,但很有效。

答案3

虽然并不完美,但是您可以使用带有启动命令的快捷方式,告诉 PowerShell 在退出时保存所有历史记录。

  1. 右键单击桌面并选择新的->捷径
  2. 输入以下内容作为快捷方式路径:
powershell -NoExit -Command $histlog = Register-EngineEvent -SourceIdentifier ([System.Management.Automation.PsEngineEvent]::Exiting) -Action {Get-History | Export-Clixml ~\PowerShell\history.xml}
  1. 选择快捷方式的名称,然后单击好的

如果你从此快捷方式启动,你的历史记录将保存到~\PowerShell\history.xml每当 PowerShell 获得退出事件时。

相关内容