### Install posh-git via PowerShellGet Source: https://context7.com/dahlbyk/posh-git/llms.txt Installs or updates the module from the PowerShell Gallery for the current user. ```powershell # Install posh-git for the first time PowerShellGet\Install-Module posh-git -Scope CurrentUser -Force # Or update an existing installation PowerShellGet\Update-Module posh-git ``` -------------------------------- ### Install posh-git via Scoop Source: https://github.com/dahlbyk/posh-git/blob/master/README.md Installs posh-git and adds it to the profile using the Scoop package manager. ```powershell scoop bucket add extras scoop install posh-git Add-PoshGitToProfile ``` -------------------------------- ### Install or Update posh-git via PowerShellGet Source: https://github.com/dahlbyk/posh-git/blob/master/README.md Use these commands to install or update the module from the PowerShell Gallery. Requires an elevated PowerShell prompt. ```powershell # (A) You've never installed posh-git from the PowerShell Gallery PowerShellGet\Install-Module posh-git -Scope CurrentUser -Force ``` ```powershell # (B) You've already installed a previous version of posh-git from the PowerShell Gallery PowerShellGet\Update-Module posh-git ``` -------------------------------- ### Install posh-git via Chocolatey Source: https://github.com/dahlbyk/posh-git/blob/master/README.md Installs the posh-git package using the Chocolatey package manager. ```powershell choco install poshgit ``` -------------------------------- ### Example Prompt Output Source: https://github.com/dahlbyk/posh-git/wiki/Customizing-Your-PowerShell-Prompt The visual output resulting from the basic custom prompt function. ```text C:\Users > ``` -------------------------------- ### Git Tab Completion Example Source: https://github.com/dahlbyk/posh-git/blob/master/src/en-US/about_posh-git.help.txt Demonstrates tab completion for Git subcommands and branch names in PowerShell. Pressing tab cycles through available options. ```powershell C:\GitHub\posh-git> git ch ``` ```powershell C:\GitHub\posh-git> git fetch origin master ``` ```powershell C:\GitHub\posh-git> git fe or ma ``` -------------------------------- ### Utilize Git Tab Completion Source: https://context7.com/dahlbyk/posh-git/llms.txt Examples of using tab completion for Git commands, branches, remotes, files, and parameters. ```powershell # Command completion git ch # checkout, cherry, cherry-pick git sta # stash, status # Branch completion git checkout ma # main, master git merge feature/ # lists feature branches git push origin # lists branches # Remote completion git pull # lists remotes git fetch # lists remotes # File completion git add # lists modified/untracked files git checkout -- # lists modified files git diff # lists modified files # Parameter completion git commit -- # lists commit parameters git log -- # lists log parameters # Stash completion git stash apply # lists stashes git stash drop # lists stashes # Git flow completion (if installed) git flow feature # lists flow commands git flow feature finish # lists feature branches ``` -------------------------------- ### Advanced Prompt Customization Example Source: https://github.com/dahlbyk/posh-git/wiki/Customizing-Your-PowerShell-Prompt Combine multiple settings to create a highly customized prompt, including status first, a two-line prompt with timestamp, and a custom suffix displaying the PowerShell history ID. ```powershell $GitPromptSettings.DefaultPromptWriteStatusFirst = $true $GitPromptSettings.DefaultPromptBeforeSuffix.Text = '`n$([DateTime]::now.ToString("MM-dd HH:mm:ss"))' $GitPromptSettings.DefaultPromptBeforeSuffix.ForegroundColor = 0x808080 $GitPromptSettings.DefaultPromptSuffix = ' $((Get-History -Count 1).id + 1)$(">" * ($nestedPromptLevel + 1)) ' ``` -------------------------------- ### Locate posh-git module path Source: https://github.com/dahlbyk/posh-git/wiki/Home Displays the file system path where the posh-git module is currently installed. ```ps1 $env:userprofile\AppData\Local\GitHub\PoshGit_869d4c5159797755bc04749db47b166136e59132\posh-git.psm1 ``` ```ps1 (Get-Module -Name posh-git).Path ``` -------------------------------- ### Integrated posh-git Prompt Function Source: https://github.com/dahlbyk/posh-git/wiki/Customizing-Your-PowerShell-Prompt A complete prompt function example that integrates path, git status, and debug information while preserving the last exit code. ```powershell function prompt { $origLastExitCode = $LASTEXITCODE $prompt = "" $prompt += Write-Prompt "$($ExecutionContext.SessionState.Path.CurrentLocation)" -ForegroundColor Cyan $prompt += Write-VcsStatus $prompt += Write-Prompt "$(if ($PsDebugContext) {' [DBG]: '} else {''})" -ForegroundColor Magenta $prompt += "$('>' * ($nestedPromptLevel + 1)) " $LASTEXITCODE = $origLastExitCode $prompt } ``` -------------------------------- ### Get-PromptPath Source: https://context7.com/dahlbyk/posh-git/llms.txt Gets the formatted current path for display in the prompt, with optional home directory abbreviation and git directory abbreviation. ```APIDOC ## Get-PromptPath ### Description Gets the formatted current path for display in the prompt, with optional home directory abbreviation and git directory abbreviation. ### Method Cmdlet ### Endpoint N/A (PowerShell Cmdlet) ### Parameters #### Global Variables - **$GitPromptSettings.DefaultPromptAbbreviateHomeDirectory** (bool) - If true, abbreviates the home directory path with '~'. ### Request Example ```powershell # Get prompt path with default settings $path = Get-PromptPath # Output: "C:\Users\user\Projects\my-repo" # Enable home directory abbreviation $GitPromptSettings.DefaultPromptAbbreviateHomeDirectory = $true $path = Get-PromptPath # Output: "~\Projects\my-repo" ``` ### Response - **string** - The formatted path string. ``` -------------------------------- ### Customizing Prompt with posh-git Integration Source: https://github.com/dahlbyk/posh-git/wiki/Customizing-Your-PowerShell-Prompt Example of wrapping the posh-git prompt script block within a custom prompt function in a profile script. ```powershell function prompt { # Your non-prompt logic here $prompt = Write-Prompt "Text before posh-git prompt " -ForegroundColor Green $prompt += & $GitPromptScriptBlock $prompt += Write-Prompt "Text after posh-git prompt " -ForegroundColor Magenta if ($prompt) {$prompt} else {" "} } ``` -------------------------------- ### Get Formatted Prompt Path Source: https://context7.com/dahlbyk/posh-git/llms.txt Gets the current directory path formatted for display in the prompt. It supports optional abbreviation of the home directory and Git repository directory. ```powershell # Get prompt path with default settings $path = Get-PromptPath # Output: "C:\Users\user\Projects\my-repo" ``` ```powershell # Enable home directory abbreviation $GitPromptSettings.DefaultPromptAbbreviateHomeDirectory = $true $path = Get-PromptPath # Output: "~\Projects\my-repo" ``` -------------------------------- ### Get-PromptConnectionInfo Source: https://context7.com/dahlbyk/posh-git/llms.txt Gets SSH connection information (username and hostname) for display in the prompt when connected via SSH. ```APIDOC ## Get-PromptConnectionInfo ### Description Gets SSH connection information (username and hostname) for display in the prompt when connected via SSH. ### Method GET ### Endpoint /prompt/connection ### Parameters #### Query Parameters - **Format** (string) - Optional - Custom format string for the output. ### Request Example ```powershell # Get connection info with default format $connInfo = Get-PromptConnectionInfo # Output: "[user@hostname]: " when connected via SSH, empty otherwise # Custom format $connInfo = Get-PromptConnectionInfo -Format "{1} on {0} > " # Output: "user on hostname > " # Use in prompt function prompt { $connInfo = Get-PromptConnectionInfo return "${connInfo}PS $(Get-Location)> " } ``` ### Response #### Success Response (200) - **connInfo** (string) - SSH connection information or empty string. #### Response Example ```json { "connInfo": "[user@hostname]: " } ``` ``` -------------------------------- ### Get SSH Connection Info - Get-PromptConnectionInfo Source: https://context7.com/dahlbyk/posh-git/llms.txt Retrieves SSH connection information (username and hostname) for display in the prompt. Use the -Format parameter for custom output. ```powershell # Get connection info with default format $connInfo = Get-PromptConnectionInfo # Output: "[user@hostname]: " when connected via SSH, empty otherwise ``` ```powershell # Custom format $connInfo = Get-PromptConnectionInfo -Format "{1} on {0} > " # Output: "user on hostname > " ``` ```powershell # Use in prompt function prompt { $connInfo = Get-PromptConnectionInfo return "${connInfo}PS $(Get-Location)> " } ``` -------------------------------- ### Get Git Status and Write Status Source: https://context7.com/dahlbyk/posh-git/llms.txt Retrieves the Git status of the repository and writes it to the console. This is often used within a custom prompt function. ```powershell $status = Get-GitStatus Write-GitStatus $status # Output: [main ≡ +1 ~2 -0 | +0 ~3 -1 !] ``` ```powershell # Use in a custom prompt function function prompt { $status = Get-GitStatus Write-Host "PS $(Get-Location)" -NoNewline Write-GitStatus $status return "> " } ``` -------------------------------- ### Prompt Function Without Trailing Space Source: https://github.com/dahlbyk/posh-git/wiki/Customizing-Your-PowerShell-Prompt An example of a prompt function that fails to return a trailing space, causing PowerShell to append 'PS>'. ```powershell function prompt { Write-Host $ExecutionContext.SessionState.Path.CurrentLocation -ForegroundColor Cyan Write-Host "$('>' * ($nestedPromptLevel + 1)) " -NoNewline } ``` -------------------------------- ### New-GitPromptSettings Source: https://context7.com/dahlbyk/posh-git/llms.txt Creates a new instance of PoshGitPromptSettings with default values. Useful for resetting settings to defaults. ```APIDOC ## New-GitPromptSettings ### Description Creates a new instance of PoshGitPromptSettings with default values. Useful for resetting settings to defaults. ### Method POST ### Endpoint /settings/prompt/new ### Request Example ```powershell # Reset all prompt settings to defaults $GitPromptSettings = New-GitPromptSettings # Create a new settings object for comparison $defaultSettings = New-GitPromptSettings ``` ### Response #### Success Response (200) - **settings** (object) - A new PoshGitPromptSettings object with default values. #### Response Example ```json { "settings": { "DefaultPromptAbbreviateGitDirectory": false, "DefaultPromptPath": { "ForegroundColor": null }, "DefaultPromptAbbreviateHomeDirectory": false, "DefaultPromptWriteStatusFirst": false, "DefaultPromptBeforeSuffix": { "Text": null }, "DefaultPromptSuffix": null, "EnableStashStatus": false, "EnableFileStatus": true, "RepositoriesInWhichToDisableFileStatus": [], "BranchBehindAndAheadDisplay": "Full", "BranchNameLimit": null, "TruncatedBranchSuffix": null, "DefaultPromptEnableTiming": false, "BeforeStatus": { "ForegroundColor": null }, "AfterStatus": { "ForegroundColor": null }, "FileAddedText": "+", "FileModifiedText": "*", "FileRemovedText": "-", "FileConflictedText": "!" } } ``` ``` -------------------------------- ### Create New Git Prompt Settings - New-GitPromptSettings Source: https://context7.com/dahlbyk/posh-git/llms.txt Creates a new instance of PoshGitPromptSettings with default values. Useful for resetting settings. ```powershell # Reset all prompt settings to defaults $GitPromptSettings = New-GitPromptSettings ``` ```powershell # Create a new settings object for comparison $defaultSettings = New-GitPromptSettings ``` -------------------------------- ### Add-PoshGitToProfile Source: https://context7.com/dahlbyk/posh-git/llms.txt Configures the PowerShell profile to load the module automatically on startup. ```powershell # Add posh-git to current host profile (e.g., just PowerShell console) Add-PoshGitToProfile # Add posh-git to all PowerShell hosts (console, ISE, VS Code, etc.) Add-PoshGitToProfile -AllHosts # Add posh-git for all users on the system (requires admin/sudo) Add-PoshGitToProfile -AllUsers -AllHosts # Force add even if posh-git appears to already be imported Add-PoshGitToProfile -Force ``` -------------------------------- ### View prompt layout reference Source: https://github.com/dahlbyk/posh-git/blob/master/README.md Displays the structural components of the prompt for both default and status-first configurations. ```text {DPPrefix}{BeforePath}{DPPath}{AfterPath}{PathStatusSeparator}<{BeforeStatus}{Status}{AfterStatus}>{DPBeforeSuffix}<{DPDebug}><{DPTimingFormat}>{DPSuffix} ``` ```text {DPPrefix}<{BeforeStatus}{Status}{AfterStatus}>{PathStatusSeparator}{BeforePath}{DPPath}{AfterPath}{DPBeforeSuffix}<{DPDebug}><{DPTimingFormat}>{DPSuffix} ``` -------------------------------- ### Get-GitBranchStatusColor Source: https://context7.com/dahlbyk/posh-git/llms.txt Gets the appropriate color for the branch status based on ahead/behind state relative to the remote. ```APIDOC ## Get-GitBranchStatusColor ### Description Gets the appropriate color for the branch status based on ahead/behind state relative to the remote. ### Method Cmdlet ### Endpoint N/A (PowerShell Cmdlet) ### Parameters #### Parameters - **InputObject** (Object) - The Git status object. ### Request Example ```powershell # Get branch status color $status = Get-GitStatus $colorSpan = Get-GitBranchStatusColor $status # Returns PoshGitTextSpan with colors: # - Cyan: branch is in sync with remote # - Green: branch is ahead of remote # - Red: branch is behind remote # - Yellow: branch is both ahead and behind ``` ### Response - **PoshGitTextSpan** - An object containing the color information for the branch status. ``` -------------------------------- ### $GitPromptSettings Configuration Source: https://context7.com/dahlbyk/posh-git/llms.txt The global $GitPromptSettings object controls all aspects of the posh-git prompt appearance and behavior. ```APIDOC ## $GitPromptSettings Configuration ### Description The global `$GitPromptSettings` object controls all aspects of the posh-git prompt appearance and behavior. ### Method GET/PUT ### Endpoint /settings/prompt ### Parameters #### Request Body (for PUT operations) - **DefaultPromptAbbreviateGitDirectory** (boolean) - Enable git directory abbreviation. - **DefaultPromptPath.ForegroundColor** (string) - Sets the foreground color for the path. - **DefaultPromptAbbreviateHomeDirectory** (boolean) - Abbreviate home directory with `~`. - **DefaultPromptWriteStatusFirst** (boolean) - Show Git status before path. - **DefaultPromptBeforeSuffix.Text** (string) - Text to display before the prompt suffix. - **DefaultPromptSuffix** (string) - The prompt suffix string. - **EnableStashStatus** (boolean) - Enable stash count in prompt. - **EnableFileStatus** (boolean) - Disable file status for performance. - **RepositoriesInWhichToDisableFileStatus** (array of strings) - List of repositories where file status is disabled. - **BranchBehindAndAheadDisplay** (string) - Controls how behind/ahead status is displayed (Full, Compact, Minimal). - **BranchNameLimit** (integer) - Maximum length for branch names. - **TruncatedBranchSuffix** (string) - Suffix for truncated branch names. - **DefaultPromptEnableTiming** (boolean) - Enable prompt timing display. - **BeforeStatus.ForegroundColor** (string) - Foreground color for text before Git status. - **AfterStatus.ForegroundColor** (string) - Foreground color for text after Git status. - **FileAddedText** (string) - Text displayed for added files. - **FileModifiedText** (string) - Text displayed for modified files. - **FileRemovedText** (string) - Text displayed for removed files. - **FileConflictedText** (string) - Text displayed for conflicted files. ### Request Example ```powershell # View all current settings $GitPromptSettings # Customize prompt prefix with timestamp $GitPromptSettings.DefaultPromptPrefix.Text = '$(Get-Date -f "HH:mm:ss") ' $GitPromptSettings.DefaultPromptPrefix.ForegroundColor = [ConsoleColor]::Magenta # Change path color to orange (Windows only) $GitPromptSettings.DefaultPromptPath.ForegroundColor = 'Orange' # Use RGB color on all platforms $GitPromptSettings.DefaultPromptPath.ForegroundColor = 0xFFA500 # Abbreviate home directory with ~ $GitPromptSettings.DefaultPromptAbbreviateHomeDirectory = $true # Show Git status before path instead of after $GitPromptSettings.DefaultPromptWriteStatusFirst = $true # Add newline before prompt suffix (two-line prompt) $GitPromptSettings.DefaultPromptBeforeSuffix.Text = '`n' # Customize prompt suffix with history number $GitPromptSettings.DefaultPromptSuffix = ' $((Get-History -Count 1).id + 1)> ' # Enable stash count in prompt $GitPromptSettings.EnableStashStatus = $true # Disable file status for performance on large repos $GitPromptSettings.EnableFileStatus = $false # Disable file status for specific large repos $GitPromptSettings.RepositoriesInWhichToDisableFileStatus = @( 'C:\Projects\huge-repo', 'C:\Projects\another-large-repo' ) # Change branch status display mode $GitPromptSettings.BranchBehindAndAheadDisplay = 'Compact' # Full, Compact, or Minimal # Truncate long branch names $GitPromptSettings.BranchNameLimit = 25 $GitPromptSettings.TruncatedBranchSuffix = '...' # Enable prompt timing $GitPromptSettings.DefaultPromptEnableTiming = $true # Customize status bracket colors $GitPromptSettings.BeforeStatus.ForegroundColor = [ConsoleColor]::Blue $GitPromptSettings.AfterStatus.ForegroundColor = [ConsoleColor]::Blue # Customize file status symbols $GitPromptSettings.FileAddedText = '[+]' $GitPromptSettings.FileModifiedText = '[M]' $GitPromptSettings.FileRemovedText = '[-]' $GitPromptSettings.FileConflictedText = '[!]' ``` ### Response #### Success Response (200) - **$GitPromptSettings** (object) - The current Git prompt settings. #### Response Example ```json { "DefaultPromptAbbreviateGitDirectory": true, "DefaultPromptPath": { "ForegroundColor": "Orange" }, "DefaultPromptAbbreviateHomeDirectory": true, "DefaultPromptWriteStatusFirst": true, "DefaultPromptBeforeSuffix": { "Text": "`n" }, "DefaultPromptSuffix": " $((Get-History -Count 1).id + 1)> ", "EnableStashStatus": true, "EnableFileStatus": false, "RepositoriesInWhichToDisableFileStatus": [ "C:\Projects\huge-repo", "C:\Projects\another-large-repo" ], "BranchBehindAndAheadDisplay": "Compact", "BranchNameLimit": 25, "TruncatedBranchSuffix": "...", "DefaultPromptEnableTiming": true, "BeforeStatus": { "ForegroundColor": "Blue" }, "AfterStatus": { "ForegroundColor": "Blue" }, "FileAddedText": "[+]", "FileModifiedText": "[M]", "FileRemovedText": "[-]", "FileConflictedText": "[!]" } ``` ``` -------------------------------- ### Configure Posh-Git Prompt - $GitPromptSettings Source: https://context7.com/dahlbyk/posh-git/llms.txt The global $GitPromptSettings object controls the appearance and behavior of the posh-git prompt. Customize various aspects like prefixes, colors, and status displays. ```powershell # View all current settings $GitPromptSettings ``` ```powershell # Customize prompt prefix with timestamp $GitPromptSettings.DefaultPromptPrefix.Text = '$(Get-Date -f "HH:mm:ss") ' $GitPromptSettings.DefaultPromptPrefix.ForegroundColor = [ConsoleColor]::Magenta ``` ```powershell # Change path color to orange (Windows only) $GitPromptSettings.DefaultPromptPath.ForegroundColor = 'Orange' ``` ```powershell # Use RGB color on all platforms $GitPromptSettings.DefaultPromptPath.ForegroundColor = 0xFFA500 ``` ```powershell # Abbreviate home directory with ~ $GitPromptSettings.DefaultPromptAbbreviateHomeDirectory = $true ``` ```powershell # Show Git status before path instead of after $GitPromptSettings.DefaultPromptWriteStatusFirst = $true ``` ```powershell # Add newline before prompt suffix (two-line prompt) $GitPromptSettings.DefaultPromptBeforeSuffix.Text = '`n' ``` ```powershell # Customize prompt suffix with history number $GitPromptSettings.DefaultPromptSuffix = ' $((Get-History -Count 1).id + 1)> ' ``` ```powershell # Enable stash count in prompt $GitPromptSettings.EnableStashStatus = $true ``` ```powershell # Disable file status for performance on large repos $GitPromptSettings.EnableFileStatus = $false ``` ```powershell # Disable file status for specific large repos $GitPromptSettings.RepositoriesInWhichToDisableFileStatus = @( 'C:\Projects\huge-repo', 'C:\Projects\another-large-repo' ) ``` ```powershell # Change branch status display mode $GitPromptSettings.BranchBehindAndAheadDisplay = 'Compact' # Full, Compact, or Minimal ``` ```powershell # Truncate long branch names $GitPromptSettings.BranchNameLimit = 25 $GitPromptSettings.TruncatedBranchSuffix = '...' ``` ```powershell # Enable prompt timing $GitPromptSettings.DefaultPromptEnableTiming = $true ``` ```powershell # Customize status bracket colors $GitPromptSettings.BeforeStatus.ForegroundColor = [ConsoleColor]::Blue $GitPromptSettings.AfterStatus.ForegroundColor = [ConsoleColor]::Blue ``` ```powershell # Customize file status symbols $GitPromptSettings.FileAddedText = '[+]' $GitPromptSettings.FileModifiedText = '[M]' $GitPromptSettings.FileRemovedText = '[-]' $GitPromptSettings.FileConflictedText = '[!]' ``` -------------------------------- ### Retrieve posh-git system details Source: https://github.com/dahlbyk/posh-git/blob/master/ISSUE_TEMPLATE.md Execute this command in PowerShell to generate a formatted string of environment details for troubleshooting. ```PowerShell "- posh-git version/path: $($m = Get-Module posh-git; '{0} {1} {2}' -f $m.Version,$m.PrivateData.PSData.Prerelease,$m.ModuleBase.Replace($HOME,'~'))`n- PowerShell version: $($PSVersionTable.PSVersion)`n- $(git --version)`n- OS: $([System.Environment]::OSVersion)" ``` -------------------------------- ### Configure Git Prompt Settings Source: https://context7.com/dahlbyk/posh-git/llms.txt Customize path delimiters, console output, and window title formatting for the Git prompt. ```powershell $GitPromptSettings.BeforePath = '{' $GitPromptSettings.AfterPath = '}' $GitPromptSettings.BeforePath.ForegroundColor = 'Red' $GitPromptSettings.AfterPath.ForegroundColor = 'Red' # Disable ANSI console (use Write-Host instead) $GitPromptSettings.AnsiConsole = $false # Custom window title $GitPromptSettings.WindowTitle = { param($GitStatus, [bool]$IsAdmin) $prefix = if ($IsAdmin) { "Admin: " } else { "" } if ($GitStatus) { "$prefix$($GitStatus.RepoName) [$($GitStatus.Branch)]" } else { "${prefix}PowerShell" } } ``` -------------------------------- ### Defining a Basic Custom Prompt Function Source: https://github.com/dahlbyk/posh-git/wiki/Customizing-Your-PowerShell-Prompt A simple prompt function using Write-Host to display the current path in Cyan. ```powershell function prompt { Write-Host $ExecutionContext.SessionState.Path.CurrentLocation -ForegroundColor Cyan "$('>' * ($nestedPromptLevel + 1)) " } ``` -------------------------------- ### Get Git Branch Status Color Source: https://context7.com/dahlbyk/posh-git/llms.txt Retrieves the appropriate color for the Git branch status based on its ahead/behind state relative to the remote. Returns a `PoshGitTextSpan` object with color information. ```powershell # Get branch status color $status = Get-GitStatus $colorSpan = Get-GitBranchStatusColor $status # Returns PoshGitTextSpan with colors: # - Cyan: branch is in sync with remote # - Green: branch is ahead of remote # - Red: branch is behind remote # - Yellow: branch is both ahead and behind ``` -------------------------------- ### Write Git Status Summary First Source: https://github.com/dahlbyk/posh-git/wiki/Customizing-Your-PowerShell-Prompt Change the prompt layout to display the Git status summary before the directory path. Set this to $true to reorder the elements. ```powershell $GitPromptSettings.DefaultPromptWriteStatusFirst = $true ``` -------------------------------- ### Writing Custom Prompt Text with Write-Prompt Source: https://github.com/dahlbyk/posh-git/blob/master/README.md Wraps the posh-git prompt with custom text and colors using the Write-Prompt command. ```powershell # my profile.ps1 function prompt { # Your non-prompt logic here $prompt = Write-Prompt "Text before posh-git prompt " -ForegroundColor ([ConsoleColor]::Green) $prompt += & $GitPromptScriptBlock $prompt += Write-Prompt "Text after posh-git prompt" -ForegroundColor ([ConsoleColor]::Magenta) if ($prompt) { "$prompt " } else { " " } } ``` -------------------------------- ### PowerShell Prompt with Git Status Source: https://github.com/dahlbyk/posh-git/blob/master/src/en-US/about_posh-git.help.txt Illustrates the default posh-git prompt format, showing the current directory and Git status summary. Customize using $GitPromptSettings. ```powershell C:\GitHub\posh-git [master ≡]> ``` -------------------------------- ### Abbreviate Home Directory in Prompt Source: https://github.com/dahlbyk/posh-git/wiki/Customizing-Your-PowerShell-Prompt Set `$GitPromptSettings.DefaultPromptAbbreviateHomeDirectory` to `$true` to abbreviate paths under your home directory with a '~'. ```powershell $GitPromptSettings.DefaultPromptAbbreviateHomeDirectory = $true ``` -------------------------------- ### Default Prompt Layout Reference Source: https://github.com/dahlbyk/posh-git/wiki/Customizing-Your-PowerShell-Prompt Reference for the default layout of the posh-git prompt elements. DP is an abbreviation for DefaultPrompt settings. ```text {DPPrefix}{DPPath}{PathStatusSeparator}<{BeforeStatus}{Status}{AfterStatus}>{DPMiddle}<{DPDebug}><{DPTimingFormat}>{DPSuffix} ``` -------------------------------- ### Import-Module posh-git Source: https://context7.com/dahlbyk/posh-git/llms.txt Loads the module into the current session to enable prompt integration and tab completion. ```powershell # Import posh-git module Import-Module posh-git # Force posh-git to use its default prompt even if you have a custom prompt Import-Module posh-git -Args 1 # Use legacy TabExpansion on PowerShell Core (instead of Register-ArgumentCompleter) Import-Module posh-git -ArgumentList 0,1 ``` -------------------------------- ### Prompt Layout with Status First Reference Source: https://github.com/dahlbyk/posh-git/wiki/Customizing-Your-PowerShell-Prompt Reference for the posh-git prompt layout when DefaultPromptWriteStatusFirst is set to $true. This shows the Git status appearing before the path. ```text {DPPrefix}<{BeforeStatus}{Status}{AfterStatus}>{PathStatusSeparator}{DPPath}{DPMiddle}<{DPDebug}><{DPTimingFormat}>{DPSuffix} ``` -------------------------------- ### Configure Git Tab Settings Source: https://context7.com/dahlbyk/posh-git/llms.txt Manage tab completion behavior and logging for Git commands. ```powershell # Enable tab completion for all Git commands (not just common ones) $GitTabSettings.AllCommands = $true # Enable tab expansion logging for debugging $GitTabSettings.EnableLogging = $true $GitTabSettings.LogPath = "C:\temp\posh-git-tabexp.log" # View registered commands for completion $GitTabSettings.RegisteredCommands ``` -------------------------------- ### Customize Default Prompt Prefix with Timestamp Source: https://github.com/dahlbyk/posh-git/wiki/Customizing-Your-PowerShell-Prompt Set a colored timestamp as the default prompt prefix. Ensure $GitPromptSettings is initialized before use. ```powershell $GitPromptSettings.DefaultPromptPrefix.Text = '$(Get-Date -f "MM-dd HH:mm:ss") ' $GitPromptSettings.DefaultPromptPrefix.ForegroundColor = [ConsoleColor]::Magenta ``` -------------------------------- ### Write-VcsStatus Source: https://context7.com/dahlbyk/posh-git/llms.txt Writes all version control prompt statuses configured in $global:VcsPromptStatuses. By default, this includes the posh-git status. ```APIDOC ## Write-VcsStatus ### Description Writes all version control prompt statuses configured in $global:VcsPromptStatuses. By default, this includes the posh-git status. ### Method Cmdlet ### Endpoint N/A (PowerShell Cmdlet) ### Parameters #### Global Variables - **$global:VcsPromptStatuses** (Array) - An array of script blocks that provide version control status information. ### Request Example ```powershell # Use in a custom prompt function function prompt { Write-Host "PS $(Get-Location)" -NoNewline Write-VcsStatus # Automatically calls Get-GitStatus and Write-GitStatus return "> " } # Add additional VCS status providers $global:VcsPromptStatuses += { # Custom status logic here if (Test-Path .hg) { " [Hg]" } } ``` ### Response N/A (Writes directly to console or prompt) ``` -------------------------------- ### Handle Empty Prompt Strings Source: https://github.com/dahlbyk/posh-git/wiki/Customizing-Your-PowerShell-Prompt Ensure the prompt string is not empty before outputting to prevent default PS> behavior. ```powershell if ($prompt) {$prompt} else {" "} ``` -------------------------------- ### Get-GitDirectory Source: https://context7.com/dahlbyk/posh-git/llms.txt Returns the path to the current repository's .git directory. ```powershell # Get the .git directory path $gitDir = Get-GitDirectory # Returns: "C:\Projects\my-repo\.git" # Use in conditional logic if (Get-GitDirectory) { Write-Host "Inside a Git repository" } else { Write-Host "Not in a Git repository" } ``` -------------------------------- ### Enable Two-Line Prompt Source: https://github.com/dahlbyk/posh-git/wiki/Customizing-Your-PowerShell-Prompt Configure the prompt to span two lines by inserting a newline character after the Git status summary. Use '`n' for the newline. ```powershell $GitPromptSettings.DefaultPromptBeforeSuffix.Text = '`n' ``` -------------------------------- ### Customize Default Prompt Prefix Source: https://github.com/dahlbyk/posh-git/wiki/Customizing-Your-PowerShell-Prompt Set the `$GitPromptSettings.DefaultPromptPrefix` to a custom string, such as a timestamp, to change the beginning of the prompt. ```powershell $GitPromptSettings.DefaultPromptPrefix = '$(Get-Date -f "MM-dd HH:mm:ss") ' ``` -------------------------------- ### Enable Git Directory Abbreviation Source: https://context7.com/dahlbyk/posh-git/llms.txt Enables abbreviation for the Git directory in the prompt, showing the repository name and relative path. ```powershell $GitPromptSettings.DefaultPromptAbbreviateGitDirectory = $true $path = Get-PromptPath # Output: "my-repo:src\components" (when in my-repo/src/components) ``` -------------------------------- ### Using $GitPromptScriptBlock for Custom Logic Source: https://github.com/dahlbyk/posh-git/blob/master/README.md Executes custom logic within the PowerShell prompt function while still rendering the default posh-git prompt. ```powershell # my profile.ps1 function prompt { # Your non-prompt logic here # Have posh-git display its default prompt & $GitPromptScriptBlock } ``` -------------------------------- ### Create Custom Prompt with Error Information Source: https://context7.com/dahlbyk/posh-git/llms.txt Display exit codes and status information by accessing $GitPromptValues within a custom prompt function. ```powershell # Define error info function function global:PromptWriteErrorInfo() { if ($global:GitPromptValues.DollarQuestion) { return } if ($global:GitPromptValues.LastExitCode) { "`e[31m($($global:GitPromptValues.LastExitCode)) `e[0m" } else { "`e[31m! `e[0m" } } # Configure prompt to show errors $GitPromptSettings.DefaultPromptBeforeSuffix.Text = '`n$(PromptWriteErrorInfo)$(Get-Date -f "HH:mm:ss")' # Access GitPromptValues properties $global:GitPromptValues.DollarQuestion # Was last command successful $global:GitPromptValues.LastExitCode # Exit code of last external command $global:GitPromptValues.IsAdmin # Running as admin/root $global:GitPromptValues.LastPrompt # ANSI string of last prompt (for debugging) ``` -------------------------------- ### Write-Prompt Source: https://context7.com/dahlbyk/posh-git/llms.txt Writes text to the console with specified colors, or returns an ANSI-escaped string when AnsiConsole mode is enabled. ```APIDOC ## Write-Prompt ### Description Writes text to the console with specified colors, or returns an ANSI-escaped string when AnsiConsole mode is enabled. ### Method Cmdlet ### Endpoint N/A (PowerShell Cmdlet) ### Parameters #### Parameters - **InputObject** (Object) - The object to write to the console. - **-ForegroundColor** (ConsoleColor) - The foreground color for the text. - **-BackgroundColor** (ConsoleColor) - The background color for the text. - **-AnsiConsole** (Switch) - Enables ANSI-escaped string output. ### Request Example ```powershell # Write colored text to console Write-Prompt "Hello" -ForegroundColor Cyan -BackgroundColor Black # Write a PoshGitTextSpan object $span = [PoshGitTextSpan]::new("Status:", [ConsoleColor]::Green) Write-Prompt $span # Use with StringBuilder for efficient string building $sb = [System.Text.StringBuilder]::new() $sb | Write-Prompt "Part 1 " -ForegroundColor Red $sb | Write-Prompt "Part 2" -ForegroundColor Blue $sb.ToString() ``` ### Response N/A (Writes directly to console or returns string) ``` -------------------------------- ### Get-GitDirectory Source: https://context7.com/dahlbyk/posh-git/llms.txt Retrieves the path to the current repository's .git directory or the root directory for bare repositories. ```APIDOC ## Get-GitDirectory ### Description Gets the path to the current repository's .git directory, or the root directory for bare repositories. ### Response #### Success Response (200) - **Path** (String) - The absolute path to the .git directory or null if not in a repository ``` -------------------------------- ### Add path delimiters Source: https://github.com/dahlbyk/posh-git/blob/master/README.md Wraps the path in custom characters with specific colors. ```powershell $GitPromptSettings.BeforePath = '{' $GitPromptSettings.AfterPath = '}' $GitPromptSettings.BeforePath.ForegroundColor = 'Red' $GitPromptSettings.AfterPath.ForegroundColor = 'Red' ``` -------------------------------- ### Write-GitWorkingDirStatusSummary Source: https://context7.com/dahlbyk/posh-git/llms.txt Writes a single symbol summarizing the overall working directory state: unstaged changes (!), staged changes (~), or clean. ```APIDOC ## Write-GitWorkingDirStatusSummary ### Description Writes a single symbol summarizing the overall working directory state: unstaged changes (!), staged changes (~), or clean. ### Method Cmdlet ### Endpoint N/A (PowerShell Cmdlet) ### Parameters #### Parameters - **InputObject** (Object) - The Git status object. ### Request Example ```powershell # Write working directory summary symbol $status = Get-GitStatus Write-GitWorkingDirStatusSummary $status # Output: " !" (unstaged changes), " ~" (staged only), "" (clean) ``` ### Response N/A (Writes directly to console or appends to StringBuilder) ``` -------------------------------- ### Git Status Summary Format Source: https://github.com/dahlbyk/posh-git/blob/master/src/en-US/about_posh-git.help.txt Explains the components of the Git status summary displayed in the prompt. This includes branch status relative to remote and working directory status. ```text [{HEAD-name} S +A ~B -C !D | +E ~F -G !H W] ``` -------------------------------- ### Expand-GitCommand Source: https://context7.com/dahlbyk/posh-git/llms.txt Expands a partial Git command for tab completion. This is the core function powering Git tab completion. ```APIDOC ## Expand-GitCommand ### Description Expands a partial Git command for tab completion. This is the core function powering Git tab completion. ### Method GET ### Endpoint /git/expand ### Parameters #### Query Parameters - **Command** (string) - Required - The partial Git command to expand. ### Request Example ```powershell # Expand partial git commands Expand-GitCommand "git ch" # Output: "checkout", "cherry", "cherry-pick" # Expand branch names for checkout Expand-GitCommand "git checkout ma" # Output: "main", "master" # Expand remote names for push Expand-GitCommand "git push or" # Output: "origin" # Expand file paths for add Expand-GitCommand "git add src/" # Output: list of modified/untracked files in src/ ``` ### Response #### Success Response (200) - **completions** (array of strings) - A list of possible command completions. #### Response Example ```json { "completions": [ "checkout", "cherry", "cherry-pick" ] } ``` ``` -------------------------------- ### Integrate with Custom Prompt Functions Source: https://context7.com/dahlbyk/posh-git/llms.txt Use $GitPromptScriptBlock to embed posh-git status into custom PowerShell prompt functions. ```powershell # Use posh-git prompt within a custom prompt function function prompt { # Your custom logic before prompt Set-NodeVersion # Execute the posh-git prompt & $GitPromptScriptBlock } # Wrap posh-git prompt with custom text function prompt { $prompt = Write-Prompt "Before > " -ForegroundColor Green $prompt += & $GitPromptScriptBlock $prompt += Write-Prompt " < After" -ForegroundColor Magenta if ($prompt) { "$prompt" } else { " " } } ``` -------------------------------- ### Integrate posh-git into custom prompt Source: https://github.com/dahlbyk/posh-git/wiki/Customizing-Your-PowerShell-Prompt Invoke the GitPromptScriptBlock within a custom prompt function to display the default posh-git prompt. ```powershell function prompt { # Your non-prompt logic here # Have posh-git display its default prompt & $GitPromptScriptBlock } ``` -------------------------------- ### Write-VcsStatus Source: https://github.com/dahlbyk/posh-git/blob/master/src/en-US/about_posh-git.help.txt Retrieves and formats Git repository status for display in the prompt. ```APIDOC ## Write-VcsStatus ### Description Gets the Git repository information and formats it for the prompt. Can be integrated with other version control systems via $global:VcsPromptStatuses. ``` -------------------------------- ### Write VCS Status in Prompt Source: https://context7.com/dahlbyk/posh-git/llms.txt Writes version control prompt statuses. By default, it includes posh-git status. This function can be extended to include statuses from other version control systems. ```powershell # Write VCS status in your prompt function prompt { Write-Host "PS $(Get-Location)" -NoNewline Write-VcsStatus # Automatically calls Get-GitStatus and Write-GitStatus return "> " } ``` ```powershell # Add additional VCS status providers $global:VcsPromptStatuses += { # Custom status logic here if (Test-Path .hg) { " [Hg]" } } ``` -------------------------------- ### Write Git Working Directory Status Summary Source: https://context7.com/dahlbyk/posh-git/llms.txt Writes a single symbol that summarizes the overall state of the working directory, indicating unstaged changes (!), staged changes (~), or a clean state. ```powershell # Write working directory summary symbol $status = Get-GitStatus Write-GitWorkingDirStatusSummary $status # Output: " !" (unstaged changes), " ~" (staged only), "" (clean) ``` -------------------------------- ### Make Posh-Git Prompt Span Two Lines Source: https://github.com/dahlbyk/posh-git/wiki/Customizing-Your-PowerShell-Prompt Append a newline character to `$GitPromptSettings.AfterText` to make the posh-git prompt span two lines, providing more space for commands. ```powershell $GitPromptSettings.AfterText += "`n" ``` -------------------------------- ### Configure posh-git in PowerShell Profile Source: https://github.com/dahlbyk/posh-git/blob/master/README.md Manually add the import command to your PowerShell profile script to load the module automatically in new sessions. ```powershell Import-Module posh-git ``` -------------------------------- ### Disable Home Directory Abbreviation Source: https://github.com/dahlbyk/posh-git/wiki/Customizing-Your-PowerShell-Prompt Disable the default behavior of abbreviating the home directory with '~' in the prompt path. Set this to $false to display the full path. ```powershell $GitPromptSettings.DefaultPromptAbbreviateHomeDirectory = $false ``` -------------------------------- ### Change path color Source: https://github.com/dahlbyk/posh-git/blob/master/README.md Sets the path color using HTML color names on Windows or RGB values on other platforms. ```text $GitPromptSettings.DefaultPromptPath.ForegroundColor = 'Orange' ``` ```text $GitPromptSettings.DefaultPromptPath.ForegroundColor = 0xFFA500 ``` -------------------------------- ### Edit PowerShell Profile Source: https://github.com/dahlbyk/posh-git/wiki/FAQ Use this command to open your current user and host specific PowerShell profile in Notepad. For other editors or profiles, adjust the command accordingly. ```powershell notepad.exe $profile ``` -------------------------------- ### Write-GitIndexStatus Source: https://context7.com/dahlbyk/posh-git/llms.txt Writes the index (staged changes) status showing counts of added, modified, deleted, and conflicted files. ```APIDOC ## Write-GitIndexStatus ### Description Writes the index (staged changes) status showing counts of added, modified, deleted, and conflicted files. ### Method Cmdlet ### Endpoint N/A (PowerShell Cmdlet) ### Parameters #### Parameters - **InputObject** (Object) - The Git status object. ### Request Example ```powershell # Write index status $status = Get-GitStatus Write-GitIndexStatus $status # Output: " +2 ~1 -0" (2 added, 1 modified, 0 deleted) ``` ### Response N/A (Writes directly to console or appends to StringBuilder) ``` -------------------------------- ### Launch TortoiseGit Commands Source: https://context7.com/dahlbyk/posh-git/llms.txt Use the tgit function to trigger TortoiseGit GUI operations from the command line. ```powershell # Launch TortoiseGit commit dialog tgit commit # Launch TortoiseGit log viewer tgit log # Launch TortoiseGit diff tgit diff # Tab completion works for TortoiseGit commands tgit ``` -------------------------------- ### Working Directory Status Symbol Source: https://github.com/dahlbyk/posh-git/blob/master/src/en-US/about_posh-git.help.txt Indicates if there are unstaged or uncommitted changes in the working directory. '!' for unstaged, '~' for uncommitted. ```text ! = There are unstaged changes (LocalWorkingStatusSymbol) ~ = There are uncommitted changes i.e. staged changes waiting to be ``` -------------------------------- ### Using GitPromptScriptBlock for Custom Logic Source: https://github.com/dahlbyk/posh-git/wiki/Customizing-Your-PowerShell-Prompt In v1.x, use the $GitPromptScriptBlock variable to execute custom logic before or during prompt rendering, allowing for non-prompt related operations within the prompt function. ```powershell powershell ``` -------------------------------- ### Enable Two-Line Prompt in Posh-Git Source: https://github.com/dahlbyk/posh-git/wiki/FAQ In posh-git versions 0.7.0 and higher, override these settings in your PowerShell profile after importing the module to make your prompt span two lines. ```powershell Import-Module posh-git $GitPromptSettings.PromptSuffix = '`nPS$(''>'' * ($nestedPromptLevel + 1)) ' $GitPromptSettings.PromptDebugSuffix = '`n[DBG]: PS$(''>'' * ($nestedPromptLevel + 1)) ' ``` -------------------------------- ### Change Prompt Path Foreground Color (Linux/macOS) Source: https://github.com/dahlbyk/posh-git/wiki/Customizing-Your-PowerShell-Prompt Set the foreground color for the prompt path on Linux or macOS using an RGB hexadecimal value. This is necessary as color name translation differs from Windows. ```powershell $GitPromptSettings.DefaultPromptPath.ForegroundColor = 0xFFA500 ``` -------------------------------- ### Index and Working Directory Status Symbols Source: https://github.com/dahlbyk/posh-git/blob/master/src/en-US/about_posh-git.help.txt Defines the symbols indicating the status of files in the Git index and working directory. Colors reflect 'git status' output. ```text + = Added files ~ = Modified files - = Removed files ! = Conflicted files Index status is dark green and working directory status is dark red reflecting the colors used by 'git status'. ``` -------------------------------- ### Boilerplate Prompt Function Pattern Source: https://github.com/dahlbyk/posh-git/wiki/Customizing-Your-PowerShell-Prompt A standard pattern for saving and restoring the last exit code within a custom prompt function. ```powershell function prompt { $origLastExitCode = $LASTEXITCODE # Generate prompt text to appear before the > char $LASTEXITCODE = $origLastExitCode "$(if ($PsDebugContext) {'[DBG]: '} else {''})$('>' * ($nestedPromptLevel + 1)) " } ``` -------------------------------- ### Change Prompt Path Foreground Color (Windows) Source: https://github.com/dahlbyk/posh-git/wiki/Customizing-Your-PowerShell-Prompt Set the foreground color for the prompt path on Windows. Accepts color names that can be translated via System.Drawing.ColorTranslator.FromHtml(). ```powershell $GitPromptSettings.DefaultPromptPath.ForegroundColor = 'Orange' ``` -------------------------------- ### Write-GitStatus Source: https://github.com/dahlbyk/posh-git/blob/master/src/en-US/about_posh-git.help.txt Formats a Git status object into a string for display in the PowerShell prompt. ```APIDOC ## Write-GitStatus ### Description Formats a status object returned by Get-GitStatus into a prompt string. Supports ANSI escape sequences if enabled in $GitPromptSettings. ### Parameters #### Parameters - **StatusObject** (Object) - Required - The status object returned by Get-GitStatus. ``` -------------------------------- ### Get-GitStatus Source: https://context7.com/dahlbyk/posh-git/llms.txt Retrieves an object containing detailed Git repository status information. ```powershell # Get Git status for current directory $status = Get-GitStatus # Access status properties $status.Branch # Current branch name: "main" $status.AheadBy # Commits ahead of remote: 2 $status.BehindBy # Commits behind remote: 1 $status.Upstream # Upstream branch: "origin/main" $status.UpstreamGone # Is upstream branch deleted: $false $status.HasIndex # Are there staged changes: $true $status.HasWorking # Are there unstaged changes: $true $status.HasUntracked # Are there untracked files: $true $status.StashCount # Number of stashes: 3 $status.RepoName # Repository folder name: "my-project" $status.GitDir # Path to .git directory # Access index (staged) file details $status.Index.Added # Staged new files $status.Index.Modified # Staged modified files $status.Index.Deleted # Staged deleted files $status.Index.Unmerged # Conflicted files # Access working directory (unstaged) file details $status.Working.Added # Untracked files $status.Working.Modified # Modified files $status.Working.Deleted # Deleted files $status.Working.Unmerged # Conflicted files # Force get status even when EnableFileStatus is disabled $status = Get-GitStatus -Force ``` -------------------------------- ### Get-GitStatus Source: https://github.com/dahlbyk/posh-git/blob/master/src/en-US/about_posh-git.help.txt Retrieves detailed information about the current Git repository, including the index and working directory status. ```APIDOC ## Get-GitStatus ### Description Returns information about the current Git repository as well as the index and working directory. ### Method PowerShell Cmdlet ### Response - **Object** (Object) - Returns a status object containing repository, index, and working directory information. ``` -------------------------------- ### Expand Partial Git Commands - Expand-GitCommand Source: https://context7.com/dahlbyk/posh-git/llms.txt Expands partial Git commands for tab completion. This function is central to Git tab completion in PowerShell. ```powershell # Expand partial git commands Expand-GitCommand "git ch" # Output: "checkout", "cherry", "cherry-pick" ``` ```powershell # Expand branch names for checkout Expand-GitCommand "git checkout ma" # Output: "main", "master" ``` ```powershell # Expand remote names for push Expand-GitCommand "git push or" # Output: "origin" ``` ```powershell # Expand file paths for add Expand-GitCommand "git add src/" # Output: list of modified/untracked files in src/ ```