背景:
PowerShell历史对我来说更有用,因为我有办法在会话中保存历史记录。
# Run this every time right before you exit PowerShell
get-history -Count $MaximumHistoryCount | export-clixml $IniFileCmdHistory;
现在,我试图阻止PowerShell将重复命令保存到我的历史记录中。
我尝试使用Get-Unique
,但这不起作用,因为历史记录中的每个命令都是“唯一的”,因为每个命令都有不同的ID号。
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
以下命令适用于Windows 10中的PowerShell(在v.1803中测试)。该选项记录在案here。
Set-PSReadLineOption –HistoryNoDuplicates:$True
实际上,使用以下命令调用PowerShell(例如,保存在快捷方式中)会打开PowerShell,其中包含没有重复项的历史记录
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -NoExit -Command Set-PSReadLineOption –HistoryNoDuplicates:$True
与副本没有直接关系,但同样有用,我的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