Tested with PowerShell v7.3.6 and PSReadLine v2.3.1-beta1. It should also work with later versions but not with older ones (can even cause loss of command history).
Steps:
-
Run the following command to update PSReadLine in PowerShell. (VERY IMPORTANT!)
Update-Module PSReadLine -AllowPrerelease
-
Add the following code to your PowerShell profile:
Set-PSReadLineOption -AddToHistoryHandler { # A hack to keep each item unique in the history file. param([string]$itemNew) $historyFile = (Get-PSReadLineOption).HistorySavePath if (!(Test-Path $historyFile)) { return $true } $items = [ordered]@{} $sb = [System.Text.StringBuilder]::new() Get-Content $historyFile | ForEach-Object { if ($_.Length -eq 0) { return } [void]$sb.Append($_) if ($_.EndsWith('`')) { [void]$sb.Append("`n") return } $item = $sb.ToString() if ($items.Contains($item)) { $items.Remove($item) } $items.Add($item, $null) [void]$sb.Clear() } if ($items.Contains($itemNew)) { $items.Remove($itemNew) } $items.Keys | Out-File $historyFile -Force return $true }
-
Restart PowerShell.