Build/Rerun-FailedInsiderBuilds.ps1

function Rerun-FailedInsiderBuilds {
    Param(
        [Parameter(Mandatory=$false)]
        [switch]$SkipAttempts
    )
    
    $InsiderRepos = Invoke-TFSAPI ('{0}/_apis/git/repositories' -f (Get-TFSCollectionURL))
    $InsiderRepos = $InsiderRepos.value | Where-Object name  -like '*-BC'
    foreach ($Repo in $InsiderRepos) {
        $Branches = Invoke-TFSAPI ('{0}/refs' -f $Repo.url)
        $Branches = $Branches.value | Where-Object name  -like 'refs/heads/build/insider*'
        foreach ($Branch in $Branches) {
            $LastBuildUrl = ('{0}/build/builds?$top=1&branchName={1}' -f $Branch.url.Substring(0, $Branch.url.IndexOf('/git')), $Branch.name)
            $LastBuild = Invoke-TFSAPI $LastBuildUrl
            #result: succeeded,failed
            if ($LastBuild.value.result -eq 'failed') {
                $Logs = Invoke-TFSAPI $LastBuild.value.Logs.url
                $timeline = Invoke-TFSAPI $LastBuild.value._links.timeline.href
                $attempts = ($timeline.records | Sort-Object attempt -Descending)[0].attempt
                if ($SkipAttempts -or ($attempts -le 3)) {
                    foreach ($Log in $Logs.value | Sort-Object id -Descending) {
                        $RawLog = Invoke-TFSAPI ('{0}?endLine=1' -f $Log.url)   
                        if ($RawLog -match 'Create packages and execute tests') {
                            $FullRawLog = Invoke-TFSAPI $Log.url
                            if (!($FullRawLog -match 'Compilation started for project')) {
                                Write-Host 'Retrying failed build '$LastBuild.value.buildNumber' - '$Repo.name':'$LastBuild.value.sourceBranch -ForegroundColor Green
                                $Response = Invoke-TFSAPI -Url ('{0}/?retry=true&api-version=6.0' -f $LastBuild.value.url) -HttpMethod Patch
                            }
                            break
                        }
                    }
                }
            }
        }
    }
}

Export-ModuleMember -Function Rerun-FailedInsiderBuilds