当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 管理 PSReadline 历史文件

作者:精品下载站 日期:2024-12-14 07:51:49 浏览:15 分类:玩电脑

管理 PSReadline 历史文件


这需要一些纪律,但我终于掌握了使用 PSReadline 维护的命令历史文件的窍门。尽管 Set-PSReadlineOption 有一些关于如何使用此文件的选项,但根据我的经验,我觉得需要自己处理一些事情。这是我的看法。

我发现我的历史文件可能变得非常大,这似乎会影响加载 PowerShell 的性能,或者这可能只是巧合。尽管有一些设置可以控制最大行数并阻止重复命令,但 PSReadline 似乎对这些值没有做任何事情。也许在早期版本的 Windows 中确实如此,但我运行的是 5.1.16299,似乎没有任何东西可以检查历史文件。我自己处理这个问题也同样容易。

这是我编写的用于优化 PSReadline 历史文件的函数。您可以从 Github 获取代码。

Optimize-PSReadLineHistory:

#requires -version 5.0
#requires -module PSReadline


Function Optimize-PSReadLineHistory {
     Optimize-PSReadelineHistory
        
        Trim the PSReadlineHistory file to default maximum number of lines.
    .EXAMPLE
        PS C:\> Optimize-PSReadelineHistory -maximumlinecount 500 -passthru

            Directory: C:\Users\Jeff\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline


            Mode                LastWriteTime         Length Name
            ----                -------------         ------ ----
            -a----        11/2/2017   8:21 AM           1171 ConsoleHost_history.txt
                    
        Trim the PSReadlineHistory file to 500 lines and display the file listing.
    .INPUTS
        None
    .OUTPUTS
       None
    .NOTES
        version 1.0
        Learn more about PowerShell: http://jdhitsolutions.com/blog/essential-powershell-resources/
    .LINK
    Get-PSReadlineOption
    .LINK
    Set-PSReadlineOption
    #>
    [cmdletbinding(SupportsShouldProcess)]
    Param(
        [Parameter(ValueFromPipeline)]
        [int32]$MaximumLineCount = $MaximumHistoryCount,
        [switch]$Passthru
    )
    Begin {
        Write-Verbose "[$((Get-Date).TimeofDay) BEGIN  ] Starting $($myinvocation.mycommand)"
        $History = (Get-PSReadlineOption).HistorySavePath
    } #begin

    Process {
        if (Test-Path -path $History) {
            Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Measuring $history"
            $myHistory = Get-Content -Path $History
    
            Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Found $($myHistory.count) lines of history"
            $count = $myHistory.count - $MaximumLineCount
            
            if ($count -gt 0) {
                Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Trimming $count lines to meet max of $MaximumLineCount lines"
                 $myHistory | Select-Object -skip $count -Unique  | Set-Content -Path $History
                
            }
        }
        else {
            Write-Warning "Failed to find $history"
        }

    } #process

    End {
        If ($Passthru) {
            Get-Item -Path $History
        }
        Write-Verbose "[$((Get-Date).TimeofDay) END    ] Ending $($myinvocation.mycommand)"
    } #end 

} #close Name

该函数会将您的历史文件修剪为指定的行数。默认值是全局 $MaximumHistoryCount 变量。该功能还将删除重复的条目,进一步减小文件大小。在我的 PowerShell 配置文件脚本中,我点了该函数并运行它。现在至少我可以在某种程度上控制该文件。

如果您遇到问题或有反馈,请在要点页面上发布问题。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