shellpowershellinput-history

How to prevent save input history that begins with a space in PowerShell?


In bash (at least in Ubuntu), it is possible not to save commands starting with a space in the history (HISTCONTROL). Is there a way to get this feature in Powershell?


Solution

  • Since at least PowerShell 5.1 you can use Set-PSReadlineOption's -AddToHistoryHandler to validate if a command should be added to the history with a custom function.

    -AddToHistoryHandler Specifies a ScriptBlock that controls which commands get added to PSReadLine history.

    The ScriptBlock receives the command line as input. If the ScriptBlock returns $True, the command line is added to the history.

    And for completeness, here is a code sample you can add to your $PROFILE.CurrentUserAllHosts

    Set-PSReadLineOption -AddToHistoryHandler {
        param($command)
        if ($command -like ' *') {
            return $false
        }
        # Add any other checks you want
        return $true
    }