PowerShell history: how do you prevent duplicate commands?

Viewed 4046

Background:

PowerShell history is a lot more useful to me now that I have a way to save history across sessions.

# Run this every time right before you exit PowerShell
get-history -Count $MaximumHistoryCount | export-clixml $IniFileCmdHistory;

Now, I am trying to prevent PowerShell from saving duplicate commands to my history.

I tried using Get-Unique, but that doesn't work since every command in the history is "unique", because each one has a different ID number.

3 Answers

The following command works for PowerShell in Windows 10 (tested in v.1803). The option is documented here.

Set-PSReadLineOption –HistoryNoDuplicates:$True

In practice, calling PowerShell with the following command (e.g. saved in a shortcut) opens PowerShell with a history without duplicates

%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -NoExit -Command Set-PSReadLineOption –HistoryNoDuplicates:$True

Not directly related to duplicates, but similarly useful, this AddToHistoryHandler script block in my $PROFILE keeps short and simple commands out of my history:

$addToHistoryHandler = {
    Param([string]$line)
    if ($line.Length -le 3) {
        return $false
    }
    if (@("exit","dir","ls","pwd","cd ..").Contains($line.ToLowerInvariant())) {
        return $false
    }
    return $true
}
Set-PSReadlineOption -AddToHistoryHandler $addToHistoryHandler
Related