Git list of remote branches

I'm looking for the best way to execute a function for each remote Git branch in a PowerShell script.

I don't know of a better way to get a list of remote Git branches. I can successfully list all remote branches, but I always get annoying formatting in the branch names.

Here are the commands I tried and the resulting arrays I got.

$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 that $allBranches = @('origin/branch1', 'origin/branch2', 'origin/branch3')

, so my current approach is to simply manually remove the formatting from the weird branch names with Trim()

:

foreach($branch in $allBranches) {
    # Format $branch
    # Do function
}

      

Is there a better approach?

+4


source to share


2 answers


The Trim () operation should do what you want.



$allTrimmedBranches = @()
foreach($branch in $allBranches) {
    $allTrimmedBranches += $branch.Trim()
}
#do function

      

+2


source


$branches = git for-each-ref --format='%(refname:short)' refs/remotes/origin



+2


source







All Articles