如何在PowerShell提示符中显示当前的git分支名称?

Pau*_*tum 52 git powershell command-prompt

基本上我是在之后但是对于PowerShell而不是bash.

我通过PowerShell在Windows上使用git.如果可能,我希望我当前的分支名称显示为命令提示符的一部分.

sev*_*rce 39

一种更简单的方法就是安装Powershell模块posh-git.它开箱即用,带有所需的提示:

提示

PowerShell通过执行提示函数(如果存在)生成其提示.posh-git在profile.example.ps1中定义了这样一个函数,它输出当前工作目录,后跟缩写的git状态:

C:\Users\Keith [master]>

默认情况下,状态摘要具有以下格式:

[{HEAD-name} +A ~B -C !D | +E ~F -G !H]

(对于安装posh-git我建议使用psget)

如果您没有psget,请使用以下命令:

(new-object Net.WebClient).DownloadString("http://psget.net/GetPsGet.ps1") | iex
Run Code Online (Sandbox Code Playgroud)

要安装posh-git,请使用以下命令: Install-Module posh-git

要确保每个shell的posh-git加载,请使用该Add-PoshGitToPrompt命令.

  • 如果您使用 Chocolatey,您只需从提升的命令提示符处使用“choco install poshgit”即可安装 posh-git。 (3认同)
  • GetPsGet.ps1 现在位于“https://raw.githubusercontent.com/psget/psget/master/GetPsGet.ps1”。“http://psget.net/GetPsGet.ps1”URL 似乎不再存在。 (3认同)
  • @NicolaPeluchetti谢谢!我关注了https://www.howtogeek.com/50236/customizing-your-powershell-profile/,并在我的powershell配置文件中添加了`Import-Module posh-git`.像魅力一样工作! (2认同)
  • 我发现它很慢.._加载个人和系统配置文件花了 1065 毫秒._ (2认同)

Dav*_*ker 23

@ Paul-

我的Git PowerShell配置文件基于我在这里找到的脚本:

http://techblogging.wordpress.com/2008/10/12/displaying-git-branch-on-your-powershell-prompt/

我已经修改了一下以显示目录路径和一些格式.它还设置了我的Git bin位置的路径,因为我使用PortableGit.

# General variables
$pathToPortableGit = "D:\shared_tools\tools\PortableGit"
$scripts = "D:\shared_tools\scripts"

# Add Git executables to the mix.
[System.Environment]::SetEnvironmentVariable("PATH", $Env:Path + ";" + (Join-Path $pathToPortableGit "\bin") + ";" + $scripts, "Process")

# Setup Home so that Git doesn't freak out.
[System.Environment]::SetEnvironmentVariable("HOME", (Join-Path $Env:HomeDrive $Env:HomePath), "Process")

$Global:CurrentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$UserType = "User"
$CurrentUser.Groups | foreach { 
    if ($_.value -eq "S-1-5-32-544") {
        $UserType = "Admin" } 
    }

function prompt {
     # Fun stuff if using the standard PowerShell prompt; not useful for Console2.
     # This, and the variables above, could be commented out.
     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("")
    $status_string = ""
    $symbolicref = git symbolic-ref HEAD
    if($symbolicref -ne $NULL) {
        $status_string += "GIT [" + $symbolicref.substring($symbolicref.LastIndexOf("/") +1) + "] "

        $differences = (git diff-index --name-status HEAD)
        $git_update_count = [regex]::matches($differences, "M`t").count
        $git_create_count = [regex]::matches($differences, "A`t").count
        $git_delete_count = [regex]::matches($differences, "D`t").count

        $status_string += "c:" + $git_create_count + " u:" + $git_update_count + " d:" + $git_delete_count + " | "
    }
    else {
        $status_string = "PS "
    }

    if ($status_string.StartsWith("GIT")) {
        Write-Host ($status_string + $(get-location) + ">") -nonewline -foregroundcolor yellow
    }
    else {
        Write-Host ($status_string + $(get-location) + ">") -nonewline -foregroundcolor green
    }
    return " "
 }
