Windows PowerShell Aliases

PowerShell Tutorial 3: PowerShell Aliases


Aliasing in PowerShell allows for the use of commands we become accustomed to. Windows users can utilize commands like dir, move, type, cls, etc… PowerShell also provides a set of aliases for Linux; ls, pwd, mv, man, cat, etc… PowerShell Aliases are provided for the purpose of allowing new users the ability to quickly interact with the shell. An alias is an alternative name assigned to a cmdlet. For example, “dir” is an alias for “Get-ChildItem.” This tutorial presents two types of aliases:

  • Built-in Aliases – Predefined alternative names for Windows, Unix, and PowerShell cmdlets.
  • User-defined Aliases – Custom alternative names created by the user.

Launch your PowerShell Console and let’s get started.

Built-In PowerShell Aliases

As previously described, built-in aliases are predefined. Use the following cmdlet to get a list of PowerShell Aliases:

Get-Alias <enter>

Get-Alias
Image 3.1

While browsing through the list, notice that there are multiple Aliases for the “Get-ChildItem” cmdlet. Windows “dir” command, Unix “ls” command, and a PowerShell alias “gci” command. No matter which alias you have chosen to use, typing any one of the aliases will result in the running of the “Get-ChildItem” cmdlet. Let’s test this out, type the following:

dir <enter>
ls <enter>
gci <enter>
Get-ChildItem <enter>

Get-ChildItem cmdlet
Image 3.2

Listed in Image 3.2, we can verify that each command resulted in the same output. In essence, we just ran “Get-ChildItem” four times. There is really not much more to built-in aliases. They exist to assist you while working in the shell, until you become more familiar with the cmdlets. User-Defined aliases require a little more attention.

User-Defined PowerShell Aliases

Set-Alias alias command – Simple syntax, not much to it. Let’s say I want to create a User-Defined alias for the “Get-Service” cmdlet:

Set-Alias gs Get-Service <enter>

Test your new Alias:

gs <enter>

User Defined Alias

Image 3.3

That was easy, so why does a user-defined alias need a little more attention? User-defined aliases only last while the PowerShell session is active. As soon a you quit the session, your alias is gone forever. Close your PowerShell session and re-launch PowerShell. Attempt to use the “gs” alias, you will receive the following error: “The term ‘gs’ is not recognized as a cmdlet, function, operable program, or script file. Verify the term and try again.” O.k. – Recognize the term by creating the alias again:

Set-Alias gs Get-Service

So, we have created a User-defined PowerShell alias and don’t want to lose it when we quit the session, what do we do? There are two options to explore:

  • Import/Export the PowerShell alias.
  • User-defined Aliases using PowerShell Profiles.

Import/Export User-Defined PowerShell Aliases

The purpose of Importing and Exporting is to make user-defined aliases available to multiple machines. Say you wrote a script that uses custom aliases. If you attempted to run your script on another machine, it would fail. The remote PowerShell session is not aware of the custom aliases you have created. Unless, you export the aliases to a text file in which the remote computer could import.

Go ahead and export the “gs” alias using the “Export-Alias” cmdlet:

Export-Alias -Path Aliases.txt <enter>

Since I am running from my home directory “C:\MyScripts” the Aliases.txt file will be created there. Use the “-Path” parameter to set the desired location. One option is to save the export file to a UNC path so that it is available from a network share. Open “Aliases.txt” in notepad:

PS C:\MyScripts>notepad Aliases.txt <enter>

Do you notice anything odd about the text file?

Export-Alias cmdlet

Export-Alias

Image 3.4

Not only did it export the “gs” user-defined alias we created, it exported ALL PowerShell aliases. Is this an issue? If we attempt to import the Aliases.txt file, PowerShell will report an error for each alias that already exists. Import the Aliases.txt file using the “Import-Alias” cmdlet:

Import-Alias -Path Aliases.txt <enter>

Alias Import Error
Image 3.5

That looks ugly… but, if the alias does not exist, it will get imported. There is actually a better way to do this. The example above was shown to make you aware of a potential problem when you are importing and exporting aliases. By using the -Name parameter, you can export only the aliases you choose. So with our “gs” alias let’s attempt the following:

Export-Alias -Path Alias.txt -Name gs <enter>
notepad Alias.txt <enter>

Alias Export with Name Paramter
Image 3.6

That looks much better… What do you think would happen if you attempted to import this file? If your PowerShell Session is still active, you should get the import error because the “gs” alias still exists in the current session. Exit your PowerShell session and re-launch PowerShell.

