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

1

5

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?

Maxon answered 29/8, 2019 at 7:53 Comment(3)
I don't think so. You can get and clear the history but I don't think you can omit certain items from it. Check out the docsMenses
Ok, thanks, I will check. But this feature is very useful for quick simple calculation (for example, 2 + 2, 12654 * 13, etc.) or changing folders (cd) without saving them in history.Maxon
IMO that wouldn't make sense when pasting code with indents. Take a look at PSReadLine Hint if you don't want some entries in the history, inspect &(Get-PSReadLineOption).HistorySavePath from time to time.Tachistoscope
M
14

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
} 
Macula answered 16/7, 2020 at 14:4 Comment(3)
While commands starting with a space won't be saved to the file (Get-PSReadLineOption).HistorySavePath, it does not affect the command Get-History. Entries beginning with space will still be outputed.Vaccine
Interesting comment. Indeed, Get-History does return the command with the leading space. I do not know how Get-History is really used, because when using the arrow up or Control P or Control R to recall recent commands, the command is not shown.Macula
Found the simpler syntax over here https://mcmap.net/q/1922550/-can-39-t-set-any-value-for-addtohistoryhandler-in-powershell so updated the answer.Macula

© 2022 - 2024 — McMap. All rights reserved.