Write-Host "`nBranches that match the prefix 'prefix′:"−ForegroundColorGreenmatchingBranches = matchingLocalBranches+matchingRemoteBranches
$matchingBranches
Ask for confirmation to delete
$confirmation = Read-Host -Prompt "Do you want to delete these branches? (yes/no)"
if (confirmation -ieq 'yes') {
foreach (branch in matchingBranches) {
# Remove leading spaces, "*" from the branch name, and any trailing whitespace
branchName = $branch.Trim()
# For remote branches
if ($branchName -imatch "^origin/") {
$cleanBranchName = $branchName -replace '^origin/', ''
try {
git push origin --delete "$cleanBranchName"
} catch {
Write-Host "Error deleting remote branch ${cleanBranchName}: $_" -ForegroundColor Red
}
} else {
try {
git branch -D "$branchName" # Force delete the local branch
} catch {
Write-Host "Error deleting local branch ${branchName}: $_" -ForegroundColor Red
}
}
}
} else {
Write-Host "No branches were deleted." -ForegroundColor Yellow
}
it doesn't correctly list branches based on prefix. it should list both local and remote branches
Assistant
Here's a corrected version of the script that lists both local and remote branches based on the provided prefix:
# List all local branches
Write-Host "Local branches:" -ForegroundColor Green
$localBranches = git branch | ForEach-Object { $_ -replace '^\s*\*?\s*', '' }
# List all remote branches
Write-Host "Remote branches:" -ForegroundColor Green
$remoteBranches = git branch -r
# Ask the user for a prefix
$prefix = Read-Host -Prompt 'Enter the branch prefix to filter'
# Ensure the prefix starts and ends with '/'
if (-not $prefix.StartsWith('/')) {
$prefix = '/' + $prefix
}
if (-not $prefix.EndsWith('/')) {
$prefix = $prefix + '/'
}
# Filter local branches based on the prefix
$matchingLocalBranches = $localBranches | Where-Object { $_ -imatch "^$prefix" }
# Filter remote branches based on the prefix
$matchingRemoteBranches = $remoteBranches | Where-Object { $_ -imatch "^(origin|upstream)$prefix" }
# Display branches that match the prefix
Write-Host "`nBranches that match the prefix '$prefix':" -ForegroundColor Green
$matchingBranches = $matchingLocalBranches + $matchingRemoteBranches
$matchingBranches
# Ask for confirmation to delete
$confirmation = Read-Host -Prompt "Do you want to delete these branches? (yes/no)"
if ($confirmation -ieq 'yes') {
foreach ($branch in $matchingBranches) {
# Remove leading spaces, "*" from the branch name, and any trailing whitespace
$branchName = $branch.Trim()
# For remote branches
if ($branchName -imatch "^origin/") {
$cleanBranchName = $branchName -replace '^origin/', ''
try {
git push origin --delete "$cleanBranchName"
} catch {
Write-Host "Error deleting remote branch ${cleanBranchName}: $_" -ForegroundColor Red
}
} elseif