Last active
February 14, 2020 12:30
-
-
Save paitonic/2cd7504ec6502ddc5aabeef290e59fd5 to your computer and use it in GitHub Desktop.
Powershell script to remove git branches by pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Remove-GitBranch { | |
# Example: | |
# Remove-GitBranch -regex feature # remove local branches matching regex pattern | |
# Remove-GitBranch -regex feature -origin # remove local & origin branches | |
param ( | |
[string] $regex, | |
[switch] $origin # remove the origin branch? | |
) | |
$branches = @( | |
git branch | ForEach-Object { $_.Trim() } | Where-Object { | |
$_ -NotMatch '^master|^develop|\*' -and | |
$_ -Match $regex | |
} | |
) | |
Write-Host "Found" $branches.Length "branches" | |
$branches = $branches | Where-Object { | |
$answer = Read-Host ("Remove branch '$_'? [y/n]"); | |
$answer -eq 'y' | |
} | |
if ($branches.Length -eq 0) { | |
return; | |
} | |
"The following branches will be removed:" | |
$branches | ForEach-Object { Write-Host "`t$_" -ForegroundColor red } | |
$answer = Read-Host ("Are you sure? [y/n]"); | |
if ($answer -ne 'y') { | |
return | |
} | |
git branch --delete $branches | |
if ($origin) { | |
$allRemoteBranches = git branch --remote | ForEach-Object { $_.Trim() } | |
$branchesToRemove = $branches | ForEach-Object { | |
if ($allRemoteBranches.Contains("origin/$_")) { | |
$_ | |
} | |
} | |
if ($branchesToRemove.Length -gt 0) { | |
git push origin --delete $branchesToRemove | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment