Delete Git Branches in PowerShell

technology

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

By Ganessh Kumar1 min read
  • 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.

Keep reading

I write about full-stack development, developer tooling and the problems I run into building things. Here is everything else on the blog.