Remove merged branches with PowerShell
When working with Git repositories, it’s common to have multiple branches that have already been merged into the main branch. To keep your repository clean and organized, you can use PowerShell to remove these merged branches easily.
PowerShell Solution
As a developer running Windows all search engine results pointed me to bash scripts or Linux commands. However, I wanted a solution that works natively in PowerShell. Here’s a simple script that accomplishes this:
First, start with this command to fetch and prune remote-tracking branches (remove tracking of branches that no longer exist on the remote):
git fetch --prune
Then, use the following PowerShell command to delete all local branches that have been merged into the current branch (usually main or master):
git branch -vv | Where-Object { $_ -match 'gone\]' } | ForEach-Object { $_.Trim().Split()[0] } | ForEach-Object { git branch -d $_ }
Or, if you’re using squash merges and want to force delete branches, you can use:
git branch -vv | Where-Object { $_ -match 'gone\]' } | ForEach-Object { $_.Trim().Split()[0] } | ForEach-Object { git branch -D $_ }
Done!
No long scripts and no multiple page explanations. Just a couple of lines of PowerShell to keep your local repository cleaned up from merged branches. Happy coding!