Windows PowerShell Aliases

So, would you rather type something like Get-AuthenticodeSignature or would you rather type something like gas? We had a feeling you’d say that.

 

Samuel Clemens. Archibald Leach. Ramón Gerardo Antonio Estévez. William Sydney Porter. The list goes on…. And exactly what is this a list of? Well, as you might have figured out it’s a list of the given names of people who decided they didn’t want to (or couldn’t) become famous with those names. Instead, they took on new names, or aliases, in order to be more easily identified and remembered. As it turns out, Windows PowerShell has decided to join the other celebrities in utilizing aliases. How so? Read on.

It’s true that Windows PowerShell, before it became Windows PowerShell, began life with the given name Monad. It then briefly tried out MSH (pronounced “mish”), and finally settled on the catchy, rolls-smoothly-off-the-tongue, Windows PowerShell. Given that lifecycle you might think of Windows PowerShell as an alias. The problem is that, if we call it an alias, the Microsoft lawyers will be very unhappy: it was a legal name change. And because we find it best not to make the lawyers unhappy, we won’t use the term “alias” to refer to Windows PowerShell. But we will use the term “alias” to talk about a certain renaming feature within PowerShell. These aliases serve the same purpose as the aliases we mentioned at the beginning of this article: they make certain things in Windows PowerShell easier to identify and remember. (Although in some cases, if you’re not careful, an alias can be pretty effective at hiding an identity.)

Aliases Defined

Within PowerShell, an alias is simply another name assigned to a cmdlet, function, script, executable, and so on. Just about anything you can run from the PowerShell command prompt can have an alias assigned to it. We’ll explain how this works and why you’d even care about this by first showing you some of the aliases built-in to PowerShell. After that we’ll show you how to make aliases of your own. And then, after we’ve covered that, we’ll show you how to make sure the aliases you create stick around from one PowerShell session to another.

Are you ready for all that? Don’t worry, this will be easy. Even easier than remembering who Norma Jeane Mortenson was.

Built-In Aliases

Windows PowerShell 2.0 ships with well over 100 built-in aliases. You can find these aliases with the Get-Alias cmdlet:

PS C:\scripts> get-alias

CommandType Name Definition

----------- ---- ----------

Alias % ForEach-Object

Alias ? Where-Object

Alias ac Add-Content

Alias asnp Add-PSSnapIn

Alias cat Get-Content

Alias cd Set-Location

All the built-in aliases are simply short versions of cmdlet names. For example, the alias for Get-Alias is gal:

PS C:\scripts> gal

CommandType Name Definition

----------- ---- ----------

Alias % ForEach-Object

Alias ? Where-Object

Alias ac Add-Content

Alias asnp Add-PSSnapIn

Alias cat Get-Content

Alias cd Set-Location

Alias chdir Set-Location

Alias clc Clear-Content

Alias clear Clear-Host

You can use these aliases alone, like we just did, or anywhere within a command string where you’d use the cmdlet. For example, here’s a command that retrieves the cmdlet associated with the alias ac:

PS C:\scripts> gal -name ac

CommandType Name Definition

----------- ---- ----------

Alias ac Add-Content

You can imagine how much typing this can save you in the long run. Just to demonstrate, here’s a command that retrieves the five smallest text files in the C:\ folder:

get-childitem C:\*.txt | sort-object -property length | select-object -last 5

Here’s that same command using built-in aliases:

ls C:\*.txt | sort -property length | select -last 5

That’s better.

Note. If you use shorthand for the parameters you can compact this even more:

ls C:\*.txt | sort -p length | select -l 5

But keep in mind that parameter resolution is a completely different feature than aliases. We’re not going to talk about parameters here. If this just confused you, ignore this note and keep reading.

A lot of the aliases are built-in simply to give you a quicker way to access cmdlets. However, some of them are there to make sure you can do things such as navigate your way around the file system in the command window by using familiar commands. For example, here are the commands you can use to list the items in the current directory:

Shell

Command

MS-DOS

Dir

Unix

Ls

Windows PowerShell

Get-ChildItem

Admittedly, PowerShell’s commands sometime seem a little cumbersome compared to the others. But with built-in aliases you can use any of these commands in PowerShell (in addition to the alias gci) to retrieve the contents of a folder.

Finding Aliases

We already showed you how to get a list of all the aliases available (the Get-Alias cmdlet). Here’s how to get a list of aliases sorted by alias:

get-alias | sort-object

Want to sort by definition (the cmdlet, function, etc. that the alias is an alias for)? Okay:

get-alias | sort-object definition

How about this: let’s retrieve the definition associated with a given alias. We’ll try the cd alias:

PS C:\scripts> get-alias cd

CommandType Name Definition

----------- ---- ----------

Alias cd Set-Location

