20

背景:

PowerShell 历史记录对我来说非常有用,因为我有一种方法可以跨会话保存历史记录。

# Run this every time right before you exit PowerShell
get-history -Count $MaximumHistoryCount | export-clixml $IniFileCmdHistory;

现在,我试图阻止 PowerShell 将重复的命令保存到我的历史记录中。

我尝试使用Get-Unique,但这不起作用,因为历史记录中的每个命令都是“唯一的”,因为每个命令都有不同的 ID 号。

4

3 回答 3

23

Get-Unique 还需要一个排序列表,我假设您可能希望保留执行顺序。试试这个

Get-History -Count 32767 | Group CommandLine | Foreach {$_.Group[0]} |
Export-Clixml "$home\pshist.xml"

此方法使用 Group-Object cmdlet 创建唯一的命令存储桶,然后 Foreach-Object 块仅抓取每个存储桶中的第一项。

顺便说一句,如果您希望将所有命令保存到历史文件中,我将使用限制值 - 32767 - 除非您将 $MaximumHistoryCount 设置为。

顺便说一句,如果您想在退出时自动保存它,您可以像这样在 2.0 上执行此操作

Register-EngineEvent PowerShell.Exiting {
  Get-History -Count 32767 | Group CommandLine |
  Foreach {$_.Group[0]} | Export-CliXml "$home\pshist.xml" } -SupportEvent

然后在加载时恢复你所需要的就是

Import-CliXml "$home\pshist.xml" | Add-History
于 2009-09-17T14:17:04.837 回答
9

以下命令适用于 Windows 10 中的 PowerShell(在 v.1803 中测试)。该选项在此处记录。

Set-PSReadLineOption –HistoryNoDuplicates:$True

在实践中,使用以下命令(例如保存在快捷方式中)调用 PowerShell 会打开具有不重复历史记录的 PowerShell

%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -NoExit -Command Set-PSReadLineOption –HistoryNoDuplicates:$True
于 2018-05-11T14:57:24.880 回答
3

与重复项没有直接关系,但同样有用,我的这个AddToHistoryHandler脚本块在我$PROFILE的历史记录中保留了简短的命令:

$addToHistoryHandler = {
    Param([string]$line)
    if ($line.Length -le 3) {
        return $false
    }
    if (@("exit","dir","ls","pwd","cd ..").Contains($line.ToLowerInvariant())) {
        return $false
    }
    return $true
}
Set-PSReadlineOption -AddToHistoryHandler $addToHistoryHandler
于 2018-10-15T14:01:57.137 回答