PersistentHistory.psm1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
$historyPath = Join-Path (split-path $profile) history.csv function Save-HistoryAll() { $history = Get-History -Count $MaximumHistoryCount [array]::Reverse($history) $history = $history | Group CommandLine | Foreach {$_.Group[0]} [array]::Reverse($history) $history | Export-Csv $historyPath } function Test-HistoryToSave($historyEntry) { $historyEntry.CommandLine.Length -gt 2 } function Save-HistoryIncremental() { # Get-History -Count $MaximumHistoryCount | Group CommandLine | Foreach {$_.Group[0]} | Export-Csv $historyPath Get-History -Count 1 | ? { Test-HistoryToSave $_ } | Export-Csv -Append $historyPath } # hook powershell's exiting event & hide the registration with -supportevent. #Register-EngineEvent -SourceIdentifier powershell.exiting -SupportEvent -Action { Save-History } $oldPrompt = Get-Content function:\prompt if( $oldPrompt -notlike '*Save-HistoryIncremental*' ) { $newPrompt = @' Save-HistoryIncremental '@ $newPrompt += $oldPrompt $function:prompt = [ScriptBlock]::Create($newPrompt) } # load previous history, if it exists if ((Test-Path $historyPath)) { $loadTime = ( Measure-Command { Import-Csv $historyPath | Add-History Save-HistoryAll Clear-History Import-Csv $historyPath | ? {$count++;$true} | Add-History } ).totalseconds Write-Host -Fore Green "`nLoaded $count history item(s) in $loadTime seconds.`n" } function Search-History() { <# .SYNOPSIS Retrive and filter history based on query .DESCRIPTION .PARAMETER Name .EXAMPLE .LINK #> param( [string[]] $query ) $history = Get-History -Count $MaximumHistoryCount foreach ($item in $query){ $item = $item.ToLower() $history = $history | where {$_.CommandLine.ToLower().Contains($item)} } $history } |