PowerShell – Expand-Aliases


#Requires -Version 3

function Expand-Aliases {
 <#
 .SYNOPSIS
 find any aliases in use and expand them to full cmdlet names.
 .DESCRIPTION
 Any scripts in 'corporate' or 'formal' use should have any aliases
 expanded. This removes ambiguity and any potential clashes or errors.
 .PARAMETER InputFiles
 The powershell .ps1 file(s) you wish to scan/repair for aliases.
 .EXAMPLE
 Expand-Aliases -InputFile test.ps1
 .EXAMPLE
 Get-ChildItem *.ps1 | Expand-aliases
 #>

 [cmdletbinding(SupportsShouldProcess=$True)]
 Param ([parameter(Mandatory=$true,ValueFromPipeline=$true,HelpMessage='Enter a valid PowerShell filename')]
 [string[]] $InputFiles)

 BEGIN {
   $aliases = Get-Alias | Group-Object -AsHashTable -Property Name
   $ParserErrors = $null
 }

 PROCESS {
 ForEach ($InputFile in $InputFiles) {
   Write-Verbose -Message "$Inputfile"
   $text = Get-Content -Path $InputFile -Raw -verbose # ignore newlines, etc. and return as a single string.
   $tokens = [System.Management.Automation.PSParser]::Tokenize($text, [ref]$ParserErrors)
   $commands = $tokens | Where-Object {$_.Type -eq 'Command'} | Sort-Object { $_.Start } -Descending

   Foreach ($cmd in $commands) { # sorted so that last one in file is expanded first
      $key = $cmd.Content
      if ($aliases.Contains($key)) {
        $alias = $aliases.$key # Alias
        $old = $cmd.Content
        $new = $alias.ResolvedCommandName # expanded Alias as command
        If ($pscmdlet.ShouldProcess($old, ('Expand alias to {0}' -f $new))
        {
        $text = $text.Remove($cmd.start,$cmd.Content.Length).Insert($cmd.start,$new)
        }

  }

 }

  $text

}

}

}

 

Comments (3)

  1. NoneAndOne says:

    It seems that because of the difference in the string length between an alias and it’s command, if there were more than one alias this script would start putting the replacements in the wrong place. I think there needs to be a point of reference by (adding the difference in alias to command lengths together) that will link $cmd.start to the new place that $cmd actually starts in the string after previous insertions. I haven’t tested, I may be wrong

    1. NoneAndOne says:

      My apologies, re-ordering from last to first takes care of that issue quite nicely!

      1. LukeBrennan says:

        YES, that is exactly the point I reached too – until I realised sort and then work from last to first would do the trick!

Skip to main content