Let’s import the Alias.txt file:

Import-Alias -Path Alias.txt <enter>
gs <enter>

Import-Alias gs
Image 3.7

No error reported when importing the Alias.txt file and entering the “gs” alias provides us with the output expected.

Importing and Exporting allows for the use of user-defined aliases on local and multiple systems. What if you just wanted to use custom aliases on your local system and don’t want to be burdened with importing a file each time you launch PowerShell? PowerShell profiles allow you to customize the PowerShell environment at launch time. The last section of this tutorial introduces the PowerShell profile. We are only going to discuss profiles as it pertains to user-defined aliases. With Profiles, there are many options to customize your PowerShell environment, which will be covered in this series.

User-Defined Aliases using PowerShell Profiles

What is a PowerShell Profile? In simplest terms, a profile is a script that runs at session startup. The location of the Profile is stored in the $Profile variable, which by default is “My Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1″
To verify the location of your profile type:

$Profile <enter>

Profile Variable
Image 3.8

In image 3.8 you can see the path to my profile, which happens to be were “My Documents” are stored. As already mentioned, the profile is a script which is denoted by the “.ps1″ extension. All PowerShell scripts are identified by this extension. Since the profile is a PowerShell script we will need to edit it. You can use any PowerShell editor, in this tutorial I will be using Notepad. Before editing the file we need to check the PowerShell execution policy.

When PowerShell is first installed the default execution policy is “Restricted.” This means PowerShell will not run scripts or configuration files. Here is a list of policy levels:

  • Restricted – We know what this means.
  • AllSigned – All scripts and configuration files must be signed by a trusted publisher.
  • RemoteSigned – All scripts and configuration files downloaded from the Internet must be signed by a trusted publisher.
  • Unrestricted – All scripts and configuration files will run. Scripts downloaded from the Internet will prompt for permission before running.

Use the “Get-ExecutionPolicy” cmdlet to verify policy level:

Get-ExecutionPolicy <enter>

What is your policy set at? By definition, since the profile is a script file, the execution policy should be set to anything other than “Restricted.” For this exercise you will set your policy to “Unrestricted.” Here is how to set that policy:

Set-ExecutionPolicy Unrestricted <enter>

Now that the policy is set to run scripts, let’s create a profile by following the steps below:

Step 1. Verify existence of a profile.

test-path $Profile <enter>

If the result = False. No profile exists (continue to step2).
If the result = True. Profile exists (skip steps 2 & 3). Unless you want to create a new profile, which will delete the current profile.

Step 2. Create a new profile.

New-Item -Path $Profile -ItemType file -Force <enter>

Step 3. Verify new profile was created.

Repeat step 1. Result should equal “True.”

Let’s open our new profile in notepad:

notepad $Profile <enter>

PowerShell Profile Notepad
Image 3.9

Isn’t that great! We have a blank page! The important thing to note: We have a script file called “Microsoft.PowerShell_profile.ps1″

This script file will be called using the $Profile variable each time a PowerShell session is launched. What goes into the script file will be up to you, how you decide to configure your PowerShell environment. For now, let’s have our profile load our custom user-defined PowerShell alias. Edit and Save the profile as shown below:

PowerShell Profile Saved
Image 3.10

After you have saved the profile, close notepad, and exit the PowerShell session.

Launch a new PowerShell session and verify that your custom alias is functional:

gs <enter>

Viola! your profile has loaded successfully and your alias is working. Use “Get-Alias” cmdlet to verify the existence of your new alias:

Get-Alias <enter>

-or- a more refined search:

Get-Alias -Name gs <enter>

Hope you enjoyed the Tutorial on PowerShell Aliases, we covered a lot. Built-in aliases, user-defined aliases, importing aliases, exporting aliases, a small preview into profiles, and PowerShell script files. See you in the next tutorial.

Email This Page To A Friend Email This Page To A Friend

Comments

By Kevin Kelleher on November 5th, 2007 at 8:45 am

I think it would be helpful for those us with a unix background to make it clear that PowerScript aliases are aliases for single words. I didn’t realize this at first, and couldn’t understand why I couldn’t redefine “ls” as “get-childitem -force -name”.

By Roy Pardee on May 30th, 2008 at 2:13 pm

Ach–thanks Kevin! I’ve been surfing around for a while now looking for multi-word examples & trying different combinations of single/double quotes & escapes & such and having no luck.

I guess it’s *functions* that I need to be able to do multi-word commands?

I don’t know if having My Documents redirected to the D: drive has anything to do with it, but the Profile.ps1 results in the following for me:

