Skip to content

Instantly share code, notes, and snippets.

@rfennell
Last active July 29, 2023 10:08
Show Gist options
  • Save rfennell/281e7e6c34d5ab511b2a4b38b8ceae72 to your computer and use it in GitHub Desktop.
Save rfennell/281e7e6c34d5ab511b2a4b38b8ceae72 to your computer and use it in GitHub Desktop.
A PowerShell script to do a git fetch with a prune then also delete any local branches of the same name
# To set as Git Alias
# git config --global alias.tidy "!pwsh -command C:\MyFolder\Remove-DeletedGitBranches.ps1"
param
(
[Parameter()]
[Switch]
$Force
)
Write-Host "Getting list of branches"
$output = [string] (& git.exe branch 2>&1)
$mainbranch = "main"
if ($output.Contains("master"))
{
$mainbranch = "master"
}
Write-Host "Trunk branch is $mainbranch"
git checkout $mainbranch
$null = (git fetch --all --prune);
$branches = git branch -vv | Select-String -Pattern ": gone]" | ForEach-Object { $_.toString().Split(" ")[2] };
if($Force)
{
Write-Host "Deleting all removed branched"
$branches | ForEach-Object {git branch -D $_};
} else {
Write-Host "Deleting removed branched if committed"
$branches | ForEach-Object {git branch -d $_};
}
Write-Host "Fetching changes"
git fetch
@rfennell
Copy link
Author

rfennell commented Jul 6, 2022

To make this a git alias use the command

git config --global alias.tidy "!pwsh -command C:\MyFolder\Remove-DeletedGitBranches.ps1"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment