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?
How to prevent save input history that begins with a space in PowerShell?
Asked Answered
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
}
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.
&(Get-PSReadLineOption).HistorySavePath
from time to time. – Tachistoscope