问题描述
背景:
由于我有一种保存跨会话历史记录的方法,因此PowerShell历史记录对我有用得多。
PowerShell history is a lot more useful to me now that I have a way to save history across sessions.
# Run this every time right before you exit PowerShell
get-history -Count $MaximumHistoryCount | export-clixml $IniFileCmdHistory;
现在,我正试图防止PowerShell将重复的命令保存到我的历史记录中。
Now, I am trying to prevent PowerShell from saving duplicate commands to my history.
我尝试使用 Get-Unique
,但是由于历史记录中的 every 命令是唯一,因为每个人都有不同的ID号。
I tried using Get-Unique
, but that doesn't work since every command in the history is "unique", because each one has a different ID number.
推荐答案
Get-Unique也需要一个排序列表,我认为您可能希望
保留执行顺序。
Get-Unique also requires a sorted list and I assume you probably want topreserve execution order. Try this instead
Get-History -Count 32767 | Group CommandLine | Foreach {$_.Group[0]} |
Export-Clixml "$home\pshist.xml"
此方法使用了Group -Object cmdlet创建唯一的命令桶
,然后Foreach-Object块仅抓取每个桶中的第一项。
This approach uses the Group-Object cmdlet to create unique buckets of commandsand then the Foreach-Object block just grabs the first item in each bucket.
BTW如果要所有命令保存到历史文件中,我将使用限制值
-32767-除非您将$ MaximumHistoryCount设置为该值。
BTW if you want all commands saved to a history file I would use the limit value- 32767 - unless that is what you set $MaximumHistoryCount to.
BTW如果要自动保存退出时,您可以在2.0上执行此操作,例如
,
BTW if you want to automatically save this on exit you can do this on 2.0 likeso
Register-EngineEvent PowerShell.Exiting {
Get-History -Count 32767 | Group CommandLine |
Foreach {$_.Group[0]} | Export-CliXml "$home\pshist.xml" } -SupportEvent
然后在全部加载后还原您需要的是
Then to restore upon load all you need is
Import-CliXml "$home\pshist.xml" | Add-History
这篇关于PowerShell历史记录:如何防止重复的命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!