Powershell Best Practice #1: Use full cmdlet name in scripts (not alias)

By | May 22, 2015

Best Practice: It is recommended to use full cmdlet in your scripts and alias in an interactive console (never use alias in your scripts).

Explanation:

Script (use cmdlet)

Using cmdlets in a script makes the code more clear and consistent when shared with other people.

PowerShell Script VSCode

===

Interactive (use alias)

Using alias in an interactive console is useful to speed up but makes the code less clear and should never used in a script.

PowerShell Interactive

===

Additional Information

An alias is a an alternative shorter name for a cmdlet, function, script, file or executable file.
For instance, sl is the alias for the cmdlet Set-Location.

You can list all the aliases (including the built-in aliases) with the cmdlet: Get-Alias

get-alias-powershell

You can find the equivalence alias <> cmdlet:

get-alias-definition

Let’s take an example, you publish a script on Internet and you used aliases into your script, it will be probably downloaded and used by thousands of users, the problem is that we never know in advance what aliases are defined on a foreign computer. If someone decided to change a built-in alias to another command or made a mistake when setting an alias, then the behavior of the script becomes unpredictable and can lead to unexpected behavior.

Moreover, some aliases are not so intuitive and it can be difficult to remember all of them.

get-alias-not-obvious

You can refactor by replacing alias with full cmdlet in Visual Studio Code:

VisualStudioCode Replace Alias


next-button

One thought on “Powershell Best Practice #1: Use full cmdlet name in scripts (not alias)

  1. Pingback: Powershell Best Practice #2: Use named parameter (not positional and partial parameter) | Powershell Guru

Leave a Reply

Your email address will not be published. Required fields are marked *