Using aliases in scripts

There’s been a long debate on the PowerShell github site regarding ternary operators – think of it as a short cut for if-else. Twice in that debate the point has been made that aliases are perfectly acceptable in scripts. Wrong. Using aliases in scripts should never be encouraged.

Aliases are short cuts to cmdlet and parameter names. In some instances a parameter name has changed but the old name is available as an alias so existing code doesn’t break.

Using aliases at the command line is perfectly acceptable as they cut down typing – debateable with PSUseAbbreviationExpansion in PowerShell v6/7 – but I can see their use in that situation. I tend to use full cmdlet names – more from habit due to doing so many demos, articles and books – but understand that many people use aliases.

Aliases in scripts are a bad idea because they cause confusion. They’re more difficult to understand, especially for new comers, and make code harder to maintain especially for someone other than the original writer.

If you use VScode or ISEsteroids they will explicitly flag aliases to be expanded. PSScriptAnalyzer (also used in VScode) will also flag aliases that should be expanded.

Given tab completion and the intellisense built into VScode and ISE using aliases in your code is just bad practice. There is no need to do so and very good reasons why you shouldn’t.

Advertisements
This entry was posted in Powershell. Bookmark the permalink.

1 Response to Using aliases in scripts

  1. yubu says:

    This what i have on my laptop:
    2019-07-29: Win10 1903: ((get-module -ListAvailable).name | %{gcm -mod $_ -CommandType Function,Cmdlet} | measure).count == 61039
    2019-07-29: Win10 1903: (get-alias | measure).count == 952
    For compare: 2019-05-25: Win10 1903: ((get-module -ListAvailable).name | %{gcm -mod $_ -CommandType Function,Cmdlet} | measure).count == 40161
    2019-07-29: Win10 1903: ((get-module).name | %{gcm -mod $_ -CommandType Function,Cmdlet} | measure).count == 706
    2019-07-29: Win10 1903: (get-alias | measure).count == 481

    I can’t memorize, all needed (to me!) aliases not using them on daily basis and/or not using them in scripts on daily basis. When you’re dealing with live IT/prod with lots of servers you need this on top of your head to do things fast. Nothing is fast as brain.

    It would be great to have VSCode extension that toggles aliases to full cmdlet names. I would require from big module providers (Msft, Aws, VMware etc) to provide config for this kind of extension.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s