Functions/Sync-GitRepos.ps1


function Sync-GitRepos {
    [CmdletBinding()]
    param (
        [Parameter()] [switch] $Pull,
        [Parameter()] [switch] $RunMaintenance,
        [Parameter()] [switch] $CommitAndPush,
        [Parameter()] [string[]] $GitFolder = @("$($env:USERPROFILE)\Git", "$($env:USERPROFILE)\DevOps")
    )

    $currentLocation = $PWD.Path

    foreach ($gf in $GitFolder) {

        Write-Host "$($gf)" -ForegroundColor Yellow

        if (Test-Path $gf) {

            "---------------------------------"

            Get-ChildItem $gf -Directory | ForEach-Object {

                $GitConfigPath = Join-Path $_.FullName ".git"
                if (Test-Path $GitConfigPath) {
                    Set-Location $_.FullName
                    Write-Host $_.Name -ForegroundColor Green
                    "`n"
                    Write-Host "get all branches and switch to main/master" -ForegroundColor Yellow
                    $Branches = git branch -a
                    if ($Branches -match "main") {
                        git switch main
                    } elseif ($Branches -match "master") {
                        git switch master
                    } else {
                        Write-Warning "Master or main branch not found, leaving branch unchanged"
                    }

                    Write-Host "Fetch all and prune" -ForegroundColor Yellow
                    git fetch --all --prune
                    Write-Host "Run git status" -ForegroundColor Yellow
                    git status
                    Write-Host "Get git branches" -ForegroundColor Yellow
                    git branch -a

                    if ($Pull) {
                        Write-Host "Git pull" -ForegroundColor Yellow
                        git pull
                    }
                    if ($RunMaintenance) {
                        Write-Host "Run gif lfs prune" -ForegroundColor Yellow
                        git lfs prune
                        Write-Host "Run git gc" -ForegroundColor Yellow
                        git gc
                        Write-Host "Run git fsck" -ForegroundColor Yellow
                        git fsck
                    }
                    if ($CommitAndPush) {
                        git add .
                        git commit -a -m 'Commit All'
                        git push
                    }
                    "---------------------------------------------------------------`n"

                }

            }

            Set-Location $gf

        }
    }
    Set-Location $currentLocation

}