Refreshing/Restarting PowerShell session w/out exiting

Viewed 57077

I have been tweaking some of the scripts in my PowerShell profile and it has got annoying to exit powershell then restart it so it will load any changes I have made to the scripts in my profile. Is it possible to restart the powershell session without exiting?

6 Answers

This will start a new session, reloading your profile, in the same console window:

Invoke-Command { & "powershell.exe" } -NoNewScope # PowerShell 5
Invoke-Command { & "pwsh.exe"       } -NoNewScope # PowerShell 7

Or a longer but more robust command, the following should work correctly across versions:

Get-Process -Id $PID | Select-Object -ExpandProperty Path | ForEach-Object { Invoke-Command { & "$_" } -NoNewScope }

You will, of course, lose all your variables etc. from the previous session.

Note: creating new sessions in the same window like this will leave the parent process running in the background. Generally, this is not a problem as the parent (and any other ancestors) will terminate when the window is closed. If this is a concern, however, you may want to add something like the following to your profile:

$p = Get-Process -Id $PID
If ($p.Parent.Name -eq $p.Name -and !($p.MainWindowTitle))
{
    Stop-Process -Id $p.Parent.Id -Force
}

Here is an expansion upon @Bad's answer. This will now handle ISE (because I use it all the time).

The idea is if you are in ISE, it will restart ISE. If you are in plain PowerShell, it will restart plain PowerShell. Get-PSHostProcessInfo returns information about the current PowerShell session which allows you to determine whether or not you are running ISE or not.

function Restart-PowerShell
{
    if((Get-PSHostProcessInfo).ProcessName.Contains('powershell_ise'))
    {
        Start-Process 'powershell_ise.exe'
    } else {
        Start-Process 'powershell.exe'
    }
    exit
}
Related