How to reload PowerShell after installing poshgit from script?

Issue

I’m having troubles to find a way to get git and poshgit working after installing it through a script using chocolatey without closing the powershell console.

Here is what my script currently looks like.

Function InstallChocolatey {
    iwr https://chocolatey.org/install.ps1 -UseBasicParsing | iex
    refreshenv  #needed to make poshgit install succesfully without restarting Powershell
    Write-Output "Chocolatey installed and configured."
}

Function InstallSoftware {
    choco install git --params='/NoShellIntegration' -y
    choco install poshgit -y
    . $profile   #reload profile
    Write-Output "Software installed and profile reloaded"
}

InstallChocolatey
InstallSoftware

When I close Powershell and restart it everything works as expected. But as my script should later continue executing git stuff I would really like to find a solution to make it work without closing the Console.

From what I found on Stackoverflow and other sites using

. $profile

should reload the Profile. But unfortunately I my case it doesn’t seem to have any effect. I tried to use refreshenv again.

My profile file currently only contains one line

 Import-Module 'C:\tools\poshgit\dahlbyk-posh-git-a4faccd\src\posh-git.psd1'

I also tried adding -force at the end of the line but nothing changed.

I’m pretty new to Powershell, so please bear with me… 🙂

Solution

Thanks to the comments above I was able to get it to work without restarting PowerShell (see script below)!

The key elements needed to make it work are:

Refresh the environment variables after installing Chocolatey and Git/Posh Git

refreshenv 

In Order to make Git work without PS restart temporarily add Git to path

$env:path+='C:\Program Files\Git\cmd' 

and last but not least reload Posh Git Profile (as suggested by @4c74356b41)

. C:\tools\poshgit\dahlbyk-posh-git-a4faccd\profile.example.ps1

The complete script (improvements are welcome!):

    Function InstallChocolatey {
    iwr https://chocolatey.org/install.ps1 -UseBasicParsing | iex
    #choco feature enable -n autoUninstaller
    refreshenv
    Write-Output "Chocolatey installed."
}


Function InstallSoftware {
    choco install git --params='/NoShellIntegration' -y
    $env:path+='C:\Program Files\Git\cmd'
    Write-Output "Git installed"
    choco install poshgit -y
    refreshenv
    Write-Output "Posh Git installed"
}

Function WriteSSHKeys { #Writing SSH keys to the user directory
}

Function SetupSSH {
    . C:\tools\poshgit\dahlbyk-posh-git-a4faccd\profile.example.ps1
}

InstallChocolatey
InstallSoftware
WriteSSHKeys
SetupSSH

Answered By – Pascal Mages

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published