A PowerShell alias is a shortcut to a command that can save you some keystrokes and help you remember commands. In this guide, you will learn how to create a PowerShell alias and what to keep in mind when working with aliases.

PowerShell uses aliases generically for alternatives to many commands. Even in its early version, 1.0, PowerShell came with 100 aliases by default. As an example, you can give PowerShell a UNIX flavor and use commands like cp, mv, man, and ls. PowerShell will parse and translate them to native PowerShell versions. The UNIX “man” command, for example, is an alias for PowerShell’s command get-help. If you’re not happy with the built-in aliases, you can add your own to replace them. Let’s have a look at the built-in aliases first.

Built-in aliases

The number of built-in PowerShell aliases has steadily increased from the original 100 in version 1.0 to around 450 in PowerShell 4. You can list all aliases with the command get-alias. Notice that get-alias even has its own alias, “gal.”

Here’s a sample listing:

PS C:\scripts> get-alias

CommandType     Name         Definition
-----------     ----         ----------
Alias           ac           Add-Content
Alias           asnp         Add-PSSnapin
Alias           clc          Clear-Content
Alias           cli          Clear-Item
Alias           clp          Clear-ItemProperty
Alias           clv          Clear-Variable
Alias           cpi          Copy-Item

Some commands have multiple built-in aliases. Get-childitem, for example, has several pseudonyms: dir, ls, and gci. Be warned, however, that alias behavior does not extend to parameters of the original native commands.

For example, trying to display a wide directory listing with dir /w will result in the following error:

PS C:\> dir /w
dir : Cannot find path 'C:\w' because it does not exist.

You have to use PowerShell to format the display with dir |fw instead to get a wide display of files and folders.

PowerShell alias cmdlets

Aliases can be managed with five PowerShell cmdlets: Export-alias, Import-alias, Get-alias, Set-alias, and New-alias.

Export-alias and Import-alias simply save or load aliases to or from a text file, respectively, allowing you to back up and restore aliases. Note that PowerShell 3.0 and later does not overwrite existing aliases, by default, when you import from a file. To overwrite an existing alias, you need to use the -Force argument.

Get-alias, as already mentioned, displays existing aliases along with their meaning. You can use wildcards or exclude items to filter the display.

Finally, New-alias and Set-Alias are both very similar. The difference is subtle. New-alias will error if you try to create an alias that already exists, whereas Set-alias will happily create a brand new alias or overwrite an existing one.

Create an alias

You can create an alias for any cmdlet, script, function within a script, or even an external command. The choice is limited only by your creativity. To create your own alias, you need to use either the New-Alias or Set-Alias command. The simplest syntax is:

Set-alias <your alias> <the command to alias>

So, if you want to open Notepad by typing “ed,” you use:

Set-alias ed notepad

That’s easy but not that useful. The secret to benefiting from aliases is to use them for complex PowerShell scripts or external commands that have horrible paths too hard to type or remember. For example, you would set the alias “cm” for the command that launches System Center’s Configuration Manager agent as follows:

Set-alias cm C:\Windows\ccm\SMSCFGRC.cpl

A few aliasing issues

Aliasing has a few notable caveats to be aware of. One issue is that many of the built-in aliases are read-only.

PS C:\> gal |group Options

Count Name                      Group                                                                  
----- ----                      -----                                                                  
   99 ReadOnly, AllScope        {%, ?, ac, asnp...}                                                    
   50 AllScope                  {cat, cd, chdir, clear... 

What that means is those aliases are protected from accidental use—that is, you cannot delete them easily. You need to use –Force to delete; however, doing so is not recommended.

The second big issue is that aliases only exist for the lifetime of the shell window. This is very similar to the DOS Set command. If you create an environment variable in a DOS window and then close that window, you destroy the variable. PowerShell aliases behave in the same way. The solution is to add the alias to your PowerShell profile.

Before you add aliases to your profile, however, be selective. Choose only the commands that you use most often to be aliases. If you have too many, you will struggle to remember them all and thus defeat the whole purpose of an alias in the first place—its usability.

There is, however, one core catch to aliasing in PowerShell that even DOS betters. It’s only practical to alias single commands or cmdlets. That means you cannot alias long, multi-command strings or even add parameters. Doing so will cause the command to fail.

Creating complex aliases

The solution, ironically, is to use functions. So, to edit your profile with “edss,” you need to define a function first and then alias the function.

Function Edit-PowerShellProfile {notepad $profile}
New-alias edal Edit-PowerShellProfile

Your profile is
<your user ID path>\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1

Now that your appetite is whetted, here are some creative alias/function pairs:

Function Get-IP4 {Ipconfig | sls IPv4}
	New-Alias IP Get-IP4

Function Get-ErrorsPerDay { Get-EventLog -LogName 'Application' -EntryType Error -After ((Get-Date).Date.AddDays(-30))| ForEach-Object{$_|Add-Member -	MemberType NoteProperty -Name LogDay -Value $_.TimeGenerated.ToString("yyyyMMdd") -PassThru} | Group-Object LogDay | Select-Object @{N='LogDay';E=	{[int]$_.Name}},Count | Sort-Object LogDay | Format-Table –Auto}
	New-alias GDE Get-ErrorsPerDay

Function Get-BootTime {wmic OS get LastBootupTime}
	New-Alias GBT Get-BootTime

Function Get-Version {$psversiontable}
	New-Alias ver Get-Version

Function Get-SerialNumber {(Get-WmiObject -Class:Win32_BIOS).SerialNumber}
	New-Alias GSer Get-SerialNumber	
	
Function Get-Model {(Get-WmiObject -Class:Win32_ComputerSystem).Model}
	New-Alias GML Get-Model

In order of appearance, these aliases display eventlog errors per day, last boot time of a machine, PowerShell version, and, finally, two deployment values: machine serial number and machine model from the BIOS, respectively.

You can, of course, split your aliases off into a separate file altogether if you want, using Export-Alias, and simply have “import-alias D:\youraliases.txt” in your profile. Note that the export will overwrite the file. To prevent that, you can use the wonderfully named –noclobber option:

Subscribe to 4sysops newsletter!

Export-Alias D:\YourAliases.txt –noclobber

Don’t get carried away as you create aliases. It’s a bad idea to create aliases in scripts, and certainly never do so in production scripts. Alias commands, but don’t do so in scripts.

What PowerShell aliases are you using?

2 Comments
  1. Valentin 7 years ago

    Hello,

    I want to create an alias like :

    set-alias -name CommitC4CK -value  ‘cp -r C:\Users\Lefranc\Documents\Classif4CustKnow_Val\ Q:\ProjetsInternes\Classif4CustKnow\’

    but it doesn’t work. If I remove the quotes it is the same.

    Any idea?

     

    Thanks

  2. You can do it with a function:

    function CommitC4CK {cp -r C:\Users\Lefranc\Documents\Classif4CustKnow_Val\ Q:\ProjetsInternes\Classif4CustKnow}

    You can then also set a alias:

    set-alias 4C CommitC4CK2

     

     

Leave a reply

Please enclose code in pre tags

Your email address will not be published.

*

© 4sysops 2006 - 2023

CONTACT US

Please ask IT administration questions in the forums. Any other messages are welcome.

Sending

Log in with your credentials

or    

Forgot your details?

Create Account