使用PowerShell获取当前git分支的名称

use*_*807 8 git powershell github

我希望能够从PowerShell脚本执行git命令,该脚本与我的git repo不在同一个文件夹中.

首先,我想检查当前的分支,如果它不是主要的,请尝试检查主机和拉主机.

到目前为止我做了什么:

function Get-ScriptDirectory {
    Split-Path $script:MyInvocation.MyCommand.Path
}

$currentPath = Get-ScriptDirectory
[string]$Path_GIT = "C:\Program Files\Git\git-cmd.exe"
$gitRepo = $currentPath + "\..\"
$nameCurrentBranch = & $Path_GIT git -C "$gitRepo" rev-parse --abbrev-ref HEAD
Run Code Online (Sandbox Code Playgroud)

这里的文档和这个问题的答案.

$gitRepo 包含包含git repo的文件夹的路径.

我收到错误:

git-cmd.exe : fatal: Cannot change to 'C:\Users\MyName\Documents\Projects\MyProject\
Batchs\.." rev-parse --abbrev-ref HEAD': Invalid argument
At C:\Users\MyName\Documents\Projects\MyProject\Batchs\Publish.ps1:64 char:22
+ ... entBranch = & $Path_GIT git -C "$gitRepo" rev-parse --abbrev-ref HEAD ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (fatal: Cannot c...nvalid argument:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

编辑: @ 4c74356b41命令后的新问题(使用Join-Path):我没有任何错误弹出窗口打开和关闭非常快,然后我的powershell脚本卡住了,好像它正在等待git-cmd.exe关闭.但是我看不到cmd git的窗户而无法关闭它.

MiF*_*vil 13

CD您的存储库文件夹

$branch= &git rev-parse --abbrev-ref HEAD 
Run Code Online (Sandbox Code Playgroud)

来自Show只是Git中的当前分支

  • 从 git 2.22 开始,这有点简单 `$branch = gitbranch --show-current` (4认同)

4c7*_*b41 1

尝试加入路径

$gitRepo = Join-Path $currentPath ".." -Resolve
Run Code Online (Sandbox Code Playgroud)