Last active
May 30, 2026 17:55
-
-
Save trackd/f84e085482b5f6314cd37befa56a80f5 to your computer and use it in GitHub Desktop.
Replace aliases on enter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Set-PSReadLineKeyHandler -Chord 'Enter' -BriefDescription 'Replace aliases on enter' -ScriptBlock { | |
| $ast = $tokens = $parseErrors = $cursor = $null | |
| [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState( | |
| [ref]$ast, | |
| [ref]$tokens, | |
| [ref]$parseErrors, | |
| [ref]$cursor | |
| ) | |
| # Replace from end to start so offsets stay valid for multiline buffers. | |
| $commandTokens = $tokens | | |
| Where-Object { $_.TokenFlags -band [Management.Automation.Language.TokenFlags]::CommandName } | | |
| Sort-Object { $_.Extent.StartOffset } -Descending | |
| foreach ($token in $commandTokens) { | |
| if ($token.Extent.Text -in 'cd', 'dir', 'ls', 'z') { | |
| # i prefer the shorter version here. | |
| continue | |
| } | |
| # Escape wildcard characters so aliases like '?' are matched literally. | |
| $escapedName = [System.Management.Automation.WildcardPattern]::Escape($token.Extent.Text) | |
| $alias = Get-Command -Name $escapedName -CommandType Alias -ErrorAction Ignore | |
| if (-not $alias.ResolvedCommandName) { | |
| continue | |
| } | |
| $extent = $token.Extent | |
| $length = $extent.EndOffset - $extent.StartOffset | |
| [Microsoft.PowerShell.PSConsoleReadLine]::Replace( | |
| $extent.StartOffset, | |
| $length, | |
| $alias.ResolvedCommandName | |
| ) | |
| } | |
| [Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment