Friday, February 9, 2024

Cleanup Local Git Branches

 Below is a Powershell script that will remove local Git branches except for a list of excluded branches.


# Usage:  .\RemoveGitBranches.ps1 -directoryPath "C:\path\to\your\repository"
param (
    [string]$directoryPath
)

# Define the branches to keep
$branchesToKeep = @("dev", "develop", "development", "main", "master", "qa", "test", "stage")

# Change to the specified directory
Set-Location -Path $directoryPath

# Get a list of all local branches
$branches = git branch --format "%(refname:short)"

foreach ($branch in $branches) {
    $branch = $branch.Trim()

    # Check if the branch is not in the list of branches to keep
    if ($branch -notin $branchesToKeep) {
        # Delete the branch
        git branch -D $branch
    }
}