PowerShell的历史:你如何防止重复命令?(PowerShell history: how d

2019-07-18 08:31发布

背景:

PowerShell的历史,现在,我有办法救跨会话历史,是很多对我更有用。

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

现在,我试图阻止PowerShell与节约重复的命令,我的历史。

我试着使用Get-Unique ,但是,这并不工作,因为在历史上的每一个命令是“独一无二”的,因为每个人都有不同的ID号。

Answer 1:

获取唯一还需要一个排序列表,我以为你可能想保留执行顺序。 试试这个

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

此方法使用组对象cmdlet来创建命令的独特的桶,然后在Foreach对象块只是抓住每个桶中的第一项。

顺便说一句,如果你想保存这些历史文件,我会用限值的所有命令 - 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


Answer 2:

为PowerShell中的以下命令工作在Windows 10(v.1803测试)。 该选项被记录在这里 。

Set-PSReadLineOption –HistoryNoDuplicates:$True

在实践中,调用PowerShell将使用下面的命令(如保存在一个快捷键)打开PowerShell和无重复历史

%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -NoExit -Command Set-PSReadLineOption –HistoryNoDuplicates:$True


Answer 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


文章来源: PowerShell history: how do you prevent duplicate commands?