Skip to content

Instantly share code, notes, and snippets.

@trackd
Last active May 30, 2026 17:55
Show Gist options
  • Select an option

  • Save trackd/f84e085482b5f6314cd37befa56a80f5 to your computer and use it in GitHub Desktop.

Select an option

Save trackd/f84e085482b5f6314cd37befa56a80f5 to your computer and use it in GitHub Desktop.
Replace aliases on enter
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