如何防止在 PowerShell 中保存以 space 开头的输入历史记录?

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

在bash中(至少在Ubuntu中),可以不在历史(HISTCONTROL)中保存以space开头的命令。 有没有办法在 Powershell 中获得此功能?

至少从 PowerShell 5.1 开始,您可以使用 Set-PSReadlineOption-AddToHistoryHandler 来验证是否应使用自定义函数将命令添加到历史记录中。

-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.

为了完整起见,这里有一个代码示例,您可以将其添加到 $PROFILE.CurrentUserAllHosts

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