Powershell: Do not add space-prefixed commands to history (like in bash/zsh)

Created on 21 Aug 2019  路  3Comments  路  Source: PowerShell/PowerShell

In bash and zsh there are very useful options to avoid adding commands to the shell history when they are prefixed with a space:

It would be nice if PS had this feature as well, since sometimes you want to run some long command, knowing that you won't need it again, and thus not bother adding it to the history. This is particularly useful when using a very large max history size (in my zsh I have more than 10000, since I like having access to all commands I executed).

It would also be useful when some other program runs a shell command, since those are usually even more meaningless when you later use a shell "manually".

Issue-Enhancement

Most helpful comment

@ThiefMaster : I use following code in my profile to make sure that any command with spaces or tabs at the beginning of the line is not added to the PSReadLine history. In addition it also prevents clear text passwords to be stored in the command history.

Set-PSReadLineOption -AddToHistoryHandler {
        param($line)
        $line -notmatch '^\s+|AsPlainText'
}

All 3 comments

@lzybkr would this be a PSReadLine issue?

And if I recall correctly, I remember hearing mention that PSReadLine has a way to handle this, but I don't recall exactly how to do it. 馃槙

Add something like this to your profile:

$options = @{
    MaximumHistoryCount           = 10000
    HistoryNoDuplicates           = $true
    HistorySearchCursorMovesToEnd = $true
    AddToHistoryHandler           = {
        param([string]$line)
        return $line.Length -gt 3 -and $line[0] -ne ' '
    }
}

Set-PSReadLineOption @options

The AddToHistoryHandler is the relevant parameter.

@ThiefMaster : I use following code in my profile to make sure that any command with spaces or tabs at the beginning of the line is not added to the PSReadLine history. In addition it also prevents clear text passwords to be stored in the command history.

Set-PSReadLineOption -AddToHistoryHandler {
        param($line)
        $line -notmatch '^\s+|AsPlainText'
}
Was this page helpful?
0 / 5 - 0 ratings