Skip to content

Instantly share code, notes, and snippets.

@trackd
Last active October 2, 2026 17:13
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 {
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