How to reload user profile from script file in PowerShell

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 $_"
            . $_
        }
    }    
}

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

Why are you trying to do this?

Because it is likely to create duplicates (appends to $env:path) and problems with setting constant/readonly objects causing errors.

There was a thread on this topic recently on microsoft.public.windows.powershell.

If you are trying to reset the state of the session there is no way to do this, even using an inner scope ($host.EnterNestedPrompt()) because of the ability to set variables/aliases/... at "all scope".


& $profile   

works to reload the profile.

If your profile sets aliases or executes imports which fail then you will see errors because they were already set in the previous loading of the profile.