Last active
October 2, 2026 17:13
-
-
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 { | |
| try { | |
| $ast = $tokens = $parseErrors = $cursor = $null | |
| [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState( | |
| [ref]$ast, | |
| [ref]$tokens, | |
| [ref]$parseErrors, | |
| [ref]$cursor | |
| ) | |
| $commands = $ast.FindAll({ | |
| param($node) $node -is [Management.Automation.Language.CommandAst] | |
| }, | |
| $true | |
| ) | Sort-Object { $_.CommandElements[0].Extent.StartOffset } -Descending | |
| foreach ($cmd in $commands) { | |
| $commandName = $cmd.GetCommandName() | |
| if (-not $commandName) { | |
| continue | |
| } | |
| if ($commandName -in 'cd', 'dir', 'ls', 'z') { | |
| # i prefer the shorter version here. | |
| continue | |
| } | |
| $alias = $ExecutionContext.SessionState.InvokeCommand.GetCommand( | |
| $commandName, | |
| [System.Management.Automation.CommandTypes]::Alias | |
| ) | |
| if (-not $alias.ResolvedCommandName) { | |
| continue | |
| } | |
| $extent = $cmd.CommandElements[0].Extent | |
| $length = $extent.EndOffset - $extent.StartOffset | |
| [Microsoft.PowerShell.PSConsoleReadLine]::Replace( | |
| $extent.StartOffset, | |
| $length, | |
| $alias.ResolvedCommandName | |
| ) | |
| } | |
| } | |
| finally { | |
| [Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine() | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment