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

标签 git powershell github

我希望能够从与我的 git 存储库不在同一文件夹中的 PowerShell 脚本执行 git 命令。

首先我想检查当前分支,如果不是master,尝试checkout master和pull master。

到目前为止我做了什么:

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

来自文档 here以及 this question 的答案.

$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): 我没有任何错误, pop 窗口打开和关闭的速度非常快,然后我的 powershell 脚本卡住了,就好像它在等待 git-cmd.exe 关闭一样。但是我看不到cmd git的窗口,也无法关闭。

最佳答案

CD 你的仓库文件夹

$branch= &git rev-parse --abbrev-ref HEAD 

来自Show just the current branch in Git

关于git - 使用 PowerShell 获取当前 git 分支的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42903289/

相关文章:

android - 如何在 Android 应用程序中使用来自 GitHub 的库

git - 下载Android源时节省空间

git - 将两个 git 存储库 merge 为一个,保留(重命名)master 分支

git - 如何清除远程 github repo 中的所有提交

powershell - 删除项目后强制桌面上的图标刷新,或首先停止添加项目

macos - git-core 已经被 git 端口废弃了

linux - Linux 共享开发中如何保证代码安全?

powershell - 融合应用程序 Azure AD v2,以编程方式注册

powershell - 无法比较创建日期和当前日期

git - 如何在 pull 请求事件中获取 github 应用程序安装 ID?