This is all pretty simple, right? The next logical step would be to find all the aliases associated with a given cmdlet (or definition). That’s pretty easy too:

PS C:\scripts> Get-Alias -Definition Set-Location

CommandType Name Definition

----------- ---- ----------

Alias cd Set-Location

Alias chdir Set-Location

Alias sl Set-Location

Creating Aliases

Okay, this is all very nice, but what if you don’t like the built-in aliases? Or what if you want to set an alias for a function that you’ve created? As it turns out, this is no problem at all. Simply use the Set-Alias cmdlet. Suppose you want to retrieve the current date. You could do that with the Get-Date cmdlet:

PS C:\scripts> Get-Date

Monday, June 7, 2010 3:47:56 PM

That’s simple enough, but let’s make it even simpler – let’s set an alias for Get-Date:

Set-Alias d Get-Date

Logically enough, we use the Set-Alias cmdlet to create an alias. We pass two parameters to this cmdlet: the new alias (d) and the cmdlet being aliased (Get-Date). Let’s try it out:

PS C:\scripts> d

June 7, 2010 3:49:51 PM

The cmdlet works exactly the same; we just use an alias to reference it. For example, you can pass parameters to the alias in the same way you’d pass them to the cmdlet:

PS C:\scripts> d -displayHint date

June 7, 2010

As you can see, we used the -DisplayHint parameter of the Get-Date cmdlet to display only the date portion of the date/time value, but we used that parameter with the d alias.

You can also alias functions. Here’s a function that finds the default printer on the local computer.:

function FindDefaultPrinter

{

Get-WMIObject –query "Select * From Win32_Printer Where Default = TRUE"

}

To run this function, simply type the name of the function, FindDefaultPrinter, at the command prompt:

PS C:\scripts> FindDefaultPrinter

Location : USA/REDMOND, WA/42/FLOOR4/4032

Name : \\PRINTER1\HP LaserJet

PrinterState : 0

PrinterStatus : 3

ShareName : HP LaserJet

SystemName : \\PRINTER1

What’s that? FindDefaultPrinter is a big long name that you don’t want to type in every time you want to check for the default printer? Okay, how about this:

PS C:\scripts> dp

Location : USA/REDMOND, WA/42/FLOOR4/4032

Name : \\PRINTER1\HP LaserJet

PrinterState : 0

PrinterStatus : 3

ShareName : HP LaserJet

SystemName : \\PRINTER1

Will that work? Well, no, not unless you do this:

Set-Alias dp FindDefaultPrinter

Now it will work.

You can also alias executable files. Want to start Microsoft Excel from the command prompt? Why would you ever want to do that? Oh well, that’s none of our business. But if you do, you could do it like this (assuming you have the default installation for Excel 2007):

.”C:\Program Files\Microsoft Office\Office12\Excel.exe”

Note. The dot (.) is required. If you leave it out, PowerShell will just display the text that’s within the quotes. Not exactly what we had in mind.

Or you could simply alias the command:

Set-Alias excel "C:\Program Files\Microsoft Office\Office12\Excel.exe"

Now all you have to type is this:

Excel

It doesn’t get much easier than that.

Keeping Aliases Around

You’ve now spent a significant amount of time setting up all your aliases. Okay, maybe “significant” is exaggerating a little, but, nevertheless, you did spend some time on this. And all system administrators know exactly how valuable time is and how little we have to waste, which is why we set up aliases in the first place. Now suppose you shut down Windows PowerShell, move on to some other tasks, and later restart PowerShell. Hmmm, let’s use our alias d to see what day it is today:

The term 'd' is not recognized as a cmdlet, function, operable program, or script file. Verify the term and try again.

At line:1 char:2

+ d <<<<

+ CategoryInfo : ObjectNotFound: (d:String) [], CommandNotFoundException

+ FullyQualifiedErrorId : CommandNotFoundException

Wait a minute – didn’t we just set the alias d to represent the cmdlet Get-Date? Yes, as a matter of fact we did. But then we shut down Windows PowerShell. Big mistake. Don’t ever, ever, shut down Windows PowerShell.

Well, not unless you save your aliases first. Otherwise any aliases that you created during that PowerShell session will disappear.

There are two ways to save your aliases. The first approach is to export your aliases to a file. This is much easier than it might sound; that’s because PowerShell makes it easy by providing the Export-Alias cmdlet:

Export-Alias MyAliases.csv

You need to pass Export-Alias only one parameter (although there are more parameters, which we’ll talk about in a moment): the name of the text file that you want to save your aliases to. By default the file is saved as a comma-separated values file (which is why we gave it a .csv file extension, although you could also simply give it a .txt file extension).

Note: If you don’t want the file saved to the current path, you must specify the full path to the file:

Export-Alias C:\Files\MyAliases.csv

