I would like to be able to do git commands from a PowerShell script which is not located in the same folder as my git repo.
First I want to check the current branch, and if it's not master try to checkout master and pull master.
What I've done so far:
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
From the documentation here and the answers to this question.
$gitRepo
contains the path of the folder containing the git repo.
I get the error:
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
EDIT: New problem after the proposition of @4c74356b41 (using Join-Path
):
I don't have any error a popup opens and close really fast and then my powershell script is stuck, as if it was waiting for the git-cmd.exe to close. But I can't see the windows of the cmd git and can't close it.
The git_branch() is a function, that prints the name of the current Git branch in the round brackets. We set the PS1 variable and place the function git_branch() inside it to display the Git branch in the terminal prompt.
CD Your repository folder
$branch= &git rev-parse --abbrev-ref HEAD
Try Join-Path
$gitRepo = Join-Path $currentPath ".." -Resolve
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With