313

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 :

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

Naigel
  • 9,086
  • 16
  • 65
  • 106
AymenDaoudi
  • 7,811
  • 9
  • 52
  • 84
  • 1
    IMO you're much better off putting scripts into the PATH. That way, the command will be available instantly to all your open shells and if you change it, the change will propagate to all subsequent uses without having to reload $profile or something. – masterxilo Nov 20 '18 at 20:39

11 Answers11

254

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" (usually C:\Users\<yourname>\Documents): only your user will execute the code. This is the recommended location You can quickly find your profile location by running echo $profile in 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.ps1 file, 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 $PsHome path 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.0 for the 64bit environment
    • C:\Windows\SysWow64\WindowsPowerShell\v1.0 for the 32bit one (Yeah I know, the folder naming is counterintuitive, but it's correct).
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Naigel
  • 9,086
  • 16
  • 65
  • 106
  • 18
    no error it just did not work, i am not sure if this is a permissions issue. I did actually get it to work ( i should i commented earlier ) . I had to create the folder `\Users\{ME}\Documents\WindowsPowerShell` and then add `Microsoft.PowerShell_profile.ps1` non of the other paths works for me. –  Feb 08 '16 at 16:25
  • 3
    According to linked article using `"$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 information – Naigel Feb 09 '16 at 10:00
  • 5
    Hi @Naigel, I must use this approach to make it work: http://superuser.com/questions/516700/bash-aliases-equivalent-for-powershell so the final solution for me was create the file for profile: `New-Item -path $profile -type file -force` that created the folder and file `Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1` – Eagle Feb 29 '16 at 16:11
  • This doesn't work for me, no matter what I do. This ended up working for me: http://www.vistax64.com/powershell/78513-how-do-you-permanently-add-function-power-shell.html – Niek Aug 20 '16 at 15:52
  • @Naigel for alluser setup I needed to restart the machine, it may be better to update answer. – Mesut GUNES Apr 07 '17 at 11:17
  • 91
    The best way to get the profile location might be to run "echo $profile" in your powershell window. – Rahul Jha Apr 12 '17 at 17:28
  • 4
    Remember to make a backup of your profile.ps1 file, as Windows Creators Update seems to clear the file at its default location!! – gooleem May 08 '17 at 07:38
  • in my case (powershell 6.1.3 win7 64bits), ISE profile is C:\Users\me\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1 and powershell is C:\Users\me\Documents\PowerShell\Microsoft.PowerShell_profile.ps1 – wotter Mar 28 '19 at 13:09
  • additionally, I had to set the execution policy to `RemoteSigned`: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-7 – solstice333 Feb 27 '20 at 01:33
  • If you're using this for PowerShell Core, the `$PSHOME` will be where that tool is installed. – FilBot3 Apr 14 '20 at 19:39
  • 1
    A better scheme to get the correct profile file: 1) Test the path: `Test-Path $Profile` 2) If necessary, create the file: `New-Item -Path $Profile -Type File -Force` 3) Edit the file: `notepad $Profile` – Uri London Oct 25 '21 at 17:20
  • In short: `"New-Alias NAME COMMAND" >> $PROFILE`. – theberzi May 07 '22 at 13:19
  • This answer was very helpfull. My way of getting an bash-like alias: (1) `notepad $PsHome\Profile.ps1` (2) inside notepad add `function my_alias_for_pws_foo(){ Set-Location }` (3) press enter & write `Set-Alias go my_alias_for_pws_foo` (4) save notepad, exit, exit & restart powershell (4) `Set-ExecutionPolicy -ExecutionPolicy RemoteSigned` if you did not already – mggluscevic Dec 17 '22 at 10:51
  • using `Set-Alias` might be faster. – NanoNova Mar 07 '23 at 06:25
187

It'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 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
Chase Florell
  • 46,378
  • 57
  • 186
  • 376
  • 1
    Great comment. Very clear, although my powershell doesn't have touch. – JustinB Apr 21 '17 at 16:53
  • @JustinB try `new-item` – Chase Florell Apr 21 '17 at 21:14
  • 14
    In order to allow the execution of my profile script, I had to do one extra step. Run Powershell as an Administrator, and execute `Set-ExecutionPolicy RemoteSigned -Scope CurrentUser`. The `-Scope` option makes it a bit more secure. – zombat Oct 25 '17 at 18:10
  • 4
    This is a great method! Please not that the function itself also becomes available in the shell, so you don't really need the Set-Alias part. Just call the function `MyAlias`. Also, to pass on arguments, use `@Args`, eg `function gs { git status @Args }` – Automatico Feb 22 '19 at 12:28
  • 3
    @Automatico I like being explicit about the `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. – Chase Florell Feb 22 '19 at 20:21
  • 1
    @zombat This is exactly I was struggling with, for hours. Thank you, I am done now. – jawad mansoor Feb 03 '20 at 09:11
  • 1
    Very clear, should be the accepted answer thank you! – Maxime Lafarie Sep 08 '20 at 08:33
  • 1
    **UPDATE 2022**: I had to use `$env:USERPROFILE\Documents\PowerShell` as folder for the profile file. (I'm using powershell V 7.2.2) – BenHero Mar 25 '22 at 12:17
  • 1
    Thanks. Of course we cannot change Microsoft program settings without disabling security. Feels like home – chill appreciator Oct 26 '22 at 10:10
67

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!

Dave
  • 2,774
  • 4
  • 36
  • 52
Sterling Bourne
  • 3,064
  • 23
  • 22
  • 1
    $profile doesn't seem to be a default environment variable in windows 10. What is it supposed to be pointing to? – wordsforthewise Sep 23 '19 at 20:47
  • @wordsforthewise - The $PROFILE automatic variable stores the paths to the PowerShell profiles that are available in the current session. It is included in Windows PowerShell. – Sterling Bourne Jan 30 '20 at 19:09
  • 3
    This was bar none the simplest solution provided. – Phill Mar 03 '20 at 01:09
  • 1
    I had to enable 'Enable PowerShell Scripts' (in another answer) to get this to work. Seriously super simple! – RockyK Jun 24 '20 at 18:09
  • 1
    Great solution, worth noting that the file under $profile may not exist yet. Can be manually created though. – yooloobooy Sep 14 '20 at 12:31
  • I got `Microsoft.PowerShell_profile.ps1 cannot be loaded. The file C:\Users\me\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 is not digitally signed.` - meh, Microsoft's classic. Will use Mingw I guess) – chill appreciator Oct 26 '22 at 10:07
44

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.

enter image description here

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.

enter image description here

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.

Enabling PowerShell scripts

Ben Carp
  • 24,214
  • 9
  • 60
  • 72
12

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

golden_grahams
  • 199
  • 2
  • 7
12

I 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
wordsforthewise
  • 13,746
  • 5
  • 87
  • 117
7

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 next 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.

Leon Bambrick
  • 26,009
  • 9
  • 51
  • 75
  • 3
    You probably want: `Set-ExecutionPolicy RemoteSigned`. Don't go recommending `Unrestricted`. Source: http://www.itprotoday.com/management-mobility/running-powershell-scripts-easy-1-2-3 – PhilT Nov 12 '17 at 18:55
4

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

Bimo
  • 5,987
  • 2
  • 39
  • 61
1

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)
Paul Williams
  • 3,099
  • 38
  • 34
0

Offering simplest solution:

  1. Open powershell
  2. 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 RemoteSigned 5. Restart powershell & write goto

mggluscevic
  • 431
  • 5
  • 8
-1
echo "Set-Alias ll dir" >> $profile
. $profile

enter image description here

Leo
  • 142
  • 1
  • 3
  • 11
  • Borked my $profile, had to open `"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"`. – Adam D. Jun 09 '23 at 17:00
  • Strange I tested in both Powershell 5 and 7 without problem. Perhaps your format will be more standard. – Leo Jun 16 '23 at 04:01