Incomplete string token.
At line:1 char:14
+ . ‘F:\Jim`’s D <<<< ocuments\WindowsPowerShell\profile.ps1′

I am new to this, when i tried to set the execution policy i got this. i am running this on windwos vista business;is that expectied ?

Set-ExecutionPolicy : Access to the

registry key ‘HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft
.PowerShell’ is denied.
At line:1 char:20
+ Set-ExecutionPolicy <<<< unrestricted

Set-ExecutionPolicy : Access to the
registry key ‘HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft
.PowerShell’ is denied.
At line:1 char:20
+ Set-ExecutionPolicy <<<< unrestricted

I get the same thing as Joe. Any way to fix this?

Set-ExecutionPolicy : Access to the registry key ‘HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft
.PowerShell’ is denied.
At line:1 char:20
+ set-executionpolicy <<<< unrestricted
+ CategoryInfo : NotSpecified: (:) [Set-ExecutionPolicy], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.SetExecutionPolicyComma
nd

Apologies, the command is slightly different.

Luke
You have to execute the set-executionpolicy as admin. if you are on Vists, try run as administrator

\\Greg

Here’s my question – I have my home directory redirected to a network path and everytime PS tries to load my profile, it prompts with this:

Run only scripts that you trust[...] Do you want to run H:\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1?
[D] Do not run [R] Run once [S] Suspend [?] Help (default is “D”):

other than signing the script, is there a way around it?

\\Greg

Thanks for the email, Jesse.

Adding my AD domain to the local intranet sites
in IE did the trick. Add it as file://*.mydomain.com

Excellent!

\\Greg

Your tutorial is awesome, thx a lot :)

By Bingo Little on March 16th, 2009 at 3:13 am

Great tutorial! Thanks.

Q: Does PS remember the ExecutionPolicy across sessions? How?

None of the following commands: dir, ls, gci, or Get-ChildItem produce any result. Is my PowerShell not installed and configured correctly? I am running on an XP Pro machine.

John

This is embarassing to say, but here goes. The reason no result was produced is that the folder was empty. Adding a sample file to the folder and running the commands again produced a listing o fthe sample file.

I love the tutorials so far! I ran into a problem though!
I’m trying to run:

export-alias -path Aliases.txt

and i’m getting:

Export-Alias : Unknown error “-1″.
At line:1 char:13
+ export-alias <<<< -path aliases.txt

I’ve tried everything, but i’m getting the same error! Can anyone tell me what I can do? Thanks!

Nice! great tutorial. I hope I will understand more about PowerShells for my profession. Excellent! :)

@Drew

Kindly try this one:

PS D:\MyScripts> Export-Alias
cmdlet Export-Alias at command pipeline position 1
Supply values for the following parameters:
path[0]:aliases.txt
path[1]:

PS D:\MyScripts>
PS D:\MyScripts> dir <– check whether your txt file has been created.

Thanks.
-Arjay

As already mentioned the Vista executionPolicy errors can be corrected by running as administrator. You can do this from the start menu by right clicking on powershell and choosing Run As Administrator. Or alternatively, if you’ve set up a desktop shortcut for powershell, right click on the the icon, choose properties, then choose the shortcut tab in the properties window. On that tab, click the advanced button and check the Run as administrator box in the resulting advanced properties window.
Of course, all this assumes you’ve logged on as an admin user in the first place.

Bingo Little: Try typing “Get-Help Set-ExecutionPolicy -Full”

In the “NOTES” section of the help text it explains that “the new user preference is written to the registry and remains unchanged until you change it.”

Great tutorials.. I have been using the virtual labs from MS and these are by far much easier to understand and follow. Thank you so much for your hard work on these..

This is really good! a few years ago I slogged through a few chapters of a book on PS and found it interesting but kind of obtuse. Your Tutorial is very elegent and makes practical sense!

Excelllent! very elegant and simple. Thank You.

i love this tutorial. thanks

Great tutorial indeed – but I have a problem!

I want to start the Powershell through the commandline by typing ‘ps’ instead of ‘powershell’.

Any way of doing that?

make a batchfile.

start cmd

echo powershell > ps.bat

ps

should start powershell

Great tutorials!
What if I want keep profile in my working directory (somewhere on D:) and open PowerShell with customised-personalised profile? Is it possible?

@Dennis
I open powershell with ps directly from run (Win-logo R)
In the registry create new key at
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\ps.exe
with value
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

does the trick?

:Dennis
I open powershell with ps directly from run (Win-logo R)
In the registry create new key at
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\ps.exe
with value
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe

does the trick?

At first the “Run as Administrator” technique didn’t work for me. I guess it does for many out there but if not, as a permanent fix you can add the permission in directly via the windows registry. It’s pretty easy and eliminates the need to “run as admin”.

See http://kyleclegg.com/powershell/

Hope this helps someone!

By Peter Wood on March 15th, 2011 at 6:17 am

Great tutorial! Thanks for the help!

Dont bother hacking the registry.

Right click the powershell shortcut on your desktop. Click advanced, click run as administrator.

Works for most any shortcut.

Thanks so much!

I am hopeless and this series is brilliant.

Cheers

Worked great for me!

Excellent Tutorial!

get-service name PowerShellProTutorial

Bill

Have you ever seen the behavior where you have the default start folder set but it changes to C:\Windows\system32 when you Run as Administrator?

It was really great and fun by learning powershell step by step. I love it just because its not theory but practical. It helps me a lot in my project. Thank you so much :)
I have a doubt..
by setting alias thru profile.. how many alias can be added(user defined)?? can u explain adding more alias to the profile?

I have the same issue as Lori. The “Start in” is ignored when running as Administrator. Also noticed the “$Path” variable no longer seems to be populated. I removed the ‘run as’ and it now respects the ‘Start in’, but $Path is still not set. Also, when Run As Adminitstator, it kept prompting st startup asking me if I wanted to allow the program to make changes to the computer. Win7 Pro 64.

This is how you would do a cd alias. Place the code in your profile file:

function exampleDir {Set-Location C:\Users\Hugo\Example}

Set-Alias cdExample exampleDir

Note:

The name of the alias cannot be the same than the function name.

Regards,

Robert

It’s amazing to me that seting the powershell to unrestricted usage is persistant beyond the life of your session – which is inherently dumb.
Seems like there should be a $profile type of variable when the shell closes, then you can set the shell to unrestricted when being used and back to restricted when it closes.

when i add the microsoft.powershell_profile.ps1 and start up powershell, it just sits there after the copyright notice. I checked syntax in the file, made it blank, and still the same. When I rename the file, it opens right up, so I know it’s actually reading the file… Any ideas?

Win7, running as admin….

@orschiro/Robert – thank you so much for that tip! brilliant!

By Steven Kitterman on July 10th, 2012 at 8:37 am

Thanks for your tutorials. I am brand-new to Powershell and still have a lot of gaps to fill, but so far I feel I am learning. Thank you for making these tutorials easy to understand and follow.

Thanks very much for these tutorials. I have a suggestion: If you’re going down the command-line route, then drop notebook and use vim. You’ll never look back…

For those with the problem opening in c:\windows\system32 when run as administrator from a shortcut, do this.

Go to properties of shortcut, on shortcut tab under target, add this to the end of the target:
-NoExit -Command “cd f:\MyScripts”

of course, change the f:\MyScripts to the path you wish to use.

Click apply, and run it. Should now open starting in your custom home target.

In response to Sanfords question about ExecutionPolicy only elevated to unrestricted during session, there is a way to do it.

Add this-> -ExecutionPolicy Unrestricted

to the end of target in the properties/shortcut tab on the shortcut you run ps from.

Thanks! You made this easy. Read through all these tutorials in an afternoon and I am already up to speed to manage my Sharepoint server with Powershell (I’m already a .Net developer) Yeah! Don’t have to change 100 report data sources by hand. It will be fun seeing what else it can do to help me manage my custom Sharepoint environments.

learning a lot here, thank you.

Excellent tutorial. This works when I alias to an executable. How do I set up aliases to a directory?

example: I want to type:

mike and have pwoershell go to directory c:\Mike

I tried generating an alias and modifying the resultant working file, but, no luck so far.

When doing this I had a small issue regarding the user of “notepad” as it constantly was not recognized as an operable program and all that good stuff. Only solution to this that I(newbie) could find was to do “start notepad $profile” instead. But then again I’m not exactly experienced at coding so I wouldn’t know much about any tricks or fix. Just in case someone has the same problem as I had/have.

Also, great tutorials, I guess you’re never in here anymore as it starts to get ancient, but it’s easy to follow and really useful. I really appreciate it.

Sorry to be French but shortly after the image 3.10 you enter the following text:

” Viola! your profile has loaded successfully and your alias is working.”

I am sure it was a typo but just in case, It’s Voila not Viola! viola actually means ” (someone) rapped….”

Cheers,

Stéphane

 

Leave a Comment