Setting Up Git and SSH in PowerShell with posh-git
I like to use Git with SSH in PowerShell. However, I set this stack up so infrequently that when I do set it up I invariably miss some detail that makes the process harder than I would like. To help future me here’s how I installed and configured Git and SSH in PowerShell with posh-git.
We’re going to use Chocolately to install Git and friends, but first we need to install Chocolatey itself. From an Administrative PowerShell prompt run the following commands.
iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
Install Git, Posh-Git, and Putty
With Chocolatey installed we can easily install Git, posh-git, and Putty. From the same Adminstrative PowerShell prompt run the following commands.
choco install -y git -params '"/GitAndUnixToolsOnPath"'
choco install -y poshgit
choco install -y putty
Create SSH Keys
First we need a place to save our public and private keys. Using PowerShell
run the following to create the
~\.ssh directory in the proper location.
Now launch PuTTYgen from PowerShell.
Then in PuTTYgen.
Generateto create the public key
- Fill in
Key commentwith an identifier, such as an email address
- Enter a passphrase in
Save private keyand save it as
Save public keyand save it as
Conversions > Export OpenSSHand save it as
- Replace the contents of
~\.ssh\github_pubwith the public key shown in PuTTYgen
Next create an
~\.ssh\config file containg the following.
Add Private Key To SSH-Agent
To avoid entering our password each time we
now modify our PowerShell profile to start ssh-agent and add our private key to
In PowerShell execute the following to open your profile in Visual Studio Code.
Locate the line where the posh-git module is loaded. It should look something like this.
Below the import add the commands to start the ssh-agent and to add your key.
Add-SshKey (Resolve-Path ~\.ssh\github_rsa)
Save your modifications.
Now when you open a PowerShell Prompt you will be prompted to enter the password for your private ssh key and will not be required to repeatedly enter it while working with Git.
Customize Posh-Git PowerShell Prompt
The last (optional) step is to customize your prompt to make it easier to read and a bit more informative. Fortunately, posh-git provides options to customize the prompt. Simply add the following to your PowerShell profile and restart PowerShell.
# change the prompt foreground color
$GitPromptSettings.DefaultForegroundColor = "DarkCyan"
# make the prompt span two lines and change the prompt character to `$`
$GitPromptSettings.DefaultPromptSuffix = '`n$(''$'' * ($nestedPromptLevel + 1)) '
# prefix the prompt with "username@hostname"
$GitPromptSettings.DefaultPromptPrefix = '$env:USERNAME@$(hostname) '
When the PowerShell working directory is also a Git repo this will cause the prompt to look similar to this.
username@hostname C:\dev\git-repo [master ≡ +1 ~1 -0 !]