Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reload user profile from script file in PowerShell

I want to reload my user profile from a script file. I thought that dot sourcing it from within the script file would do the trick, but it doesn't work:

# file.ps1 . $PROFILE

However, it does work if I dot source it from PowerShell's interpreter.

Why do I want to do this?

I run this script every time I update my profile and want to test it, so I'd like to avoid having to restart PowerShell to refresh the environment.

like image 355
guillermooo Avatar asked Feb 19 '09 23:02

guillermooo


People also ask

What is profile script in PowerShell?

A PowerShell profile is a script that runs when PowerShell starts. You can use the profile as a logon script to customize the environment. You can add commands, aliases, functions, variables, snap-ins, modules, and PowerShell drives.


2 Answers

If you want to globally refresh your profile from a script, you will have to run that script "dot-sourced".

When you run your script, all the profile script runs in a "script" scope and will not modify your "global" scope.

In order for a script to modify your global scope, it needs to be "dot-source" or preceded with a period.

. ./yourrestartscript.ps1 

where you have your profile script "dot-sourced" inside of "yourrestartscript.ps1". What you are actually doing is telling "yourrestartscript" to run in the current scope and inside that script, you are telling the $profile script to run in the script's scope. Since the script's scope is the global scope, any variables set or commands in your profile will happen in the global scope.

That doesn't buy you much advantage over running

. $profile 
like image 106
Steven Murawski Avatar answered Sep 20 '22 13:09

Steven Murawski


So, the approach that you marked as the answer may work inside the Powershell command prompt, but it doesn't work inside PowerShell ISE (which, to me, provides a superior PowerShell session) and probably won't work right in other PowerShell environments.

Here's a script that I have been using for a while, and it has worked very well for me in every environment. I simply put this function into my Profile.ps1 at ~\Documents\WindowsPowerShell, and whenever I want to reload my profile, I dot-source the function, i.e.

. Reload-Profile 

Here's the function:

function Reload-Profile {     @(         $Profile.AllUsersAllHosts,         $Profile.AllUsersCurrentHost,         $Profile.CurrentUserAllHosts,         $Profile.CurrentUserCurrentHost     ) | % {         if(Test-Path $_){             Write-Verbose "Running $_"             . $_         }     }     } 
like image 45
Winston Fassett Avatar answered Sep 16 '22 13:09

Winston Fassett