How to delete all merged local branches in Git with PowerShell
git branch --merged | Select-String -Pattern '^[^\*].*' | ForEach-Object { git branch -d $_.ToString().Trim() }
Steps:
List merged branches:
git branch --merged
feature/branch1 feature/branch2 * master
Filter out those that starts with * (current branch):
Select-String -Pattern '^[^\*].*'
feature/branch1 feature/branch2
Delete branches
ForEach-Object { git branch -d $_.ToString().Trim() }
Notice than in #3 I have removed some whitespace from the output: $_.ToString().Trim()
.
Otherwise we would get errors like:
error: branch ' feature/yourbranch' not found.
After some playing about, and further research into Powershell commands, I have found a solution!
While Powershell does not have an xargs
command, it does have something similar called ForEach-Object
. This command allows us to work on each line of the output from git for-each-ref
. For this specific problem, the following line did the trick:
git for-each-ref --format '%(refname:short)' refs/heads | ForEach-Object {git branch $_ -d}
The curly braces after the ForEach-Object
command contains the command you wish to run, while the $_
variable stands for each line of output from the piped command.
Hope this helps other newbie Powershell/Git users out there!