Skip to content

Latest commit

 

History

History
66 lines (51 loc) · 1.81 KB

powershell.md

File metadata and controls

66 lines (51 loc) · 1.81 KB

Tweak things in PowerShell

- CONTENTS -

Keep each command item unique in PSReadLine history file

Tested with PowerShell v7.3.6 and PSReadLine v2.3.1-beta1. It should also work with later versions but not with older ones (can even cause loss of command history).

Steps:

  1. Run the following command to update PSReadLine in PowerShell. (VERY IMPORTANT!)

    Update-Module PSReadLine -AllowPrerelease
  2. Add the following code to your PowerShell profile:

    Set-PSReadLineOption -AddToHistoryHandler {
      # A hack to keep each item unique in the history file.
      param([string]$itemNew)
      $historyFile = (Get-PSReadLineOption).HistorySavePath
      if (!(Test-Path $historyFile)) {
        return $true
      }
      $items = [ordered]@{}
      $sb = [System.Text.StringBuilder]::new()
      Get-Content $historyFile | ForEach-Object {
        if ($_.Length -eq 0) {
          return
        }
        [void]$sb.Append($_)
        if ($_.EndsWith('`')) {
          [void]$sb.Append("`n")
          return
        }
        $item = $sb.ToString()
        if ($items.Contains($item)) {
          $items.Remove($item)
        }
        $items.Add($item, $null)
        [void]$sb.Clear()
      }
      if ($items.Contains($itemNew)) {
        $items.Remove($itemNew)
      }
      $items.Keys | Out-File $historyFile -Force
      return $true
    }
  3. Restart PowerShell.