[CmdletBinding()] param( [string]$Path = ".", [string]$Remote = "origin", [ValidateRange(1, 3650)] [int]$StaleDays = 90, [string]$Csv ) $ErrorActionPreference = 'Stop' if (-not (Get-Command git -ErrorAction SilentlyContinue)) { throw "git not found in PATH" } $repo = (Resolve-Path -LiteralPath $Path -ErrorAction Stop).Path $null = & git -C $repo rev-parse --is-inside-work-tree 2>$null if ($LASTEXITCODE -ne 0) { throw "Not a git repository: $repo" } $null = & git -C $repo remote get-url $Remote 2>$null if ($LASTEXITCODE -ne 0) { throw "Remote not found: $Remote" } $tracked = @{} $localLines = @(& git -C $repo for-each-ref "--format=%(refname:short)|%(upstream:short)" refs/heads 2>$null) foreach ($line in $localLines) { $parts = $line -split '\|', 2 if ($parts.Count -eq 2 -and $parts[1].Trim()) { $tracked[$parts[1].Trim()] = $true } } $format = '%(refname:short)|%(committerdate:iso8601)|%(subject)' $lines = @(& git -C $repo for-each-ref "--format=$format" "refs/remotes/$Remote" 2>$null) $rows = @() foreach ($line in $lines) { if ([string]::IsNullOrWhiteSpace($line)) { continue } $parts = $line -split '\|', 3 $name = $parts[0].Trim() if ($name.EndsWith('/HEAD')) { continue } $dateText = if ($parts.Count -gt 1) { $parts[1].Trim() } else { '' } $subject = if ($parts.Count -gt 2) { $parts[2].Trim() } else { '' } $age = -1 try { $date = [datetime]::Parse($dateText, [Globalization.CultureInfo]::InvariantCulture) $age = [math]::Floor(((Get-Date) - $date).TotalDays) } catch { $age = -1 } $rows += [pscustomobject]@{ Branch = $name AgeDays = $age Stale = ($age -ge $StaleDays) Local = $tracked.ContainsKey($name) Subject = $subject } } if ($rows.Count -eq 0) { Write-Host "No remote branches found for $Remote." exit 0 } $rows | Sort-Object @{ Expression = 'Stale'; Descending = $true }, @{ Expression = 'AgeDays'; Descending = $true } | Format-Table -AutoSize if ($Csv) { $rows | Export-Csv -LiteralPath $Csv -NoTypeInformation -Encoding UTF8 Write-Host "CSV saved: $Csv" } Write-Host "Report only. Use git remote prune $Remote manually after review."