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?
Asked
Active
Viewed 1,940 times
4
-
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 docs](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/clear-history?view=powershell-6) – I.T Delinquent Aug 29 '19 at 08:15
-
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. – loki Aug 29 '19 at 08:43
-
1IMO that wouldn't make sense when pasting code with indents. Take a look at [PSReadLine](https://learn.microsoft.com/en-us/powershell/module/psreadline/?view=powershell-5.1) **Hint** if you don't want some entries in the history, inspect `&(Get-PSReadLineOption).HistorySavePath` from time to time. – Aug 29 '19 at 10:17
1 Answers
10
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
}

chutz
- 2,256
- 2
- 25
- 38
-
2While 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. – Eric Bouchard Feb 09 '21 at 22:29
-
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. – chutz Feb 10 '21 at 02:55
-
1Found the simpler syntax over here https://stackoverflow.com/a/64256603/1213346 so updated the answer. – chutz Dec 02 '21 at 04:34