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 (0)

Skip to main content