Skip to content

Instantly share code, notes, and snippets.

@kawishbit
Created May 8, 2024 06:18
Show Gist options
  • Save kawishbit/86988bdd7cc7f1898e0a27117da5f6ae to your computer and use it in GitHub Desktop.
Save kawishbit/86988bdd7cc7f1898e0a27117da5f6ae to your computer and use it in GitHub Desktop.
Delete Local Branches Using Powershell
# Array of branch names that you want to include
$excludeBranches = @("main", "develop", "feature1", "hotfix1")
# Retrieve all local branches using git command
$allBranches = git branch --format="%(refname:short)"
# Convert the output into an array
$allBranchesArray = $allBranches -split "`n"
# Filter the branches based on whether they are in the specified array
$filteredBranches = $allBranchesArray | Where-Object { $excludeBranches -NotContains $_ }
Write-Output "The following branches will be deleted:"
$filteredBranches | ForEach-Object {
$branch = $_.Trim()
# Check for upstream branches on all remotes using `git for-each-ref`
$upstreamBranch = git for-each-ref --format='%(upstream:short)' "refs/heads/$branch"
if ($upstreamBranch) {
$remoteName = $upstreamBranch -split '/' | Select-Object -First 1
Write-Output "Branch: $branch (Exists on remote: $remoteName)"
} else {
Write-Output "Branch: $branch (Local only)"
}
}
$confirmation = Read-Host "Are you sure you want to delete these branches? (Y/N)"
# If confirmed, delete the branches
if ($confirmation -eq 'Y') {
$filteredBranches | ForEach-Object {
$branch = $_.Trim()
Write-Output "Deleting branch: $branch"
git branch -D $branch
}
} else {
Write-Output "Branch deletion canceled."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment