Common.ps1

<#
.SYNOPSIS
    This script consists of common functions.
 
.DESCRIPTION
    This script consists of variables for rest end points and function to authenticate the user, handle error.
 
#>


# global variables
$global:bearerToken = $null

# Function to test whether argument is a valid Json
function Test-If-Json($_)
{
    Try
    {
        $_ | Test-Json
        return $True
    }
    Catch
    {
        return $False
    }
}

# Format and print errors in specific template
function Register-Error($_)
{
    
    if ([bool]($_.Exception.PSobject.Properties.name -match "Response"))
    {
        Write-Output "The error received is - $($_.Exception)"
    }
    else
    {
        Write-Output "The HTTP Status code received is - $($_.Exception.Response.ReasonPhrase)"
        if(Test-If-Json($_))
        {
            $scriptError = $($_) | ConvertFrom-Json
            Write-Output $scriptError.message
            Write-Output "Error Code - " $scriptError.code
        }
        else
        {
            $($_.Exception.Response.Content)
        }
    }
}

# Function to authenticate user
function Authenticate($tempEnv) {

    Try
    {
        if (-not(Get-Module -ListAvailable -Name MSAL.ps))
        {
            Install-Module -Name MSAL.ps -AllowClobber -Confirm:$False -Force
        }
        Import-Module MSAL.ps
        $tenantId = 'common'
        $clientId =  $(Get-Content "$PSScriptRoot/config.json" | ConvertFrom-Json).$tempEnv.clientId 
        Write-Output "If the interactive login screen appeared, please sign-in."
        $Token = Get-MsalToken -ClientId $clientId -TenantId $tenantId -Scope 'https://graph.microsoft.com/User.Read'
        Write-Output "Authentication successful."
        $global:bearerToken = 'Bearer ' + $Token.IdToken
    }
    Catch
    {
        Write-Output "Authentication failed."
        throw $_.Exception
    }
}