Windows PowerShell持久性历史记录

ale*_*ard 11 windows powershell command-line-interface

在Windows PowerShell中找到了这种保存历史记录的优秀方法.

# Persistent History
# Save last 200 history items on exit
$MaximumHistoryCount = 200
$historyPath = Join-Path (split-path $profile) history.clixml

# Hook powershell's exiting event & hide the registration with -supportevent (from nivot.org)
Register-EngineEvent -SourceIdentifier powershell.exiting -SupportEvent -Action {
    Get-History -Count $MaximumHistoryCount | Export-Clixml (Join-Path (split-path $profile) history.clixml)
}

# Load previous history, if it exists
if ((Test-Path $historyPath)) {
    Import-Clixml $historyPath | ? {$count++;$true} | Add-History
    Write-Host -Fore Green "`nLoaded $count history item(s).`n"
}

# Aliases and functions to make it useful
New-Alias -Name i -Value Invoke-History -Description "Invoke history alias"
Rename-Item Alias:\h original_h -Force
function h { Get-History -c  $MaximumHistoryCount }
function hg($arg) { Get-History -c $MaximumHistoryCount | out-string -stream | select-string $arg }
Run Code Online (Sandbox Code Playgroud)

但是,当我将其粘贴到我的$ PROFILE并重新启动PowerShell时,我收到以下错误:

Register-EngineEvent : Missing an argument for parameter 'Action'. Specify a parameter of type
'System.Management.Automation.ScriptBlock' and try again.
At D:\path\to\WindowsPowerShell\Microsoft.PowerShell_profile.ps1:20 char:73
+ Register-EngineEvent -SourceIdentifier powershell.exiting -SupportEvent -Action
+                                                                         ~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Register-EngineEvent], ParameterBindingException
    + FullyQualifiedErrorId : MissingArgument,Microsoft.PowerShell.Commands.RegisterEngineEventCommand

jhc*_*ark 8

与此问题非常相关的是"如何使用向上/向下箭头访问我的历史记录?" 该PSReadLine模块解决了这个:

Install-Package PSReadLine
Run Code Online (Sandbox Code Playgroud)

然后加:

Import-Module PSReadLine
Run Code Online (Sandbox Code Playgroud)

对你的$profile.


Kei*_*ill 1

这是我保存历史记录时使用的代码:

$historyPath = Join-Path (split-path $profile) "history-$(Get-Date -f o).clixml"
Register-EngineEvent -SourceIdentifier powershell.exiting -SupportEvent -Action {
    Get-History | Export-Clixml $historyPath
}.GetNewClosure()
Run Code Online (Sandbox Code Playgroud)

用于GetNewClosure()捕获$historyPath变量 IIRC。