Git prompt for Windows PowerShell
The script I use for a Git prompt in PowerShell shows a summary of the git status --porcelain command.
The prompt shows the branch and summary of the file status.
The PowerShell profile script I use can be found at PowerShell Profile.
$Global:CurrentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$UserType = "User"
$CurrentUser.Groups | foreach {
if ($_.value -eq "S-1-5-32-544")
{
$UserType = "Admin"
}
}
function prompt
{
if($UserType -eq "Admin")
{
$host.UI.RawUI.WindowTitle = "" + $(get-location) + " : Admin"
$host.UI.RawUI.ForegroundColor = "white"
}
else
{
$host.ui.rawui.WindowTitle = $(get-location)
}
Write-Host("")
$statusString = ""
$symbolicref = git symbolic-ref HEAD
if($symbolicref -ne $NULL)
{
$statusString += "GIT [" + $symbolicref.substring($symbolicref.LastIndexOf("/") +1) + "] "
$status = git status --porcelain
if ( $status )
{
$matches = [regex]::matches([system.string]::join("`n", $status), "(?m)^.{2}")
$statusTotals = @{}
foreach ( $match in $matches )
{
if ( ![string]::IsNullOrEmpty($match.Value) )
{
$matchValue = $match.Value.Replace(" ", "-")
if ( !$statusTotals.ContainsKey($matchValue) )
{
$statusTotals.Add($matchValue, 1)
}
else
{
$statusTotals.Set_Item($matchValue, $statusTotals.Get_Item($matchValue) + 1)
}
}
}
foreach ( $dictEntry in $statusTotals.GetEnumerator() | Sort-Object Name)
{
$statusString += $outVal = [string]::format("{0}:{1} ", $dictEntry.Name, $dictEntry.Value)
}
}
else
{
$statusString += "nothing to commit (working dir clean)"
}
}
else
{
$statusString = "PS "
}
if ($statusString.StartsWith("GIT")) {
Write-Host ($statusString + [System.Environment]::NewLine + $(get-location) + ">") -nonewline -foregroundcolor yellow
}
else {
Write-Host ($statusString + $(get-location) + ">") -nonewline -foregroundcolor green
}
return " "
}
The file needs to be placed in the ~\Documents\WindowsPowerShell folder (on Windows 10).
The linked profile script also contains a number of Git shortcuts. For example:
gfo will execute git fetch origin.
gmff origin/master will execute git merge --ff-only origin/master.
You can see all the shortcuts in the profile script.