7

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Elaine Lin
  • 511
  • 1
  • 5
  • 15
  • https://stackoverflow.com/questions/3846380/how-to-iterate-through-all-git-branches-using-bash-script has Bash in the title but really contains the Git magic you want – Kristján Aug 07 '15 at 15:29
  • Are you looking for Powershell code to format the returned branch names easily, or a better git call that doesn't include the extra spaces? – weirdev Aug 07 '15 at 15:32
  • I am looking for a Powershell script, not a Bash script. I know how to format the branch names. I would like a better git call or a better way to iterate through the branches. – Elaine Lin Aug 07 '15 at 15:34

2 Answers2

3

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

dimiboi
  • 163
  • 1
  • 7
2

The Trim() operation should do what you want.

$allTrimmedBranches = @()
foreach($branch in $allBranches) {
    $allTrimmedBranches += $branch.Trim()
}
#do function
weirdev
  • 1,388
  • 8
  • 20
  • My current approach is to trim the branch names, which seems rather inefficient. I would like a better git call or a better way to iterate through the branches. – Elaine Lin Aug 07 '15 at 15:41
  • 1
    How many branches do you have? The time/resources it takes to trim a hundred or fewer strings are negligible. – weirdev Aug 07 '15 at 15:50
  • I have <100 branches. However, I'm wondering if there's a cleaner solution. – Elaine Lin Aug 07 '15 at 15:52