Hello! Today, I needed a way to easily input a branch name into a PowerShell script. To do this, I decided to use what is easily the most fun cmdlet: Out-GridView. This solution would let me select the branch I want to use from a searchable GUI list.
I first needed the list of branches.
PS> $dotgit = "C:\Development\Project\.git\"
PS> git --git-dir=$dotgit branch -r | Out-GridView
--git-dir=$dotgit
lets me point the command at a git repo without being in it. -r specifies that I want the list of branches on the remote.
Already we have our list of branches! There are still some improvements that can be made. I have no need for the first line in the list, ‘origin/HEAD -> origin/master’, nor the ‘origin/’ word prefixing every line.
PS> git --git-dir=$dotgit branch -r | Select-Object -Skip 1 | ForEach-Object {$_.replace(" origin/", "")} | Out-GridView
Select-Object is used to skip the first line. ForEach-Object is used to replace the word ‘origin/’, and the unnecessary white space that comes before it, with an empty string.
The list itself is now perfect, but I still need to make some changes to Out-GridView so that I can use it to select the branches I want.
PS> git --git-dir=$dotgit branch -r | Select-Object -Skip 1 | ForEach-Object {$_.replace(" origin/", "")} | Out-GridView -Title "remote branches" -PassThru
-PassTrue does just this, and any branches I select will now be passed down the pipeline when OK is clicked. -Title just sets the window’s title.
function pickBranch($dotgit) {
git --git-dir=$dotgit branch -r |
Select-Object -Skip 1 |
ForEach-Object {$_.replace(" origin/", "")} |
Out-GridView -Title "remote branches" -PassThru
}