2017-03-20 82 views
3

我希望能夠通過PowerShell腳本執行git命令,該腳本與我的git repo不在同一文件夾中。使用PowerShell獲取當前git分支的名稱

首先我想檢查當前分支,如果它不是主人嘗試結帳主和拉主。

什麼我迄今所做的:

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倉庫的文件夾的路徑。

我得到的錯誤:

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

編輯:(使用Join-Path)@ 4c74356b41的命題後新的問題: 我沒有一個彈出打開任何錯誤和關閉非常快,然後我的powershell腳本卡住了,好像它正在等待git-cmd.exe關閉。但是我看不到cmd git的窗口,無法關閉它。

+0

您是否知道辣妹的Git的? https://github.com/dahlbyk/posh-git –

+0

posh-git不會以任何方式幫助形狀或形式 – 4c74356b41

+0

閱讀你的代碼示例,你已經在你的回購。這意味着,像@Mark所說的那樣,posh-git會有所幫助。 (例如'Get-GitDirectory') – Clijsters

回答

1

嘗試聯接路徑

$gitRepo = Join-Path $currentPath ".." -Resolve 
+0

謝謝你的回答,我知道有一個新的錯誤(我嘗試過並且沒有在git-cmd調用中引用$ gitRepo的引號。 – user2088807

+0

爲什麼要在回購 – 4c74356b41

+0

的?root用戶運行該命令來獲得當前分支的名稱。如果它不掌握我希望籤主人和拉主。 – user2088807

0

使用psget安裝豪華-git的插件,顯示你當前分支。如果您擁有最新的PowerShell,則可能已安裝psget。如果你沒有它,那麼使用這個命令來獲取它。

(new-object Net.WebClient).DownloadString("http://psget.net/GetPsGet.ps1") | iex 

要安裝豪華-混帳使用命令:

Install-Module posh-git