PowerShell Aliases: A Beginner’s Guide

PowrShell Alias

Typing long, complex command names over and over can reduce productivity in PowerShell. Luckily, aliases provide a simple shortcut by allowing you to create alternate short names for common commands and cmdlets. In this beginner’s guide, you’ll learn all about how to create, manage, persist, and remove aliases in PowerShell. We’ll cover alias syntax, listing aliases, scope, built-in aliases, and more using real-world examples. We will also explore some advanced topics like best practices, troubleshooting common issues, and the difference between PowerShell Alias and Function.

Whether you want to mimic short Linux-style commands or simply abbreviate verbose PowerShell verbs, aliases can streamline your scripting and save keystrokes. Now, let’s dive in and unlock the time-saving power of aliases in PowerShell!

Understanding PowerShell Alias and its importance

PowerShell Alias is a shortcut name for a cmdlet or command. It allows you to use a shorter and easier-to-remember name instead of the full cmdlet or command. For example, instead of typing “Get-ChildItem” every time, you can create an Alias “GCI” and use it instead. Alias can save time and make your PowerShell experience smoother.

An alias can also help you to avoid typos and errors in long cmdlet or command names. It can also help you to make your scripts shorter and more readable. However, it is essential to use Alias correctly and avoid conflicts with existing or future cmdlets or commands. If you find yourself typing the same long cmdlet and function names repeatedly in PowerShell, aliases are the solution.

How to Create an Alias in PowerShell?

PowerShell Aliases Guide

Creating an alias is simple. Use the New-Alias command followed by the alias name and the actual command you want to alias. The syntax for the New-Alias cmdlet is as follows:

New-Alias 
[-Name] <String> 
[-Value] <String> 
[-Description <String>] 
[-Force] 
[-Option <String>] 
[-PassThru] 
[-Scope <String>] 
[-WhatIf]
[-Confirm]
[<CommonParameters>]

Below is the table outlining the important parameters of the New-Alias cmdlet in PowerShell:

ParameterDescription
-NameSpecifies the name of the new alias. This is a mandatory parameter. It can have alphanumeric characters and hyphens (But the first character must be an alphabet).
-ValueSpecifies the name of the cmdlet or function that the alias refers to. Also a mandatory parameter.
-DescriptionProvides a textual description of what the alias does. If it includes space, Wrap it inside quotation marks.
-ScopeSpecifies options for the alias, like ReadOnly, Constant, None, and Private.
-OptionSpecifies the name of the new alias. This is a mandatory parameter. Can have alphanumeric characters and hyphens (But the first character must be an alphabet).
-ForceForces the cmdlet to create an alias, even if one with the same name already exists.

For instance, to create an alias named list for Get-ChildItem, you would use:

New-Alias -Name list -Value Get-ChildItem

From this point onwards, typing “list” will execute Get-ChildItem.

how to create new alias in powershell

To overwrite an existing alias, use the -Force parameter:

New-Alias -Name gs -Value Get-Service -Description "Alias for Get-Service" -Force

This creates an alias with a description, overwriting any existing aliases.

PowerShell Set-Alias

You can also add a new Alias using the “Set-Alias” command. This cmdlet creates a new alias or updates an existing one.

Set-Alias <AliasName> <Command>

Here is an example:

Set-Alias -Name GCI -Value Get-ChildItem

In this example, we created an Alias “GCI” for the “Get-ChildItem” cmdlet. You can use any name you want for the Alias as long as PowerShell does not already use it. You can also create an Alias for a function, script, or executable. For example:

Set-Alias np NotePad

After creating an alias, you can use it in the current PowerShell session just like you would use the cmdlet or function it represents. In this example, you can open Notepad just by typing “np”.

create new alias powershell

Create Alias for PowerShell Function

Here is an example of creating an alias for a Function:

function Say-Hello {
    Write-Output "Hello, World!"
}

Set-Alias -Name sh -Value Say-Hello

Please note that the alias you created will only exist for the duration of your current PowerShell session. If you want to have the alias available every time you start a new session, you’ll need to add both the function definition and the Set-Alias command to your PowerShell profile.

Listing Available Aliases

For instance, Instead of typing Get-ChildItem every time to retrieve directory items, PowerShell uses the alias dir for this command. Both commands achieve the same result, but dir is shorter and often more familiar to those who come from a background in other command-line interfaces.

To see a list of all available aliases in your PowerShell session, use the Get-Alias command (Alias: Gal). This will display a PowerShell alias list comprising of all the built-in and user-defined aliases.

PS C:\> Get-Alias | format-table name,definition,options

Similarly, to find a specific aliases, use:

Get-Alias GCI

You can also retrieve all aliases using the Alias provider (Similar to file system drive). Here is how:

#Change the Drive
Set-Location alias:

#Get All Aliases
Get-Childitem

Common PowerShell Aliases

PowerShell includes many built-in aliases like:

  • cat for Get-Content
  • cd for Set-Location
  • echo for Write-Output
  • ls for Get-ChildItem

These mimic Linux commands to provide an intuitive experience.

Setting up permanent Aliases in PowerShell

By default, any alias you create is session-specific and will be available only for the current PowerShell session. This means it’ll disappear the next time you open PowerShell. If you want to make the Alias permanent, you need to Add Alias to the PowerShell profile.

Your PowerShell profile is a script that runs every time you start PowerShell. You can use it to customize your PowerShell environment, including creating permanent Aliases. Here is how to create a permanent Alias:

  1. Open your PowerShell profile. You can use the “notepad $PROFILE” command to open it in Notepad.
  2. Add the “Set-Alias” command to create your Alias. For example:
Set-Alias -Name GCI -Value Get-ChildItem
  1. Save and close the file.
  2. Restart PowerShell.

Your permanent Alias is now available every time you start PowerShell.

Using PowerShell Alias with parameters

You can use an Alias with parameters to make your commands shorter and more readable. Let’s say you frequently use the Get-Process command with the -Name parameter set to Chrome. Instead of typing that every time, you can create a function and then alias it.

function Get-ChromeProcess {
    $Process = Get-Process -Name chrome -ErrorAction SilentlyContinue
    Return $Process
}
Set-Alias -Name gchrome -Value Get-ChromeProcess

Now, by typing “chrome”, you’ll retrieve all Chrome processes.

powershell alias with parameter

You can use Aliases with parameters in the same manner you use the actual cmdlets. Let’s take an example PowerShell script without aliases:

Get-ChildItem -Path C:\Windows -Recurse -Include *.exe | Where-Object { $_.Length -gt 10MB }

This command lists all the “.exe” files in the “C:\Windows” folder and subfolders that are larger than 10MB. It is a long command that can be simplified using Alias:

GCI -Path C:\Windows -Recurse -Include *.exe | ? { $_.Length -gt 10MB }

In this example, we used the “GCI” Alias for the “Get-ChildItem” cmdlet and the “?” Alias for the “Where-Object” cmdlet. We also used the same parameters as in the original command. Using Alias with parameters can make your commands shorter and easier to read.

Managing PowerShell Alias list

As you create more Aliases, it can be challenging to keep track of them. PowerShell provides several commands to manage your Alias list. Here are some useful commands:

  • Get-Alias: Lists all the Aliases in your PowerShell session.
  • Export-Alias: Exports your Alias list to a file.
  • Import-Alias: Imports Alias from a file.
  • Remove-Alias: Removes an Alias.

You can use these commands to manage your Alias list, backup it, or share it with others.

Removing an Existing Alias

For removing an alias, the Remove-Item command can be used with the alias’s path.

Remove-Item Alias:aliasname

For instance, to remove the previously created “np” alias, you’d use:

Remove-Item Alias:np

This will delete the “np” alias.

PowerShell Alias vs. Function – What’s the difference?

PowerShell Alias and Function are both shortcuts for commands, but they have different purposes. Alias is a shortcut for a cmdlet or command, while Function is a shortcut for a script or a series of commands. Alias is used to make your commands shorter and easier to remember, while Function is used to automate complex tasks or create reusable code.

Here is an example of using a Function to automate a task and an Alias created for the function:

#Create a Function to Backup Files
Function Backup-MyFiles {
    Param (
        [Parameter(Mandatory=$true)]
        [string]$Source,
        [Parameter(Mandatory=$true)]
        [string]$Destination
    )
    Get-ChildItem -Path $Source -Recurse -File | Copy-Item -Destination $Destination
}

#Create a alias for function
New-Alias -Name backup -Value Backup-MyFiles

This Function takes two parameters, “Source” and “Destination”, and copies all the files in the “Source” folder and subfolders to the “Destination” folder. You can use this function repeatedly with different values for the parameters, or you can use the Alias with parameters:

#Call the function with parameters using its Alias
Backup -Source "C:\Source" -Destination "C:\Backup"

In summary, PowerShell Alias is a shortcut for a cmdlet or command, while Function is a shortcut for a script or a series of commands.

Alias Scopes in PowerShell

In PowerShell, the scope defines the accessibility and lifecycle of an item, such as a variable, function, or alias. The scope plays a significant role in how aliases function and how they can be accessed. Here’s a quick summary of alias scopes and how you can effectively use them in your PowerShell scripts.

  • Global: Alias is available throughout the current PowerShell session.
  • Local: Alias is confined to the current block of code.
  • Script: Alias is confined to the script in which it is defined.
  • Private: Alias is strictly confined to the specific scope, not even available to child scopes.

For example, In a script file (.ps1), you might have:

New-Alias -Name sp -Value Set-Property -Scope Script

Here, sp will be available for the duration of the script execution but won’t be available outside the script.

Best practices for using PowerShell Alias

Here are some best practices for using PowerShell Alias:

  1. Use short and meaningful names for your Alias. Be descriptive. Use the description of the alias.
  2. Avoid Overwriting Standard Aliases: PowerShell has many built-in aliases for common cmdlets. Before creating a new alias, use Get-Alias to ensure you’re not overwriting an existing one.
  3. Prefix custom aliases with acronyms or abbreviations to avoid future conflicts.
  4. Create permanent Aliases only for frequently used commands.
  5. Avoid using Aliases in scripts that will be shared with others.
  6. Backup Your Aliases: Regularly export your custom aliases so you can import them on a new machine or recover them if something goes wrong.
  7. Keep your Alias list organized and documented.

By following these best practices, you can avoid conflicts, make your scripts easier to read and maintain and improve your PowerShell experience.

Troubleshooting common PowerShell Alias issues

Sometimes, you may encounter issues with your PowerShell Alias, such as conflicts, errors, or unexpected behaviors. Here are some common issues and how to troubleshoot them:

  1. Alias Doesn’t Exist: You attempt to use an alias, but PowerShell indicates it’s not recognized. Use the Get-Alias to check if the alias exists. Remember, aliases created in a session are not available in subsequent sessions unless added to your profile.
  2. Conflict with existing or future cmdlets or commands: Use a different name for your Alias that is not already used by PowerShell or any future cmdlets or commands.
  3. Conflict with existing or future Aliases: Avoid using names that are already used by other Aliases.
  4. Typos or errors in Alias names: Double-check your Alias names for typos or errors. You can use the “Get-Alias” command to check if your Alias is created correctly.
  5. Unexpected behaviors: Check if your Alias is used correctly and does not conflict with other commands or scripts.
  6. New-Alias : The alias is not allowed, because an alias with the name ” already exists. – Alias conflict. Choose a different name for the alias.
  7. Unexpected Alias Behavior Across Different Hosts: Different hosts (e.g., ISE vs. console) can have different profiles. Check the relevant profile script for each host.

By following these troubleshooting steps, you can resolve most PowerShell Alias issues. Here is the Microsoft Reference on PowerShell Alias

Wrapping up

PowerShell Alias can save time and make your PowerShell experience smoother. In this beginner’s guide, we discussed what PowerShell Alias is, how to create an Alias, and best practices for using it. We also explored advanced usages, troubleshooting common issues, and the difference between Alias and Function. Now, you should have a solid understanding of how to define custom aliases using Set-Alias, view existing aliases with Get-Alias, make aliases persistent, and remove unneeded aliases.

By following the best practices and using Alias correctly, you can make your scripts shorter and more readable, avoid typos and errors, and boost your productivity in PowerShell.

What is the purpose of an alias in PowerShell?

In PowerShell, aliases are used to create alternate names or shortcuts for cmdlets, functions, and scripts. They provide a way to use shorter and more familiar names for commonly used commands, making it easier and quicker to work with PowerShell. Aliases can be customized and created by the user, allowing for a more personalized and efficient PowerShell experience.

How do you create an alias in PowerShell?

To create an alias in PowerShell, you can use the Set-Alias cmdlet followed by the desired alias name and the command or function you want to associate with it. For example, to create an alias called “ls” for the Get-ChildItem cmdlet, you would use the following command: Set-Alias -Name ls -Value Get-ChildItem.

How do I list user aliases in PowerShell?

The Get-Alias cmdlet will include both built-in aliases that come with PowerShell as well as any custom aliases you’ve created. To get user-created aliases, we can compare the current alias list with the default alias list that PowerShell loads. Here is how:
$defaultAliases = powershell.exe -Command "Get-Alias | Select-Object -ExpandProperty Name"
$currentAliases = Get-Alias | Select-Object -ExpandProperty Name
#Find aliases that exist in the current session but not in the default session
$userAliases = $CurrentAliases | Where-Object { $_ -notin $defaultAliases }

How to create an alias with a parameter in PowerShell?

You can create a function that takes a parameter and then create an alias for that function. Here is an example:
function Get-FileExtension ([string]$fileName) {
$extension = [System.IO.Path]::GetExtension($fileName)
Write-Host "File extension is: $extension"
}
#Create an alias for the function
Set-Alias -Name gfe -Value Get-FileExtension
#Call the Alias
gfe -fileName "example.txt"

How to remove an alias in PowerShell?

To remove an alias in PowerShell, you can use the Remove-Item cmdlet followed by the alias name. For example, to remove an alias named “myAlias”, you would use the command: Remove-Item alias:myAlias.

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

Leave a Reply

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