How to Delete All Git Branches Except Master or Main in PowerShell

November 25, 2024
git, powershell, version control

In Windows PowerShell, you can delete all branches except main or master branch of a git repository using the following command

git branch | Where-Object { $_ -notmatch "master" -and $_ -notmatch "main" } | ForEach-Object { git branch -D $_.Trim() }

Explanation:

  • git branch: Lists all branches.
  • Where-Object { $_ -notmatch "master" -and $_ -notmatch "main" }: Filters out the branch named master or main using PowerShell’s pattern matching.
  • ForEach-Object { git branch -D $_.Trim() }: Iterates over each remaining branch name, trims any extra whitespace, and deletes it with git branch -D.

Comments