powershell历史:如何防止重复命令 [英] powershell history: how do you prevent duplicate commands

查看:374
本文介绍了powershell历史:如何防止重复命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 #每次在退出powershell之前运行这个命令
get-history -ount $ MaximumHistoryCount | export-clixml $ IniFileCmdHistory;

现在,我试图阻止PowerShell将重复的命令保存到我的
历史。 / p>

我尝试使用 Get-Unique ,但是

解决方案

Get-Unique还需要一个排序列表,我假设你可能想要
保存执行顺序。尝试此方法

  Get-History -ount 32767 |组命令行| Foreach {$ _。Group [0]} | 
Export-Clixml$ home\pshist.xml

-Object cmdlet创建唯一桶命令
,然后Foreach-Object块只抓取每个桶中的第一个项。



BTW如果你想要所有命令保存到历史文件我将使用极限值
- 32767 - 除非你设置$ MaximumHistoryCount到。



BTW如果你想自动保存这在退出你可以在2.0像
这样做这样

  Register-EngineEvent PowerShell .Exiting {
Get-History -ount 32767 |组命令行|
Foreach {$ _。Group [0]} | Export-CliXml$ home\pshist.xml} -SupportEvent

你需要的是

  Import-CliXml$ home\pshist.xml|添加历史


Background: 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;

Now, I am trying to prevent PowerShell from saving duplicate commands to my history.

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 also requires a sorted list and I assume you probably want to preserve execution order. Try this instead

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

This approach uses the Group-Object cmdlet to create unique buckets of commands and then the Foreach-Object block just grabs the first item in each bucket.

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 if you want to automatically save this on exit you can do this on 2.0 like so

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历史:如何防止重复命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