Prof. Powershell

More Fun with Aliases

PowerShell's New-Alias cmdlet makes quick work of running commands. Create new ones and share among your team.

I've written in the past about aliases and how helpful they are. To recap you can create an alias or alternate command for any PowerShell cmdlet, function, script or Windows command. Use the New-Alias cmdlet:

PS C:\> New-alias d get-childitem

Now I can type "d" at a command prompt and Get-ChildItem will run. Using aliases makes working with PowerShell interactively much easier and more efficient -- although I still recommend using full cmdlet names when writing scripts.

Let's say you add a number of new aliases:

PS C:\> New-alias na New-alias
PS C:\> na np notepad.exe
PS C:\> na cm compmgmt.msc
PS C:\> na no new-object

These aliases only exist for as long as your PowerShell session is open. You could add these commands to your PowerShell profile. But every time you wanted to keep a new alias, you'd have to modify your profile. Or if you have a team and want to share aliases, using your profile is impractical.

Instead, export your aliases using the Export-Alias cmdlet. Now you could simply run:

PS C:\ export-alias myaliases.txt

But this will also export all the default aliases defined by PowerShell, which will cause a problem when you try to import the aliases. But I have a solution, assuming you create aliases as I've done here and don't set any options, which you shouldn't really need to do.

All PowerShell-defined aliases will have the Options property defined. Your aliases will have an Options property of None. This means a command like this will work:

PS C:\> dir alias: | where {$_.options -match "none"} | export-alias \\file01\team\myaliases.txt

This will create a new text file with my aliases. If you want to append to the file, especially if more than one person will be updating the file, then use the -append parameter:

PS C:\> dir alias: | where {$_.options -match "none"} | export-alias \\file01\team\myaliases.txt -append

The change you need to make to your profile is to add this line:

import-alias \\file01\team\myaliases.txt

The Export-Alias has some other interesting options such as exporting to a CSV file or PowerShell script. Check the cmdlet help and examples for more details.

About the Author

Jeffery Hicks is an IT veteran with over 25 years of experience, much of it spent as an IT infrastructure consultant specializing in Microsoft server technologies with an emphasis in automation and efficiency. He is a multi-year recipient of the Microsoft MVP Award in Windows PowerShell. He works today as an independent author, trainer and consultant. Jeff has written for numerous online sites and print publications, is a contributing editor at Petri.com, and a frequent speaker at technology conferences and user groups.

comments powered by Disqus
Most   Popular

Upcoming Training Events