This command will export all aliases – user-defined and built-in – to the given file. Keep that in mind, because that could be a bit of a nuisance. We’ll show you that in a moment, too. But first, let’s talk about what we need to do with these aliases now that we’ve exported them.

As we mentioned, when you close your PowerShell session all the aliases you defined will disappear. That means that the next time you open PowerShell, you’ll need to redefine all your aliases. However, if you exported them to a file first, you can simply import them back into your session and all your aliases will be back. You do that with the Import-Alias cmdlet:

Import-Alias MyAliases.csv

Simply pass the name of the file that contains your exported aliases (including the full path if the file isn’t in the current directory) to the Import-Alias cmdlet. Now you can use any of the aliases you had defined before the import.

What’s that? You tried this and got a big long list of errors? A list like this:

Import-Alias : Alias not allowed because an alias with the name ‘ac’ already exists.

At line:1 char:13

+ Import-Alias <<<< MyAliases.csv

Import-Alias : Alias not allowed because an alias with the name ‘asnp’ already exists.

At line:1 char:13

+ Import-Alias <<<< MyAliases.csv

Import-Alias : Alias not allowed because an alias with the name ‘clc’ already exists.

At line:1 char:13

+ Import-Alias <<<< MyAliases.csv

First of all, don’t worry: your aliases are still there, and if you try one you’ll see that the import succeeded and your aliases will work just fine. So why all the errors? Remember when we said Export-Alias will export all aliases, user-defined and built-in? Well, the user-defined aliases were wiped out when you closed PowerShell, but the built-in aliases weren’t. That means that, when you run Import-Alias, all those built-in aliases that were exported will be re-imported. And that’s a problem, because you can’t overwrite existing aliases. Make sense? On the one hand these errors don’t hurt anything: they simply inform you that you can’t import a built-in alias because it already exists. On the other hand, who wants to see all those error messages every time they import the file? Not us, that’s for sure. But don’t worry, there’s something you can do about it.

One simple thing you can do is edit the alias file after you export it. Your exported file will then look something like this:

# Alias File

# Exported by : kenmyer

# Date/Time : Wednesday, September 16, 2009 6:58:03 PM

# Machine : ATL-FS-01

"ac”,”Add-Content”,”“,”ReadOnly, AllScope”

“asnp”,”Add-PSSnapIn”,”“,”ReadOnly, AllScope”

“clc”,”Clear-Content”,”“,”ReadOnly, AllScope”

“cli”,”Clear-Item”,”“,”ReadOnly, AllScope”

“clp”,”Clear-ItemProperty”,”“,”ReadOnly, AllScope”

“clv”,”Clear-Variable”,”“,”ReadOnly, AllScope”

Simply delete all the references to built-in aliases. Don’t worry, this isn’t hard to do: all the built-in aliases are listed first; your custom aliases are all at the bottom of the file:

“set”,”Set-Variable”,”“,”AllScope”

“type”,”Get-Content”,”“,”AllScope”

“d”,”get-date”,”“,”None”

“dp”,”FindDefaultPrinter”,”“,”None”

“excel”,”C:\Program Files\Microsoft Office\Office12\Excel.exe”,”“,”None”

See those last three, d, dp, and excel? Those are the aliases we added earlier. They’ll always be at the bottom.

The other thing you can do is add specific aliases to the file rather than doing a global export. You do this by passing a second parameter to Export-Alias, the name of the alias you want to export:

Export-Alias MyAliases.csv d

Here we’ve passed the alias d, which we set up for Get-Date. Here’s what our alias file looks like now:

# Alias File

# Exported by : kenmyer

# Date/Time : Wednesday, September 16, 2009 6:58:03 PM

# Machine : ATL-FS-01

“d”,”get-date”,”“,”None”

Here’s something important to know: every time you call Export-Alias, the current file is overwritten. That means that if you now call Export-Alias to export a different alias, d will be gone and will be replaced by the new alias. Like this:

Export-Alias MyAliases.csv dp

# Alias File

# Exported by : kenmyer

# Date/Time : Wednesday, September 16, 2009 6:58:03 PM

# Machine : ATL-FS-01

“dp”,”FindDefaultPrinter”,”“,”None”

But wait, here’s something even more important to know: you can pass another parameter to Export-Alias to make sure the new aliases are appended rather than overwritten:

Export-Alias MyAliases.csv d –append

Here’s what we have now:

# Alias File

# Exported by : kenmyer

# Date/Time : Wednesday, September 16, 2009 6:58:03 PM

# Machine : ATL-FS-01

“dp”,”FindDefaultPrinter”,”“,”None”

# Alias File

# Exported by : kenmyer

# Date/Time : Wednesday, September 16, 2009 6:58:03 PM

# Machine : ATL-FS-01

“d”,”get-date”,”“,”None”

