Skip to content

Instantly share code, notes, and snippets.

@adamrushuk
Created May 29, 2021 08:39
Show Gist options
  • Save adamrushuk/45ed2dc59dbb7c99fcac0e7cb99fa95f to your computer and use it in GitHub Desktop.
Save adamrushuk/45ed2dc59dbb7c99fcac0e7cb99fa95f to your computer and use it in GitHub Desktop.
Clear deleted git branches
function Clear-DeletedBranches {
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')]
[Alias("cdb")]
param(
[Parameter(Mandatory = $false)]
[string]
$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