Functions/Sync-AzureDevOpsPullRequests.ps1


function Sync-AzureDevOpsPullRequests {
    [CmdletBinding()]
    param (
        [Parameter()] [string] $DevOpsOrganization = "ArcusITDevOps",
        [Parameter()] [string] $ProjectName = "Apps",
        [Parameter()] [string] $PAT
    )


    if (Get-Command az -ea 0) {
        $prs = az repos pr list --organization https://dev.azure.com/$DevOpsOrganization/ --project $ProjectName | ConvertFrom-Json
    } else {
        Write-Host "Azure CLI not installed. Please install Azure CLI and the Azure DevOps extension." -ForegroundColor Red
        return
    }

    if ($prs) {
        $prs | ForEach-Object {
            if ($_.createdBy.uniquename -ne (whoami /upn)) {
                # Not created by me
                if (!(Test-Path $_.repository.name)) {
                    # Repo not already cloned
                    Write-Host $_.repository.name -ForegroundColor Yellow
                    if ($PAT) {
                        git clone https://$($adoUser):$($PAT)@dev.azure.com/$DevOpsOrganization/$ProjectName/_git/$($_.repository.name)
                    } else {
                        git clone https://dev.azure.com/$DevOpsOrganization/$ProjectName/_git/$($_.repository.name)
                    }
                    Set-Location $_.repository.name
                    git switch $(($_.sourceRefName -split "/")[-1])
                    cd..
                }
            }
        }

        Compare-Object $prs.repository.name (Get-ChildItem).Name
        return
    }

}