Granted, this file could still use some cleanup, but you don’t have to clean it up. (Although, if you want to, it’s easy enough to do.) Either way, you won’t get any more error messages.

Note that exporting and importing aliases isn’t just handy for keeping aliases from one session of PowerShell to the next; you can also copy the exported file to different machines and import them into the instance of PowerShell on those machines. Nice, huh?

We mentioned that, by default, exported aliases are saved to a comma-separated values (csv) file. That’s nice, but suppose, instead of repeatedly importing aliases, you want to run a script that will run the Set-Alias commands to re-create your aliases? Well, you’re in luck, because the Export-Alias cmdlet has a parameter named -As that lets you specify the output as a script file:

Export-Alias -As script MyAliases.ps1 d

Here we’ve called the Export-Alias cmdlet with the –As parameter, followed by the value “script”. We then pass the name of the file we’re exporting to, this time giving it a .ps1 extension (the file extension for PowerShell scripts), and the alias (d) that we want to export. When we open the MyAliases.ps1 file, this is what we see:

# Alias File

# Exported by : kenmyer

# Date/Time : Wednesday, September 16, 2009 7:21:50 PM

# Machine : ATL-FS-01

set-alias -Name:"d" -Value:"get-date" -Description:""-Option:"None"

Notice that the command isn’t exactly the same as what we typed to the command line to set the alias. Export-Alias doesn’t look back into your history to see what aliases were set, it simply looks at the available aliases (or the specified aliases, such as, in this case, d) and creates a Set-Alias command that would re-create that alias.

The next time you close Windows PowerShell and then reopen it, you can type this at the command prompt:

PS C:\scripts> . .\MyAliases.ps1

This runs the script, which includes the Set-Alias statement. Now when you type d at the command prompt, you get the output from Get-Date, the cmdlet that our alias refers to.

Note. The extra dot (.) in front of the path isn’t a mistake. If you don’t include that, the Set-Alias statement will run, but the results won’t be saved to the current instance of Windows PowerShell. Confused? Read the part about running scripts in the Introduction to Scripting article.

Now, at first glance, this might seem like more trouble – or at least not any simpler – than saving aliases to a .csv file and running the Import-Alias cmdlet. However, there’s one more thing you can do to keep your aliases from one PowerShell session to another. Simply add the Set-Alias commands (the ones that you generated using the –As Script parameter) to your Windows PowerShell profile and your aliases will be available every time you start PowerShell, without having to importing aliases or manually run scripts.

We won’t go into detail on profiles here, to learn more see the article on Windows PowerShell Profiles for details. We’ll just show you quickly how simple it is to add the aliases to your profile.

Note. The example we’ll be showing you works with the profile with a scope of current user, current host. There are other profiles you can work with, which are explained in the Profiles article.

Start by opening your profile in Notepad, like this:

notepad $profile

Now just enter your Set-Alias commands (and any necessary functions) into your profile:

Set-Alias d Get-Date

function FindDefaultPrinter

{

    Get-WMIObject –query "Select * From Win32_Printer Where Default = TRUE"

}

Set-Alias dp FindDefaultPrinter

Set-Alias excel "C:\Program Files\Microsoft Office\Office12\Excel.exe"

Save the profile, close it, close Windows PowerShell, then open PowerShell again. Try out any of the aliases we just saved – they’ll all work. Every time, no extra steps involved.

How easy was that?!

Alias Restrictions

There are a couple things that you can’t do with aliases. One is that you can’t alias a cmdlet with specific parameters. For example, say you use this command a lot:

Set-Location C:\Scripts\old

If so, it might be useful to you to create an alias to this command. Let’s give it a try:

Set-Alias toOld (Set-Location C:\Scripts\old)

Will this work? Nope. Here’s what you get back:

Set-Alias : Cannot bind argument to parameter ‘Value’ because it is null.

At line:1 char:10

+ Set-Alias <<<< toOld (Set-Location c:\scripts\old)

+ CategoryInfo : InvalidData: (:) [Set-Alias], ParameterBindingValidationException

+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.SetAliasCommand

If you want to do something like this, you need to put the cmdlet in a function, then alias the function:

function toOld{Set-Location C:\Scripts\Old}

Now you can either call the function toOld, or you can alias the function:

set-alias to toOld

Now typing either toOld or to will take you to the C:\Scripts\Old folder.

You also can’t alias a pipelined command. Try this:

Set-Alias as (Get-Alias | Sort-Object)

It didn’t work, did it? Again, you can put the command in a function and then set an alias, but you can’t directly alias a pipelined command.

The End

Oh, and in case you haven’t figured it out yet, the names we mentioned at the beginning of this article belong to Mark Twain, Cary Grant, Martin Sheen, and O. Henry. Makes us wonder if we should give ourselves an alias….