How to Set Aliases in PowerShell
ยท ๐ธ๏ธ 2 mins read
Let's enable user defined aliases!
1. Enable scripting
First, we need to enable PowerShell scripting, because by default it's disabled. Within the Powershell console, we will write (or copy/paste) this, and then press enter. (Nothing would show afterwards)
> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
If you want to read more about execution policies, go here.
2. Ok, now we need to write the aliases
There are different files where we can write the aliases. Those are the "Profile files".
Depending on what users we want to allow these scripts to be accessed, we would choose a different source file. As for this case, it's just for me: the only user on my computer. I choose the global one:
Edit to $PSHOME\Profile.ps1
.
- With
cd $PSHOME
you will navigate to the folder where theProfile.ps1
file is in your CLI. - You can also open the folder in the Files Explorer with
ii $PSHOME\
(ii
is an alias itself forInvoke-Item
in PowerShell). - Whichever the path you chose, you can then edit it with your favourite editor. I'm going to open it with VS Code. You can also do it all it one step by writing this in your CLI:
> code $PSHOME\Profile.ps1
Whithin there, let's write a custom alias (adding these lines of code at the end of the file). In this case I want an alias for npm run dev
because I find myself writing that command all the time and I want to do it with less keystrokes. ๐คท๐พโโ๏ธ Developers...
function NpmDev {
npm run dev
}
Set-Alias dev NpmDev
As you can see, the Set-Alias dev NpmDev
is the important part.
Set-Alias
register a new alias on the Profile and expects at least 2 arguments- first argument (in this case,
dev
) is my desired alias. Here you put anything you want. - second one
NpmDev
is the thing it's pointing too. It could be a program, a file location, another alias, a Powershell command or, as in this case, aFunction
's name.
You can write as many aliases as you want appending more Set-Alias
statements.
3. Save the file and restart your console
Then we need to save the Profile.ps1
file and restart the console we are using (close and open it again).
Now I can type my alias dev
in my console and it will be an alias for npm run dev
.
I decided to use a function in Powershell because that allows me to write aliases that can do more than one thing: on different lines I could put more than 1 command. ๐
Happy aliasing!