I want to create an alias of a cmdlet that doesn't expire after I close the current session of PowerShell. Let's say I have this alias:
cd C:\Users\Aymen
New-Alias Goto Set-Location
This perfectly creates the Goto alias, but I want to use it even after I close the current session. How can I achieve that?
Note:
The PowerShell Help system suggests that I can export the aliases I create, and import them next time I open a new session. Actually, that's not really what I'm looking for. Is there a direct clear way to keep having a alias after I create it through different sessions?
14 Answers 14
UPDATED - January 2021
It's possible to store in a profile.ps1 file any PowerShell code to be executed each time PowerShell starts. There are at least 6 different paths where to store the code depending on which user has to execute it. We will consider only 2 of them: the "all users" and the "only your user" paths (follow the previous link for further options).
To answer your question, you only have to create a profile.ps1 file containing the code you want to be executed, that is:
New-Alias Goto Set-Location
and save it in the proper path:
"$Home\Documents"(usuallyC:\Users\<yourname>\Documents): only your user will execute the code. This is the recommended location You can quickly find your profile location by runningecho $profilein PowerShell$PsHome(C:\Windows\System32\WindowsPowerShell\v1.0): every user will execute this code
IMPORTANT: remember you need to restart your PowerShell instances to apply the changes.
TIPS
If both paths contain a
profile.ps1file, the all-users one is executed first, then the user-specific one. This means the user-specific commands will overwrite variables in case of duplicates or conflicts.Always put the code in the user-specific profile if there is no need to extend its execution to every user. This is safer because you don't pollute other users' space (usually, you don't want to do that).
Another advantage is that you don't need administrator rights to add the file to your user-space (you do for anything in C:\Windows\System32).If you really need to execute the profile code for every user, mind that the
$PsHomepath is different for 32bit and 64bit instances of PowerShell. You should consider both environments if you want to always execute the profile code.The paths are:
C:\Windows\System32\WindowsPowerShell\v1.0for the 64bit environmentC:\Windows\SysWow64\WindowsPowerShell\v1.0for the 32bit one (Yeah I know, the folder naming is counterintuitive, but it's correct).
15 Comments
\Users\{ME}\Documents\WindowsPowerShell and then add Microsoft.PowerShell_profile.ps1 non of the other paths works for me."$HOME\Documents\WindowsPowerShell" and naming Microsoft.PowerShell_profile.ps1 restrict the scope to non-ISE and to current host, but shouldn't be a matter of permissions (same of "$Home\Documents\profile.ps1" should apply). Maybe it's not really so, I will give it a try, thank you for the informationNew-Item -path $profile -type file -force that created the folder and file Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1It's not a good idea to add this kind of thing directly to your $env:WINDIR PowerShell folders, unless you truly want your alias to be global.
The recommended way is to add it to your personal profile:
cd $env:USERPROFILE\Documents
md WindowsPowerShell -ErrorAction SilentlyContinue
cd WindowsPowerShell
New-Item Microsoft.PowerShell_profile.ps1 -ItemType "file" -ErrorAction SilentlyContinue
powershell_ise.exe .\Microsoft.PowerShell_profile.ps1
Now add your alias to the Microsoft.PowerShell_profile.ps1 file that is now opened:
function Do-ActualThing {
# Do the actual thing
}
Set-Alias MyAlias Do-ActualThing
Then save it, and refresh the current session with:
. $profile
Note: Just in case, if you get permission issue like
CategoryInfo : SecurityError: (:) [], PSSecurityException + FullyQualifiedErrorId : UnauthorizedAccess
Try the below command and refresh the session again.
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
9 Comments
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser. The -Scope option makes it a bit more secure.MyAlias. Also, to pass on arguments, use @Args, eg function gs { git status @Args }Set-Alias because I like to name my methods using the appropriate PS conventions with the appropriate Verbs. But yes, if you're not picky, you can just name your method whatever you intend to invoke.Open a Windows PowerShell window and type:
notepad $profile
Then create a function, such as:
function goSomewhereThenOpenGoogleThenDeleteSomething {
cd C:\Users\
Start-Process -FilePath "http://www.google.com"
rm fileName.txt
}
Then type this under the function name:
Set-Alias google goSomewhereThenOpenGoogleThenDeleteSomething
Now you can type the word "google" into Windows PowerShell and have it execute the code within your function!
7 Comments
2018, Windows 10
You can link to any file or directory with the help of a simple PowerShell script.
Writing a file shortcut script
Open Windows PowerShell ISE. In the script pane write:
New-Alias ${shortcutName} ${fullFileLocation}
Then head to the command-line pane. Find your PowerShell user profile address with echo $profile. Save the script in this address.
The script in PowerShell's profile address will run each time you open powershell. The shortcut should work with every new PowerShell window.
Writing a directory shortcut script
It requires another line in our script.
function ${nameOfFunction} {set-location ${directory_location}}
New-Alias ${shortcut} ${nameOfFunction}
The rest is exactly the same.
Enable PowerShell Scripts
By default PowerShell scripts are blocked. To enable them, open settings -> Update & Security -> For developers. Select Developer Mode (might require restart). Selecting Developer Mode Windows 10.
Scroll down to the PowerShell section, tick the "Change execution policy ..." option, and apply.
2 Comments
echo $profile is an awesome tip for helping finding the correct location to add the file. Thank you for the comprehensive answerI found that I can run this command:
notepad $PROFILE.CurrentUserAllHosts
and it opens my default powershell profile (for Current User, All Hosts). I found that here.
Then add an alias. For example, here is my alias of jn for jupyter notebook (I hate typing out the cumbersome jupyter notebook every time):
Set-Alias -Name jn -Value C:\Users\words\Anaconda3\Scripts\jupyter-notebook.exe
Comments
Just to add to this list of possible locations...
This didn't work for me:
\Users\{ME}\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
However this did:
\Users\{ME}\OneDrive\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
If you don't have a profile or you're looking to set one up, run the following command, it will create the folder/files necessary and even tell you where it lives!
New-Item -path $profile -type file -force
2 Comments
C:\Users\{me}\OneDrive\OneDriveDocuments\PowerShell\profile.ps1 path is what worked. (Rant: How pushy of Microsoft to force OneDrive upon us!)To create the profile1.psl file, type in the following command:
New-Item $PROFILE.CurrentUserAllHosts -ItemType file -Force
To access the file, type in the following command:
ise $PROFILE.CurrentUserAllHosts
Note: If you haven't done this before, you will see that you will not be able to run the script because of your execution policy, which you need to change to Unrestricted from Restricted (default).
To do that, close the script and then type this command:
Set-ExecutionPolicy -Scope CurrentUser
Then:
RemoteSigned
Then this command again:
ise $PROFILE.CurrentUserAllHosts
Then finally type your aliases in the script, save it, and they should run every time you run PowerShell, even after restarting your computer.
1 Comment
Set-ExecutionPolicy RemoteSigned. Don't go recommending Unrestricted. Source: itprotoday.com/management-mobility/… This is a little bit fancy... but it works:
Step 1: Create a Powershell Profile:
FILE: install_profile.ps1
# THIS SCRIPT BLOWS AWAY YOUR DEFAULT POWERSHELL PROFILE SCRIPT
# AND INSTALLS A POINTER TO A GLOBAL POWERSHELL PROFILE
$ErrorActionPreference = "Stop"
function print ([string]$msg)
{
Write-Host -ForegroundColor Green $msg
}
print ""
# User's Powershell Profile
$psdir = "$env:USERPROFILE\Documents\WindowsPowerShell"
$psfile = $psdir + "\Microsoft.PowerShell_profile.ps1"
print "Creating Directory: $psdir"
md $psdir -ErrorAction SilentlyContinue | out-null
# this is your auto-generated powershell profile to be installed
$content = @(
"",
". ~/Documents/tools/profile.ps1",
""
)
print "Creating File: $psfile"
[System.IO.File]::WriteAllLines($psfile, $content)
print ""
# Make sure Powershell profile is readable
Set-ExecutionPolicy -Scope CurrentUser Unrestricted
Step 2: then in tools ~/Documents/tools/profile.ps1:
function Do-ActualThing {
# do actual thing
}
Set-Alias MyAlias Do-ActualThing
Step 3:
$ Set-ExecutionPolicy -Scope CurrentUser Unrestricted $ . ./install_profile.ps1
Comments
It's a matter of personal taste, but I prefer to store my aliases together in a separate file and call Import-Alias in the profile.
$profileDir = Split-Path $PROFILE -Parent
$profileFile = Join-Path $profileDir profile.ps1
$aliasFile = Join-Path $profileDir aliases.csv
New-Alias -Name npp -Value "C:\Program Files\Notepad++\notepad++.exe" -Description "Notepad++"
Export-Alias -Name npp -Path $aliasFile -Append
ise $profileFile
Then in the ISE, put this line in your profile.ps1
Import-Alias -Path (Join-Path $PSScriptRoot aliases.csv)
Comments
For the one-liner bros:
echo "Set-Alias bun pnpm" >> $profile && . $profile
This will run pnpm if you type bun. The && . $profile will refresh the current session. It is useful if some frameworks depend on other underlying package managers, like you can also use to make ps1 and shell scripts compatible across OSes,
- also killing and restarting PowerShell => these aliases are guaranteed to persist, tested with a terminal and Visual Studio Code.
If you want to inspect and manually edit (requires Visual Studio Code):
code $profile
code is the CLI way to open Visual Studio Code if you didn't know. Use this for debugging if you mess up pipe append :)
Comments
To get a permanent alias, put it in your personal profile file. (There are other global profiles files, but aliases are personal preferences.) The profile is a script that is run every time you start PowerShell, unless you specify a noprofile flag on the command line. It can be used to set aliases and variables, load functions and libraries, set the start location, and do anything else you might do to make your environment work the way you like it.
The path of the profile is given in the $profile variable. If you have not created a profile, it usually won't exist, but the profile variable will exist. You can edit the profile file from the PS prompt like this
notepad.exe $profile
You will probably get an error because the the path to the file is not there. Use this command to create the full path and the file the first time.
New-Item -path $profile -ItemType File -Force # WARNING: This will overwrite!
Now edit your profile using Notepad as above. After updating and saving your profile, you can dot run it to reload it and test the change without restarting PowerShell.
. $profile
Most things that go in the profile can be done repeatedly, but if a repeat run breaks anything, add a test.
Bonus: One of the things I love in my profile is an alias to my preferred quick text editor so I can avoid notepad. I also generally add one line comment/reminder message when I do stuff in the profile:
'Notepad++ alias:npp'
Set-Alias -Name 'npp' -value 'C:\Program Files\Notepad++\notepad++.exe'
Going one step closer to full OCD, you could add a function in your profile to update your profile and reload it. (I'm not OCD; this is an example.)
'Profile updater, alias pup'
function Update-Profile {
npp $profile
pause
. $profile
}
Set-Alias -Name 'pup' -Value 'Update-Profile'
Comments
Offering simplest solution:
- Open powershell
- Write to profile for all users:
notepad $PsHome\Profile.ps1:
function Goto() {
#function name is alias, set of commands are the body
Set-Location
} 3. Save & exit notepad 4. Set powershell permissions:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned5. Restart powershell & writegoto
Comments
echo "Set-Alias ll dir" >> $profile
. $profile
2 Comments
"C:\Users\adamd\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1" in notepad and changed it from s e t - ... to set-alias -name "unzip" -value "expand-archive".If you have a PowerShell script named cd.ps1
Param(
[Parameter(Mandatory, HelpMessage = "please provide a valid
path")]
[string]
$Path
)
Set-Location $Path
To make it permanent you have to add your alias via a profile.
For Powershell 7.x this worked for me.
from a PowerShell prompt:
Get-Variable profile | Format-List
the output under "Value" will tell you where to either look for your profile 'file' or create a profile 'file'
in my case:
Name : PROFILE
Description :
Value : C:\Users\meUser\Documents\PowerShell\Microsoft.PowerShell_profile.ps1
Visibility : Public
Module :
ModuleName :
Options : None
Attributes : {}
This tells you either where your profile is or where where you need to create one if one doesn't exist. In my case it is under a One Drive but it should tell you where you need to look.
Open or create the path and file Microsoft.PowerShell_profile.ps1
Edit the profile 'file' and add your alias
New-Alias -Name goto -Value c:\myPSscripts\cd.ps1 -Force -Option AllScope
Close and reopen a PowerShell terminal
Give it a spin
goto ../someOtherFolder
echo "Set-Alias bun pnpm" >> $profile && . $profile, full answer somewhere below.