Don’t use aliases in scripts


Aliases are alternate names or nicknames for a cmdlet or for a command element, such as a function, script, file, or executable file.

When I teach PowerShell, I usually divide aliases into two groups:

Transitional aliases such as ls or dir (for Get-ChildItem), and type or cat (for Get-Content) that are aimed for people transitioning from other shells to PowerShell,

and Shortcut aliases such as gwmi (for Get-WmiObject) and gps (for Get-Process) that help you speeds things up when you code in the console.

To get the list of all the defined aliases in your runspace, use the Get-Alias cmdlet, or the alias PSDrive using dir alias:\

 

Though aliases are great, especially for the lazy typer that I am, they should not be used in scripts that you or someone else would need to read and maintain in the future.

Aliases can make your scripts inconsistent, where you use an alias that you have defined in your profile and/or someone else that runs your script has a different definition for the alias.

This is why I avoid using aliases in my scripts, and before I distribute them, I replace all the aliases in it to the full cmdlet name.

For this, I’ve written a little piece of code that can be set as an add-on in the ISE.

Add the code below to your ISE profile (usually C:\Users\<you>\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1):

function Expand-Aliases {

       $ast = [System.Management.Automation.PSParser]::Tokenize(
        $psISE.CurrentFile.Editor.Text, [ref]$null)
       $commands = $ast | Where-Object {
        $_.Type -eq [System.Management.Automation.PSTokenType]::Command }
 
       $after = $psISE.CurrentFile.Editor.Text -split [System.Environment]::NewLine
       $aliases = @{}; Get-Alias | ForEach-Object {
           $aliases += @{$_.Name = $_.Definition}
       }
 
       $commands | Sort-Object StartLine, StartColumn -Descending |
        Where-Object { $aliases.Contains($_.Content) } | ForEach-Object {
               $def = $aliases["$($_.Content)"]
               $after[$_.StartLine-1] = ([string]$after[$_.StartLine-1]).Remove($_.StartColumn-1, $_.Length).Insert($_.StartColumn-1, $def)
       }
       $psISE.CurrentFile.Editor.Text = $after -join [System.Environment]::NewLine
}
 
[void]$PSIse.CurrentPowerShellTab.AddOnsMenu.Submenus.Add(
    "Expand Aliases", {Expand-Aliases}, 'Control+Alt+A')
 
 
You can run notepad $profile from the ISE, to open up your ISE profile for editing.
 
After that, You’ll get the Expand Aliases option in the Add-ons drop down menu, and the CTRL+ALT+A shortcut key:
 
2015-02-07_235546
 
For more information about Aliases, run Get-Help about_Aliases or browse to https://technet.microsoft.com/en-us/library/hh847830.
 
 
HTH,
\Martin.
 
Comments (2)

  1. Anonymous says:

    For the past few years, I’ve picked up a several best practices for PowerShell scripting. Some of them

  2. turbomcp says:

    Thanks
    very interesting

Skip to main content