I'm looking for the best way to execute a function for each Git remote branch in a PowerShell script.
I don't know the best way to get a list of Git remote branches. I can successfully list all remote branches, but I always end up with pesky formatting in the branch names.
Here are the commands I've tried and the resulting arrays I've gotten.
$allBranches = git branch -r
$allBranches = @(' origin/branch1', ' origin/branch2', ' origin/branch3')
$allBranches = git for-each-ref --shell --format=%(refname) refs/remotes/origin
$allBranches = @(''origin/branch1'', ''origin/branch2'', ''origin/branch3'')
I would like
$allBranches = @('origin/branch1', 'origin/branch2', 'origin/branch3')
, so my current approach is to just manually remove formatting from the weird branch names using Trim()
:
foreach($branch in $allBranches) {
# Format $branch
# Do function
}
Is there a better approach?
In order to checkout a remote branch you have to first fetch the contents of the branch. In modern versions of Git, you can then checkout the remote branch like a local branch. Older versions of Git require the creation of a new branch based on the remote .
While “master” is the default name for a starting branch when you run git init which is the only reason it's widely used, “origin” is the default name for a remote when you run git clone . If you run git clone -o booyah instead, then you will have booyah/master as your default remote branch.
Fetch command will retrieve all changes from the remote branch which do not exist in the local branch. FETCH_HEAD ref track can be used for fetched changes from remote branches.
The Trim() operation should do what you want.
$allTrimmedBranches = @()
foreach($branch in $allBranches) {
$allTrimmedBranches += $branch.Trim()
}
#do function
$branches = git for-each-ref --format='%(refname:short)' refs/remotes/origin
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