无法在 PowerShell 中为 AddToHistoryHandler 设置任何值

Can't set any value for AddToHistoryHandler in PowerShell

我在 the docs for PSReadLineOption 中读到,我可以控制执行的命令行是否记录在历史记录中。我试过用多种不同的方式设置它,就像这样。

Set-PSReadLineOption -AddToHistoryHandler $true
Set-PSReadLineOption -AddToHistoryHandler "true"
Set-PSReadLineOption -AddToHistoryHandler "True"
(Get-PSReadLineOption).AddToHistoryHandler = $true
(Get-PSReadLineOption).AddToHistoryHandler = "true"
(Get-PSReadLineOption).AddToHistoryHandler = "True"

我收到了一组关于类型不可转换的各种错误。这表明我找错了树,试图修复分配参数的语法。

Cannot bind parameter 'AddToHistoryHandler'. Cannot convert value "True" to type "System.Func`2[System.String,System.Boolean]".

Cannot bind parameter 'AddToHistoryHandler'. Cannot convert the "true" value of type "System.String" to type "System.Func`2[System.String,System.Boolean]".

Exception setting "AddToHistoryHandler": "Cannot convert value "True" to type "System.Func`2[System.String,System.Boolean]".

当我 运行 命令只是检查当前值时,我在 return 中什么也没有得到。我的意思是 nothing 就像 根本没有输出,没有空行,没有错误 。这让我更加困惑。

(Get-PSReadLineOption).AddToHistoryHandler

好像这个选项在我的 PS 中根本不可用,但保留了下来。不可否认,关闭历史记录是毫无意义的,我觉得这不是一个需要的选项。事实上,历史现在按照我的意愿运作,所以我的问题相当学术。我尝试了不同的设置,这让我觉得这个设置似乎没有按预期工作。我想明白。

此 属性 包含 returns 对或错的脚本块。如果脚本块 returns 为真,该值将被添加到历史记录中。例如,您可以定义像 less 3 字符这样的短命令不会添加到历史记录中

代码示例:

$ScriptBlock = { 
Param([string]$line) 
    
    #This example will only save commands longer or equal 3 characters and no help command
    if ($line.length -ge 3 -and $line -notmatch "^get-help|^help") {
        return $True
    }
    else {
        return $False
    } 
}

#Add the scriptblock
Set-PSReadlineOption -AddToHistoryHandler $ScriptBlock

查看此站点以了解更多信息:https://petri.com/let-psreadline-handle-powershell