Public/Connect-ChangeEmailAgent.ps1

<#
.DESCRIPTION
    Connects to the ChangeEmailAgent service.

.SYNOPSIS
    Connects to the ChangeEmailAgent service.

.EXAMPLE
    Import-Module EntraIDAccessToken
    Import-Module ChangeEmailAgent

    Add-EntraIDClientSecretAccessTokenProfile `
        -Resource "api://c61cb4dd-35bf-4db9-b152-58e223782c11/" `
        -TenantId "bb73082a-b74c-4d39-aec0-41c77d6f4850" `
        -ClientId "78f07963-ce55-4b23-b56a-2e13f2036d7f"

    Connect-ChangeEmailAgent -TenantID "bb73082a-b74c-4d39-aec0-41c77d6f4850" `
        -Hostname "dev-api.byfortytwo.com" `
        -AgentID "7931eafe-21fa-4f3f-8280-968f50647e2e" `
        -Verbose
#>

function Connect-ChangeEmailAgent {
    [CmdletBinding()]

    Param(
        # Access token profile to use for authentication. the EntraIDAccessToken module must be installed and imported.
        [Parameter(Mandatory = $false)]
        [string]$AccessTokenProfile = "default",

        # Hostname of the Fortytwo API service
        [Parameter(Mandatory = $false)]
        [ValidateScript({ $_ -like "dev-api.byfortytwo.com" -or $_ -like "api.fortytwo.io" -or $_ -match "^localhost:[0-9]+$" })]
        [string]$Hostname = "api.fortytwo.io"
    )

    Process {
        $Script:AccessTokenProfile = $AccessTokenProfile
        $Script:Hostname = $Hostname
        $TenantID = (Get-EntraIDAccessTokenProfile -Profile $AccessTokenProfile).TenantId

        if(!(Get-EntraIDAccessToken | Get-EntraIDAccessTokenHasRoles -Roles "changeemail.changerequest.readwrite.all")) {
            Write-Warning "The access token profile '$AccessTokenProfile' does not have the required role 'changeemail.changerequest.readwrite.all'. Please ensure the profile is correct and has the necessary permissions."
            Write-EventLog -LogName "Application" -Source "ChangeEmailAgent" -EventId 1106 -EntryType Warning -Message "The access token profile '$AccessTokenProfile' does not have the required role 'changeemail.changerequest.readwrite.all'. Please ensure the profile is correct and has the necessary permissions."
        }

        Write-EventLog -LogName "Application" -Source "ChangeEmailAgent" -EventId 1103 -EntryType Information -Message "Connecting ChangeEmailAgent $($PSCmdlet.MyInvocation.MyCommand.ScriptBlock.Module.Version?.ToString()) to Hostname $($Script:Hostname) and TenantID $($TenantID)" -ErrorAction Continue
    }
}