Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Clear deleted git branches
function Clear-DeletedBranches {
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')]
[Parameter(Mandatory = $false)]
$GitDir = $PWD
$defaultBranch = ((git symbolic-ref --short refs/remotes/origin/HEAD) -split "/")[1]
Write-Host "Switching to branch [$defaultBranch]..." -ForegroundColor Yellow
git checkout $defaultBranch
$branchesBefore = git branch -a
$branchesToPrune = git remote prune origin --dry-run
if ($branchesToPrune) {
Write-Host "Branches to Be Pruned..." -ForegroundColor Green
Write-Host $branchesToPrune -ForegroundColor Red
if ($PSCmdlet.ShouldProcess("Remove Local Branches?")) {
git remote prune origin
$branchesAfter = git branch -a
$removed = Compare-Object -ReferenceObject $branchesBefore -DifferenceObject $branchesAfter
foreach ($b in $removed.InputObject) {
$localName = $b.Split('/')[-1]
git branch -D $localName
} else {
Write-Host "Nothing To prune" -ForegroundColor Green
Write-Host "`nPulling changes from default branch..." -ForegroundColor Green
git pull
Write-Host "`nCurrent branches..." -ForegroundColor Green
git branch -a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment