DevOpsHandling/Get-DevOpsArtifactsFromLastSuccessfulBuild.ps1

function Get-DevOpsArtifactsFromLastSuccessfulBuild {
    Param(
        [Parameter(Mandatory=$true)]
        [string]$devOpsOrganization,
        [Parameter(Mandatory=$true)]
        [string]$devOpsProjectName,
        [Parameter(Mandatory=$true)]
        [string]$repositoryName,
        [Parameter(Mandatory=$true)]
        [string]$devOpsToken,
        [Parameter(Mandatory=$true)]
        [string]$destination,
        [Parameter(Mandatory=$false)]
        [string]$branchName = ''
    )

    $projects = (Get-DevOpsProjects -devOpsOrganization $devOpsOrganization -devOpsToken $devOpsToken)
    if ($projects.Length -ne 0) {
        $project = $projects | Where-Object name -like ('*{0}*' -f $devOpsProjectName)
    } else {
        return @()
    }

    if ($null -ne $project) {
        $devOpsProjectName = $project.name
    } else {
        return @()
    }

    if ($branchName -ne '') {
        $lastBuilds = (Get-AllSuccessfulBuilds -devOpsOrganization $devOpsOrganization -devOpsProjectName $devOpsProjectName -repositoryName $repositoryName -devOpsToken $devOpsToken -branchName $branchName)
    }
    else {
        $lastBuilds = (Get-AllSuccessfulBuilds -devOpsOrganization $devOpsOrganization -devOpsProjectName $devOpsProjectName -repositoryName $repositoryName -devOpsToken $devOpsToken)
    }
    if ($null -eq $lastBuilds) {
        throw "No build found for artifact"
    }
    try {
        if ($lastBuilds.Count -eq 0) {
            throw "No build found for artifact"
        }
    }
    catch {}

    $appsList = [System.Collections.ArrayList]@()

    $lastBuilds | ForEach-Object {
        if ($appsList.Count -eq 0) {
            $artifact = (Invoke-AzureDevOpsApi -url ('https://dev.azure.com/{0}/{1}/_apis/build/builds/{2}/artifacts' -f $devOpsOrganization, $devOpsProjectName, $_.id) -devOpsToken $devOpsToken)
            if ($null -ne $artifact) {
                if ($null -ne $artifact.value -and $artifact.count -ne 0) {
                    if ($null -ne $artifact.value.resource) {
                        $artifact = $artifact.value.resource

                        $artifact | ForEach-Object {
                            $apps = (Invoke-AzureDevOpsApi -url $_.downloadUrl -destination $destination -outfile (Join-Path $destination "artifact.zip") -devOpsToken $devOpsToken)
                            foreach ($app in $apps) {
                                [void]$appsList.Add($app)
                            }
                        }
                    }
                }
            }
        }
    }

    Remove-Item -Path (Join-Path $destination "artifact.zip") -Force | Out-Null

    return $appsList
}
Export-ModuleMember Get-DevOpsArtifactsFromLastSuccessfulBuild