DevOpsHandling/Invoke-AzureDevOpsApi.ps1

<#
 .Synopsis
  Executes a command against the DevOps API
 .Description
  Executes a command against the DevOps API
 .Parameter url
  Url to the REST call
  .Parameter devOpsToken
  PAT for DevOps
  .Parameter outfile
  The output file that the result will be saved to, if the result is a file
  .Parameter GetContents
  Add this switch, if you want to get the contents of a file from DevOps
  .Example
  Invoke-AzureDevOpsApi -url "https://dev.azure.com/test/..." -devOpsToken "00000000-0000-0000-0000-000000000000" -GetContents
#>

function Invoke-AzureDevOpsApi {
    Param (
        [Parameter(Mandatory=$true)]
        [string]$url,
        [Parameter(Mandatory=$true)]
        [string] $devOpsToken,
        [Parameter(Mandatory=$false)]
        [string]$outfile,
        [switch] $GetContents
    )

    if ($url -eq '' -or $null -eq $url) {
        return ''
    }

    # Authentication
    $token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($devOpsToken)"))
    $header = @{authorization = "Basic $token"}

    # add API Version
    if (!$url.Contains('?')) {
        $url = ($url + '?api-version=5.1-preview.1')
    }
    else {
        $url = ($url + '&api-version=5.1-preview.1')
    }

    # If no out
    if ($outfile -eq '' -or $null -eq $outfile) {
        if ($GetContents.IsPresent) {
            $TempPath = (Join-Path $env:TEMP ([System.Guid]::NewGuid().ToString() + ".TXT"))
            Invoke-RestMethod -Uri $url -Method Get -ContentType '*/*' -Headers $header -OutFile $TempPath
            $result = Get-Content $TempPath -Raw
            [IO.File]::Delete($TempPath)
            $result
        }
        else
        {
            $result = Invoke-RestMethod -Uri $url -Method Get -ContentType 'application/json' -Headers $header
            $result
        }
    }
    else {
        Invoke-RestMethod -Uri $url -Method Get -ContentType '*/*' -Headers $header -OutFile $outfile
        $outfile
    }
}