Replacing Aliases with Command Names

by Apr 18, 2013

Aliases are shortcuts for commands and useful in interactive PowerShell. Once you write scripts, however, you should no longer use aliases and instead use the underlying commands directly.

You can always use Get-Command to find out the underlying command for an alias:

The replacement process can be automated, too. Here's an experimental function called Remove-ISEAlias. When used from inside the ISE 3.0 editor, the function automatically replaces all aliases with their underlying commands:

Function Remove-ISEAlias
{
  $text = $psISE.CurrentFile.Editor.Text
  $sb = New-Object System.Text.StringBuilder $text

  $commands = [System.Management.Automation.PSParser]::Tokenize($text, [ref]$null) |
  Where-Object { $_.Type -eq 'Command' } |
  Sort-Object -Property Start -Descending |
  ForEach-Object {
    $command = $text.Substring($_.Start,  $_.Length)
    $commandtype = @(try {Get-Command $command  -ErrorAction 0} catch {})[0]

    if ($commandtype -is [System.Management.Automation.AliasInfo])
    {
      $sb.Remove($_.Start, $_.Length)
      $sb.Insert($_.Start, $commandtype.ResolvedCommandName )
    }

    $psISE.CurrentFile.Editor.Text = $sb.toString()
  }
}

Note that this is just a simple proof-of-concept. Do not use it as-is on large production scripts. This is not a well-tested commercial solution. Maybe you'd like to take it from here and turn it into something robust. If so, please share with the community.

Twitter This Tip! ReTweet this Tip!