Run Code Online (Sandbox Code Playgroud)

到目前为止,这一点非常有效.在回购中,提示愉快地看起来像:

GIT [master] c:0 u:1 d:0 | j:\项目\叉\流利-的nhibernate>

*注意:更新了JakubNarębski的建议.

  • 删除了git branch/git status调用.
  • 解决了'git config --global'会失败的问题,因为没有设置$ HOME.
  • 解决了浏览到没有.git目录的目录会导致格式化还原为PS提示的问题.

  • 不要刮取git-branch输出来获取当前分支的名称; 它适用于最终用户(它是瓷器).使用`git symbolic-ref HEAD`.不要使用git-status; 它适用于最终用户,并且可能会发生变化(在1.7.0中会发生变化).使用git-diff-files,git-diff-tree,git-diff-index. (6认同)

tam*_*rd2 18

这是我的看法.我已经编辑了一些颜色以使其更具可读性.

Microsoft.PowerShell_profile.ps1

function Write-BranchName () {
    try {
        $branch = git rev-parse --abbrev-ref HEAD

        if ($branch -eq "HEAD") {
            # we're probably in detached HEAD state, so print the SHA
            $branch = git rev-parse --short HEAD
            Write-Host " ($branch)" -ForegroundColor "red"
        }
        else {
            # we're on an actual branch, so print it
            Write-Host " ($branch)" -ForegroundColor "blue"
        }
    } catch {
        # we'll end up here if we're in a newly initiated git repo
        Write-Host " (no branches yet)" -ForegroundColor "yellow"
    }
}

function prompt {
    $base = "PS "
    $path = "$($executionContext.SessionState.Path.CurrentLocation)"
    $userPrompt = "$('>' * ($nestedPromptLevel + 1)) "

    Write-Host "`n$base" -NoNewline

    if (Test-Path .git) {
        Write-Host $path -NoNewline -ForegroundColor "green"
        Write-BranchName
    }
    else {
        # we're not in a repo so don't bother displaying branch name/sha
        Write-Host $path -ForegroundColor "green"
    }

    return $userPrompt
}
Run Code Online (Sandbox Code Playgroud)

例1:

在此输入图像描述

例2:

在此输入图像描述

  • 对于那些不知道如何使用此 ps1 脚本的人,只需将其复制并粘贴到“Microsoft.PowerShell_profile.ps1”文件中,该文件位于此处(对于您的本地用户):“$UserHome\[My]Documents\PowerShell\”对我来说,因为我已将 OneDrive 集成到我的计算机中,所以它位于此处:`C:\Users\<USER>\OneDrive - \Documents\WindowsPowerShell` (4认同)

Jer*_*yal 10

posh-git 很慢,使用https://ohmyposh.dev/有更好的方法。

在此输入图像描述

  1. 从 powershell 运行此命令来安装ohmyposh模块:
Install-Module oh-my-posh -Scope CurrentUser -AllowPrerelease
Run Code Online (Sandbox Code Playgroud)
  1. 从https://www.nerdfonts.com/安装支持字形(图标)的字体。
    我喜欢Meslo LGM NF

  2. 在 powershell 默认设置中设置该字体:

在此输入图像描述

  1. 打开/创建文件Microsoft.PowerShell_profile.ps1C:\Program Files\PowerShell\7在下面写入以设置主题(与屏幕截图相同):
Set-PoshPrompt -Theme aliens
Run Code Online (Sandbox Code Playgroud)

您也可以选择其他主题。通过运行查看预览Get-PoshThemes

现在在包含 git repo 的位置打开 powershell,您将看到状态。


查看更多:增强您的 PowerShell


Von*_*onC 9

使用 Git 2.22(2019 年第 2 季度),任何脚本(无论是否为 Powershell)都可以使用--show-current 选项

$branch = git branch --show-current
Run Code Online (Sandbox Code Playgroud)

如果为空,则表示“分离的 HEAD”。