Preserving Alias Definitions

by Apr 17, 2009

Maybe you have invested some time in creating new aliases, and now you would like to know how to preserve your new aliases so that the next time you launch PowerShell again, they are still there.

You have two options. Here is the first one:

Write all alias definitions to a file using Export-Alias. You can then use Import-Alias to read them back from your file when you want them back:

Export-Alias $homemyaliases.txt
notepad $homemyaliases.txt

As you see, PowerShell saves your aliases as comma-separated values. You can import them from your list:

Import-Alias $homemyaliases.txt

However, when you do that, you get a bunch of errors because the list also contains all the pre-defined PowerShell aliases, which are write-protected. So, it is a good idea to open your exported alias list in Notepad and delete all pre-defined aliases from it before you re-import that list. Or, you can tell PowerShell to forget about error messages and silently continue anyway:

Import-Alias $homemyaliases.txt -ea SilentlyContinue

The second approach auto-generates a PowerShell script for you:

Export-Alias $homemyaliases.ps1 -as Script

To import the aliases, you simply call your new script:

. $homemyaliases.ps1

Again, it is a good idea to edit the auto-generated script and remove all pre-defined PowerShell alias definitions from it or else you wind up with a lot of error messages when you run the script.

To automatically read in your aliases when you launch PowerShell, add either way of importing to one of your profile scripts. Here is how you open a script in Notepad:

notepad $profile

Then, all you do is add the import commands and save.