Functions/PersonalAccessToken/Test-FpsAzDoPat.ps1

<#
.SYNOPSIS
    Test if a given Personal Access Token has access to Azure DevOps projects overview for a specific organisation.
.DESCRIPTION
    Test if a given Personal Access Token has access to Azure DevOps projects overview for a specific organisation.
    Returns true when there is access and false if there is no access.
    When there is no access the error will be logged in a warning message.
.EXAMPLE
    Test-FpsAzDoPat -PersonalAccessToken (Get-FpsAzDoPat -AzDoPatMethod 'CredentialManager' -CredentialName 'PowershellPATAzureDevOps')
.EXAMPLE
    Test-FpsAzDoPat -PersonalAccessToken 'ff34885a8624460a8555y03w1shth12wa2va11d' -AzDoOrganisation 'dummy'
#>


function Test-FpsAzDoPat {
    [cmdletbinding()]
    Param (
        [parameter(Mandatory=$true)]
        [string] $PersonalAccessToken,
        [string] $AzDoOrganisation = '4psnl'
    )
    
    $uri = 'https://dev.azure.com/{0}/_apis/projects/?api-version=4.1' -f $AzDoOrganisation
    $header = 'Basic {0}' -f [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes((':{0}' -f $personalAccessToken)))
    $header = @{Authorization = $header }

    try {
        $Response = Invoke-RestMethod `
                        -Uri $uri `
                        -Headers $header `
                        -ErrorAction Stop
        
        if($Response.GetType().Name -eq 'PSCustomObject'){
            return $true
        }

    } catch {
        if ($_.Exception.Response.StatusCode -ieq 'Unauthorized') {
            Write-Warning 'Azure DevOps Personal Access Token is not valid or expired.'
            return $false
        }
        Write-Warning ('Web request failed to following uri: {0}' -f $uri)
        Write-Warning $Error[0]
    }
    
    return $false
}

Export-ModuleMember -Function Test-FpsAzDoPat