Search code examples
powershellpsreadline

PSReadline history - delete one entry from history list


While customizing my PS profile with the great PSReadline sample example, I had the idea to try to delete a specific history entry from the history ListView format.

For example I have the following Powershell Listview with history command to delete

Ideally, I'd like to delete the highlighted entry from the history with the "Del" keystroke, but I don't know how to script that or get started by using the Set-PSReadLineKeyHandler CmdLet

Any suggestions ?


Solution

  • It's not ideal, it can be slow depending on the size of your history file, but this worked in my session. The caveat is that even if you remove a line from the .HistorySavePath file, the history item will still be visible as a completion item until you restart the session. Based on PSReadLine Issue #494, the way you can "refresh" without restarting is to clear the history and re-add the content lines excluding the item to remove.

    Set-PSReadLineKeyHandler -Chord Ctrl+Shift+Delete -ScriptBlock {
        $in = ''
        [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref] $in, [ref] $null)
    
        if ([string]::IsNullOrWhiteSpace($in)) {
            return
        }
    
        $historyPath = (Get-PSReadLineOption).HistorySavePath
    
        # only way to "refresh" the history in the current session is to clear it
        [Microsoft.PowerShell.PSConsoleReadLine]::ClearHistory()
        $content = [System.IO.File]::ReadAllLines($historyPath)
        Clear-Content $historyPath
    
        foreach ($line in $content) {
            if ($line.StartsWith($in, [System.StringComparison]::InvariantCultureIgnoreCase)) {
                continue
            }
    
            # and re-add it (excluding the line to remove)
            [Microsoft.PowerShell.PSConsoleReadLine]::AddToHistory($line)
        }
    
        [Microsoft.PowerShell.PSConsoleReadLine]::DeleteLine()
    }