Grant-TDCErhvervSecurityInsightsPermissions.ps1


<#PSScriptInfo
 
.VERSION 1.1.3
 
.GUID 67360e4e-8199-4421-b900-ea9183686fd0
 
.AUTHOR TDC Erhverv
 
.COMPANYNAME
 
.COPYRIGHT
 
.TAGS TDC Security Insights Entra Microsoft365
 
.LICENSEURI
 
.PROJECTURI
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
 
 
.PRIVATEDATA
 
#>


<#
 
.DESCRIPTION
 Configures TDC Erhverv Security Insights permissions in your tenant.
 
#>
 


<#
.SYNOPSIS
    Configures the permissions TDC Erhverv Security Insights needs in your tenant.

.DESCRIPTION
    TDC Erhverv Security Insights uses a set of enterprise applications (modules) to read the security configuration
    of your Microsoft 365 and Azure environments. Admin consent for their API permissions is given when the
    applications are added to your tenant. Some services need additional permissions that cannot be granted through
    consent; this script grants those for every module that is present in your tenant:

    - Microsoft Teams: Assigns the Entra ID role Teams Administrator.
    - Microsoft Azure: Assigns the Azure role Reader on the tenant root management group (or on every
                                subscription when there is no access to it) and on Microsoft Entra ID diagnostic settings.
    - Microsoft Exchange Online: Assigns the Entra ID role Security Reader and the Exchange Online roles
                                View-Only Configuration and View-Only Recipients.
    - Microsoft Power Platform: Registers the module as a Power Platform management application.
    - Microsoft Power BI: Adds the module to the security group "TDC Erhverv Security Insights Analytics - MS Power BI"
                                and allows that group to use the read-only Power BI admin APIs.

    The other modules (Entra, SharePoint, Intune, Defender, Forms and Entra ID Governance) only need admin consent and
    are not configured by this script.

    Modules that are not present in the tenant, or not selected with -ModulesToConfigure, are skipped. The script can safely be run again; existing permissions are
    left unchanged.

    You sign in interactively with your own account through the enterprise application
    "TDC Erhverv Security Insights Configuration", which can be removed from Entra ID when the script has completed.
    In Azure Cloud Shell the signed-in Cloud Shell account is used instead.

.PARAMETER Force
    Forces a new interactive sign-in with the consent prompt, instead of reusing a cached sign-in.
    Use it to sign in with a different account, or to consent to APIs that were added to
    "TDC Erhverv Security Insights Configuration" since you last ran the script.

.PARAMETER ModulesToConfigure
    The modules to configure. Defaults to all modules. Modules without additional permission requirements
    (MSEntra, MSSharepoint, MSIntune, MSDefender, MSForms and MSEntraIDGovernance) are accepted but need no configuration.

.EXAMPLE
    Grant-TDCErhvervSecurityInsightsPermissions

    Configures the permissions for all modules in the tenant.

.EXAMPLE
    Grant-TDCErhvervSecurityInsightsPermissions -ModulesToConfigure MSAzure, MSTeams

    Only configures the permissions for the Microsoft Azure and Microsoft Teams modules.

.EXAMPLE
    Grant-TDCErhvervSecurityInsightsPermissions -Force -Verbose

    Signs in again with the consent prompt and shows detailed progress, including the reason when a module fails.

.NOTES

.LINK
    https://www.powershellgallery.com/packages/Grant-TDCErhvervSecurityInsightsPermissions
#>

[CmdletBinding()]
param(
    [Switch]$Force,
    [ValidateSet('MSEntra', 'MSExchangeOnline', 'MSTeams', 'MSAzure', 'MSPowerPlatform', 'MSPowerBi', 'MSSharepoint', 'MSIntune', 'MSDefender', 'MSForms', 'MSEntraIDGovernance')]
    [String[]]$ModulesToConfigure
)

function ConvertTo-SecureStringFromPlainText {
    <#
    .SYNOPSIS
        Converts a plain text string to a read-only SecureString.

    .DESCRIPTION
        Used to pass access tokens to cmdlets that only accept a SecureString (e.g. Connect-MgGraph -AccessToken).

    .PARAMETER PlainText
        The string to convert.

    .EXAMPLE
        $SecureToken = $AccessToken | ConvertTo-SecureStringFromPlainText
    #>

    param (
        [Parameter(Mandatory, ValueFromPipeline)]
        [String]$PlainText
    )
    $SecureString = New-Object System.Security.SecureString
    $PlainText.ToCharArray() | ForEach-Object { $SecureString.AppendChar($_) }
    $SecureString.MakeReadOnly()
    return $SecureString
}
function Initialize-TDCErhvervSecurityInsightsMsalPackages {
    <#
    .SYNOPSIS
        Loads the Microsoft Authentication Library (MSAL) assemblies used for interactive sign-in.

    .DESCRIPTION
        Installs the NuGet packages Microsoft.Identity.Client and Microsoft.IdentityModel.Abstractions for the current
        user if they are missing, and loads them into the session. The Abstractions version depends on the PowerShell
        edition (8.8.0 for PowerShell 7, 6.35.0 for Windows PowerShell 5.1).

    .EXAMPLE
        Initialize-TDCErhvervSecurityInsightsMsalPackages
    #>

    try {
        if ($PSVersionTable.PSEdition -eq 'Core') {
            $MicrosoftIdentityModelAbstractionsVersion = '8.8.0'
        } else {
            $MicrosoftIdentityModelAbstractionsVersion = '6.35.0'
        }
        $MicrosoftIdentityModelAbstractions = Get-Package -Name 'Microsoft.IdentityModel.Abstractions' -RequiredVersion $MicrosoftIdentityModelAbstractionsVersion -WarningAction SilentlyContinue -ErrorAction Stop
        $MicrosoftIdentityClient = Get-Package -Name 'Microsoft.Identity.Client' -RequiredVersion '4.70.2' -WarningAction SilentlyContinue -ErrorAction Stop
    } catch {
        Install-Package -Scope CurrentUser -Source 'https://www.nuget.org/api/v2' -Name 'Microsoft.IdentityModel.Abstractions' -RequiredVersion $MicrosoftIdentityModelAbstractionsVersion -Force -WarningAction SilentlyContinue -ErrorAction Stop | Out-Null
        Install-Package -Scope CurrentUser -Source 'https://www.nuget.org/api/v2' -Name 'Microsoft.Identity.Client' -RequiredVersion '4.70.2' -Force -WarningAction SilentlyContinue -ErrorAction Stop | Out-Null
        $MicrosoftIdentityModelAbstractions = Get-Package -Name 'Microsoft.IdentityModel.Abstractions' -RequiredVersion $MicrosoftIdentityModelAbstractionsVersion -WarningAction SilentlyContinue -ErrorAction Stop
        $MicrosoftIdentityClient = Get-Package -Name 'Microsoft.Identity.Client' -RequiredVersion '4.70.2' -WarningAction SilentlyContinue -ErrorAction Stop
    }
    $MicrosoftIdentityModelAbstractionsPath = $MicrosoftIdentityModelAbstractions.Source | Split-Path | Join-Path -ChildPath 'lib\net472\Microsoft.IdentityModel.Abstractions.dll'
    $MicrosoftIdentityClientPath = $MicrosoftIdentityClient.Source | Split-Path | Join-Path -ChildPath 'lib\net472\Microsoft.Identity.Client.dll'
    Add-Type -Path $MicrosoftIdentityModelAbstractionsPath -WarningAction SilentlyContinue -ErrorAction Stop
    Add-Type -Path $MicrosoftIdentityClientPath -WarningAction SilentlyContinue -ErrorAction Stop
}
function Initialize-TDCErhvervSecurityInsightsMsalApp {
    <#
    .SYNOPSIS
        Creates the MSAL public client application used to sign in the administrator.

    .DESCRIPTION
        Loads the MSAL assemblies and stores the client application in $Script:ClientApplication, which is used by
        Get-TDCErhvervSecurityInsightsToken. Must be called before requesting tokens outside Azure Cloud Shell.

    .PARAMETER ClientId
        Application ID of the enterprise application "TDC Erhverv Security Insights Configuration".

    .PARAMETER RedirectUri
        Redirect URI registered on the application for public (native) clients.

    .EXAMPLE
        Initialize-TDCErhvervSecurityInsightsMsalApp
    #>

    param (
        [String]$ClientId = '81e6c433-88f4-490b-9266-f266a1f89c55',
        [String]$RedirectUri = 'https://login.microsoftonline.com/common/oauth2/nativeclient'
    )
    Initialize-TDCErhvervSecurityInsightsMsalPackages
    $Script:ClientApplication = [Microsoft.Identity.Client.PublicClientApplicationBuilder]::Create($ClientId).WithRedirectUri($RedirectUri).Build()
}
function Get-TDCErhvervSecurityInsightsToken {
    <#
    .SYNOPSIS
        Gets an access token for the signed-in administrator.

    .DESCRIPTION
        In Azure Cloud Shell the token is requested with Get-AzAccessToken for the Cloud Shell account.
        Elsewhere MSAL is used: the cached sign-in is reused silently, and the user is asked to sign in interactively
        (with the consent prompt) when there is no cached sign-in, when -Force is specified, or when silent sign-in is
        not possible for the requested resource.

        Returns an object with AccessToken (string), SecureAccessToken (SecureString) and AccountId (user principal name).

    .PARAMETER Scope
        The scope to request a token for, e.g. 'https://management.azure.com/.default'. Defaults to Microsoft Graph.

    .PARAMETER Force
        Always sign in interactively with the consent prompt, instead of reusing the cached sign-in.

    .EXAMPLE
        $Authentication = Get-TDCErhvervSecurityInsightsToken -Scope 'https://management.azure.com/.default'
        $Headers = @{ Authorization = "Bearer $($Authentication.AccessToken)" }
    #>

    param(
        [String]$Scope = 'https://graph.microsoft.com/.default',
        [Switch]$Force
    )
    try {
        if ($env:AZUREPS_HOST_ENVIRONMENT -like 'cloud-shell/*') {
            $TaskAuthenticationResult = Get-AzAccessToken -ResourceUrl $Scope -AsSecureString -WarningAction Ignore -ErrorAction Stop
            $AuthenticationResult = [PSCustomObject]@{
                AccessToken       = [System.Net.NetworkCredential]::new('', $TaskAuthenticationResult.Token).Password
                SecureAccessToken = $TaskAuthenticationResult.Token
                AccountId         = $TaskAuthenticationResult.UserId
            }
        } else {
            if (-not $Script:ClientApplication) {
                throw 'ClientApplication not initialized. Please call Initialize-TDCErhvervSecurityInsightsMsalApp first.'
            }
            [Microsoft.Identity.Client.IAccount]$Account = $Script:ClientApplication.GetAccountsAsync().GetAwaiter().GetResult() | Select-Object -First 1
            [String[]]$Scope = $Scope
            if ($Account -and -not $Force) {
                $AquireTokenParameters = $Script:ClientApplication.AcquireTokenSilent($Scope, $Account)
            } else {
                $AquireTokenParameters = $Script:ClientApplication.AcquireTokenInteractive($Scope).WithPrompt([Microsoft.Identity.Client.Prompt]::Consent)
            }
            $TokenSource = New-Object System.Threading.CancellationTokenSource
            $TaskAuthenticationResult = $AquireTokenParameters.ExecuteAsync($TokenSource.Token)
            try {
                if (!$Timeout) {
                    $Timeout = [System.TimeSpan]::Zero
                }
                $EndTime = [System.DateTime]::Now.Add($Timeout)
                while (!$TaskAuthenticationResult.IsCompleted) {
                    if ($Timeout -eq [System.TimeSpan]::Zero -or [System.DateTime]::Now -lt $EndTime) {
                        Start-Sleep -Seconds 1
                    } else {
                        $TokenSource.Cancel()
                        try { $TaskAuthenticationResult.Wait() }
                        catch { }
                        Write-Error -Exception (New-Object System.TimeoutException) -Category ([System.Management.Automation.ErrorCategory]::OperationTimeout) -CategoryActivity $MyInvocation.MyCommand -ErrorId 'GetMsalTokenFailureOperationTimeout' -TargetObject $Script:ClientApplication -ErrorAction Stop
                    }
                }
            } finally {
                if (!$TaskAuthenticationResult.IsCompleted) {
                    $TokenSource.Cancel()
                }
                $TokenSource.Dispose()
            }
            if ($TaskAuthenticationResult.IsFaulted) {
                Write-Error -Exception $TaskAuthenticationResult.Exception.InnerException -Category ([System.Management.Automation.ErrorCategory]::AuthenticationError) -CategoryActivity $MyInvocation.MyCommand -ErrorId 'GetMsalTokenFailureAuthenticationError' -TargetObject $Script:ClientApplication -ErrorAction Stop
            }
            if ($TaskAuthenticationResult.IsCanceled) {
                Write-Error -Exception (New-Object System.Threading.Tasks.TaskCanceledException $TaskAuthenticationResult) -Category ([System.Management.Automation.ErrorCategory]::OperationStopped) -CategoryActivity $MyInvocation.MyCommand -ErrorId 'GetMsalTokenFailureOperationStopped' -TargetObject $Script:ClientApplication -ErrorAction Stop
            } else {
                $AuthenticationResult = [PSCustomObject]@{
                    AccessToken       = $TaskAuthenticationResult.Result.AccessToken
                    SecureAccessToken = $TaskAuthenticationResult.Result.AccessToken | ConvertTo-SecureStringFromPlainText
                    AccountId         = $TaskAuthenticationResult.Result.Account.Username
                }
            }
        }
        return $AuthenticationResult
    } catch {
        throw
    }
}
function Grant-TDCErhvervSecurityInsightsPermissions {
    <#
    .SYNOPSIS
        Grants the additional permissions every TDC Erhverv Security Insights module in the tenant needs.

    .DESCRIPTION
        Signs in the administrator, finds the TDC Erhverv Security Insights modules (enterprise applications) in the
        tenant and configures each of them: Microsoft Teams, Microsoft Azure, Microsoft Exchange Online,
        Microsoft Power Platform and Microsoft Power BI. Modules that are not present or not selected are skipped, and a
        failing module does not stop the others. See the help of the script for what is granted per module.

    .PARAMETER Force
        Sign in interactively with the consent prompt, instead of reusing the cached sign-in.

    .PARAMETER ModulesToConfigure
        The modules to configure. Defaults to all modules. Modules without additional permission requirements are
        accepted but need no configuration.

    .EXAMPLE
        Grant-TDCErhvervSecurityInsightsPermissions -ModulesToConfigure MSAzure, MSTeams -Verbose
    #>

    [CmdletBinding(SupportsShouldProcess = $true)]
    param(
        [Switch]$Force = $false,
        # The consented modules to configure. Modules without additional permission requirements are accepted but need no configuration.
        [ValidateSet('MSEntra', 'MSExchangeOnline', 'MSTeams', 'MSAzure', 'MSPowerPlatform', 'MSPowerBi', 'MSSharepoint', 'MSIntune', 'MSDefender', 'MSForms', 'MSEntraIDGovernance')]
        [String[]]$ModulesToConfigure = @('MSEntra', 'MSExchangeOnline', 'MSTeams', 'MSAzure', 'MSPowerPlatform', 'MSPowerBi', 'MSSharepoint', 'MSIntune', 'MSDefender', 'MSForms', 'MSEntraIDGovernance')
    )
    try {
        try {
            if ((Get-Host -ErrorAction SilentlyContinue).UI.RawUI.BufferSize.Width -ge 114) {
                $motd = @'

 _____________________________________________________________________________________________________________________
| |
| _____________________________________ |
| /████████████████████████████████████/ ███████╗███████╗ ██████╗██╗ ██╗██████╗ ██╗████████╗██╗ ██╗ |
| /████████████████████████████████████/ ██╔════╝██╔════╝██╔════╝██║ ██║██╔══██╗██║╚══██╔══╝╚██╗ ██╔╝ |
| /████████████████████████████████████/ ███████╗█████╗ ██║ ██║ ██║██████╔╝██║ ██║ ╚████╔╝ |
| /████████████████████████████████████/ ╚════██║██╔══╝ ██║ ██║ ██║██╔══██╗██║ ██║ ╚██╔╝ |
| /████ ██ ████ ████████/ ███████║███████╗╚██████╗╚██████╔╝██║ ██║██║ ██║ ██║ |
| /████████ ███ ██ ██ ██████████/ ╚══════╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ |
| /█████████ ███ ███ █ ██████████/ |
| /██████████ ███ ██ ██ ████████/ ██╗███╗ ██╗███████╗██╗ ██████╗ ██╗ ██╗████████╗███████╗ |
| /███████████ ███ ████ ████/ ██║████╗ ██║██╔════╝██║██╔════╝ ██║ ██║╚══██╔══╝██╔════╝ |
| /████████████████████████████████████/ ██║██╔██╗ ██║███████╗██║██║ ███╗███████║ ██║ ███████╗ |
| /████████████████████████████████████/ ██║██║╚██╗██║╚════██║██║██║ ██║██╔══██║ ██║ ╚════██║ |
| /████████████████████████████████████/ ██║██║ ╚████║███████║██║╚██████╔╝██║ ██║ ██║ ███████║ |
| /████████████████████████████████████/ ╚═╝╚═╝ ╚═══╝╚══════╝╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚══════╝ |
| |
|_____________________________________________________________________________________________________________________|


'@

                Write-Host -ForegroundColor White -BackgroundColor DarkBlue $motd
            }
            Write-Host -NoNewline 'Initializing: '
            Write-Progress -Id 0 -Activity 'Configuring TDC Erhverv Security Insights permissions' -Status 'Initializing' -PercentComplete ((1 / 9) * 100) -ErrorAction SilentlyContinue
            if ($env:AZUREPS_HOST_ENVIRONMENT -notlike 'cloud-shell/*') {
                if (-not (Get-Module -Name Microsoft.Graph.Authentication -ListAvailable)) {
                    Install-Module -Name 'Microsoft.Graph.Authentication' -Scope CurrentUser -AllowClobber -Force -WarningAction SilentlyContinue -ErrorAction Stop | Out-Null
                }
                Initialize-TDCErhvervSecurityInsightsMsalApp
            }
            Write-Host -ForegroundColor Black -BackgroundColor Green -Object ' OK '
        } catch {
            Write-Host -ForegroundColor White -BackgroundColor Red -Object ' Failed '
            throw
        }
        try {
            Write-Progress -Id 0 -Activity 'Configuring TDC Erhverv Security Insights permissions' -Status 'Authenticating' -PercentComplete ((2 / 9) * 100) -ErrorAction SilentlyContinue
            Write-Host -NoNewline 'Authenticating: '
            $Authentication = Get-TDCErhvervSecurityInsightsToken -Force:$Force -ErrorAction Stop
            Connect-MgGraph -AccessToken $Authentication.SecureAccessToken -NoWelcome | Out-Null
            Write-Host -ForegroundColor Black -BackgroundColor Green -Object ' OK '
        } catch {
            Write-Host -ForegroundColor White -BackgroundColor Red -Object ' Failed '
            throw
        }
        try {
            Write-Progress -Id 0 -Activity 'Configuring TDC Erhverv Security Insights permissions' -Status 'Preparing modules' -PercentComplete ((3 / 9) * 100) -ErrorAction SilentlyContinue
            Write-Host -NoNewline 'Preparing modules: '
            $EntraIDDirectoryRoles = (Invoke-MgGraphRequest -Method GET -Uri 'https://graph.microsoft.com/v1.0/directoryRoles' -OutputType PSObject -ErrorAction Stop).value
            # Graph limits filter expressions to 15 'OR' clauses, so the appIds are queried per environment (Prod/Dev/Test) rather than in one combined filter.
            $ServicePrincipalAppIdsByEnvironment = @{
                Prod = @('59e16c46-95c2-442b-a45d-aa795c4892b7', '7d726de8-d48e-4304-9b21-f6eaf8d825e5', 'f0279a37-2a96-4d3d-8f19-d4eee0af7fc4', '80d592c4-5e3b-4469-8586-8d7a5d7fc3f6', 'dcf00d66-0307-413a-8ff6-f6dede0d584f')
                Dev  = @('44c5021d-baf4-47b5-b35f-545b8ed1d464', 'b52dcb6f-c5df-436a-ae43-c039113ad7fa', 'ddfdf184-9b52-4d19-b5e6-79c8965cd0a5', '8e507df8-4bdc-44cb-bba4-b3d9812d8576', '19641d75-3997-468f-84de-ddfa7e5e4e74')
                Test = @('79710c16-191a-407f-9566-2fc4d66e2b5a', '916027c2-ba9b-413d-bf24-06a6b1abcbf5', '41e2960f-0caf-4f1c-9aa7-26d49f9f3ea5', '1625d68a-9dd3-41a5-afdb-ac392bcc323e', '3a2b2b75-7814-4dc5-8283-42d86c920b34')
            }
            $ServicePrincipals = foreach ($Environment in $ServicePrincipalAppIdsByEnvironment.Keys) {
                $AppIdFilter = ($ServicePrincipalAppIdsByEnvironment[$Environment] | ForEach-Object { "`"$_`"" }) -join ', '
                (Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/v1.0/servicePrincipals?`$select=displayName,appId,id&`$filter=appId in ($AppIdFilter)" -OutputType PSObject -ErrorAction Stop).value
            }
            $TDCErhvervSecurityInsightsAnalyticsMSAzure = $ServicePrincipals | Where-Object { $_.AppId -in ('59e16c46-95c2-442b-a45d-aa795c4892b7', '44c5021d-baf4-47b5-b35f-545b8ed1d464','79710c16-191a-407f-9566-2fc4d66e2b5a') }
            $TDCErhvervSecurityInsightsAnalyticsMSExchangeOnline = $ServicePrincipals | Where-Object { $_.AppId -in ('7d726de8-d48e-4304-9b21-f6eaf8d825e5', 'b52dcb6f-c5df-436a-ae43-c039113ad7fa', '916027c2-ba9b-413d-bf24-06a6b1abcbf5') }
            $TDCErhvervSecurityInsightsAnalyticsMSTeams = $ServicePrincipals | Where-Object { $_.AppId -in ('f0279a37-2a96-4d3d-8f19-d4eee0af7fc4', 'ddfdf184-9b52-4d19-b5e6-79c8965cd0a5', '41e2960f-0caf-4f1c-9aa7-26d49f9f3ea5') }
            $TDCErhvervSecurityInsightsAnalyticsMSPowerPlatform = $ServicePrincipals | Where-Object { $_.AppId -in ('8e507df8-4bdc-44cb-bba4-b3d9812d8576', '80d592c4-5e3b-4469-8586-8d7a5d7fc3f6', '1625d68a-9dd3-41a5-afdb-ac392bcc323e') }
            $TDCErhvervSecurityInsightsAnalyticsMSPowerBI = $ServicePrincipals | Where-Object { $_.AppId -in ('dcf00d66-0307-413a-8ff6-f6dede0d584f', '19641d75-3997-468f-84de-ddfa7e5e4e74', '3a2b2b75-7814-4dc5-8283-42d86c920b34') }
            # Only configure the selected modules, so no PowerShell modules are installed or permissions requested for the others.
            if ('MSAzure' -notin $ModulesToConfigure) { $TDCErhvervSecurityInsightsAnalyticsMSAzure = $null }
            if ('MSExchangeOnline' -notin $ModulesToConfigure) { $TDCErhvervSecurityInsightsAnalyticsMSExchangeOnline = $null }
            if ('MSTeams' -notin $ModulesToConfigure) { $TDCErhvervSecurityInsightsAnalyticsMSTeams = $null }
            if ('MSPowerPlatform' -notin $ModulesToConfigure) { $TDCErhvervSecurityInsightsAnalyticsMSPowerPlatform = $null }
            if ('MSPowerBi' -notin $ModulesToConfigure) { $TDCErhvervSecurityInsightsAnalyticsMSPowerBI = $null }
            if ($env:AZUREPS_HOST_ENVIRONMENT -notlike 'cloud-shell/*') {
                [System.Collections.ArrayList]$ModulesToInstall = @()
                if ($TDCErhvervSecurityInsightsAnalyticsMSExchangeOnline -and -not (Get-Module -Name ExchangeOnlineManagement -ListAvailable)) {
                    $ModulesToInstall.Add('ExchangeOnlineManagement') | Out-Null
                }
                if ($TDCErhvervSecurityInsightsAnalyticsMSAzure -and -not (Get-Module -Name Az.Accounts -ListAvailable)) {
                    $ModulesToInstall.Add('Az.Accounts') | Out-Null
                }
                if ($TDCErhvervSecurityInsightsAnalyticsMSAzure -and -not (Get-Module -Name Az.Resources -ListAvailable)) {
                    $ModulesToInstall.Add('Az.Resources') | Out-Null
                }
                if ($TDCErhvervSecurityInsightsAnalyticsMSPowerPlatform -and -not (Get-Module -Name Microsoft.PowerApps.Administration.PowerShell -ListAvailable)) {
                    $ModulesToInstall.Add('Microsoft.PowerApps.Administration.PowerShell') | Out-Null
                }
                if ($ModulesToInstall.Count -gt 0) {
                    Install-Module -Name $ModulesToInstall -Scope CurrentUser -AllowClobber -Force -WarningAction SilentlyContinue -ErrorAction Stop | Out-Null
                }
            }
            Write-Host -ForegroundColor Black -BackgroundColor Green -Object ' OK '
        } catch {
            Write-Host -ForegroundColor White -BackgroundColor Red -Object ' Failed '
            throw
        }
        Write-Host -NoNewline 'Configuring module [MSTeams]: '
        if ($TDCErhvervSecurityInsightsAnalyticsMSTeams) {
            try {
                try {
                    Write-Progress -Id 0 -Activity 'Configuring TDC Erhverv Security Insights permissions' -Status 'Configuring additional permissions for Microsoft Teams' -PercentComplete ((4 / 9) * 100) -ErrorAction SilentlyContinue
                    $EntraIDDirectoryRoleTeamsReader = $EntraIDDirectoryRoles | Where-Object { $_.roleTemplateId -eq '1076ac91-f3d9-41a7-a339-dcdf5f480acc' }
                    if (-not $EntraIDDirectoryRoleTeamsReader) {
                        $EntraIDDirectoryRoleTeamsReader = Invoke-MgGraphRequest -Method POST -Uri 'https://graph.microsoft.com/v1.0/directoryRoles' -Body @{roleTemplateId = '1076ac91-f3d9-41a7-a339-dcdf5f480acc' } -OutputType PSObject -ErrorAction Stop
                        Write-Verbose -Message '[OK] Enabled Entra ID role: Teams Administrator'
                    }
                } catch {
                    Write-Verbose -Message "[Error] Failed to enable Entra ID role [Teams Administrator]: $($_.Exception.Message)"
                    throw
                }
                try {
                    $EntraIDDirectoryRoleTeamsReaderMembers = (Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/beta/directoryRoles/$($EntraIDDirectoryRoleTeamsReader.id)/members" -OutputType PSObject).value
                    foreach ($Module in $TDCErhvervSecurityInsightsAnalyticsMSTeams) {
                        if ($Module.id -notin $EntraIDDirectoryRoleTeamsReaderMembers.id) {
                            Invoke-MgGraphRequest -Method POST -Uri "https://graph.microsoft.com/v1.0/directoryRoles/$($EntraIDDirectoryRoleTeamsReader.id)/members/`$ref" -Body @{'@odata.id' = "https://graph.microsoft.com/v1.0/directoryObjects/$($Module.id)" } -OutputType PSObject -ErrorAction Stop | Out-Null
                            Write-Verbose -Message "[OK] Added Teams Administrator role to module: $($Module.id)"
                        }
                    }
                } catch {
                    Write-Verbose -Message "[Error] Failed to assign Entra ID role [Teams Administrator] to module id [$($Module.id)]: $($_.Exception.Message)"
                    throw
                }
                Write-Host -ForegroundColor Black -BackgroundColor Green -Object ' OK '
            } catch {
                Write-Host -ForegroundColor White -BackgroundColor Red -Object ' Failed '
            }
        } else {
            Write-Host -ForegroundColor Black -BackgroundColor Gray -Object ' Skipped '
        }
        Write-Host -NoNewline 'Configuring module [MSAzure]: '
        if ($TDCErhvervSecurityInsightsAnalyticsMSAzure) {
            try {
                try {
                    Write-Progress -Id 0 -Activity 'Configuring TDC Erhverv Security Insights permissions' -Status 'Configuring additional permissions for Azure' -PercentComplete ((5 / 9) * 100) -ErrorAction SilentlyContinue
                    Write-Verbose -Message 'Connecting to Azure'

                    Update-AzConfig -Scope Process -DefaultSubscriptionForLogin '' -LoginExperienceV2 Off -CheckForUpgrade $false -DisplayBreakingChangeWarning $false -DisplayRegionIdentified $false -DisplaySecretsWarning $false -DisplaySurveyMessage $false -EnableDataCollection $false -EnableErrorRecordsPersistence $false -EnableLoginByWam $false -WarningAction SilentlyContinue | Out-Null
                    $Authentication = Get-TDCErhvervSecurityInsightsToken -Scope 'https://management.azure.com/.default' -ErrorAction Stop
                    $AzAccountContext = Connect-AzAccount -AccessToken $Authentication.AccessToken -AccountId $Authentication.AccountId -WarningAction Ignore -InformationAction Ignore -ErrorAction Stop

                    $TenantId = (Get-AzContext).Tenant.Id
                    Write-Verbose -Message '[OK] Connected to Azure'
                } catch {
                    Write-Verbose -Message "[Error] Failed to connect to Azure: $($_.Exception.Message)"
                    throw
                }
                try {
                    # Use the bearer token directly for management group lookup — Connect-AzAccount
                    # -AccessToken creates a token-only session with no refresh token, so Az cmdlets
                    # that internally re-acquire tokens (e.g. Get-AzManagementGroup) will hit MFA/CA
                    # policies. Calling the REST API directly with our MSAL token avoids this entirely.
                    $AzureAuthHeader = @{ Authorization = "Bearer $($Authentication.AccessToken)" }
                    $ManagementGroups = try {
                        (Invoke-RestMethod -Method GET -Uri 'https://management.azure.com/providers/Microsoft.Management/managementGroups?api-version=2024-02-01-preview' -Headers $AzureAuthHeader -ErrorAction Stop).value
                    } catch { $null }
                    $TenantRootGroup = $ManagementGroups | Where-Object { $_.name -eq $TenantId }
                    if ($TenantRootGroup) {
                        [Array]$AssignableScopes = $TenantRootGroup.id
                    } else {
                        $Subscriptions = (Invoke-RestMethod -Method GET -Uri "https://management.azure.com/subscriptions?api-version=2025-04-01" -Headers $AzureAuthHeader -ErrorAction Stop).value
                        [Array]$AssignableScopes = $Subscriptions | Where-Object { $_.tenantId -eq $TenantId } | ForEach-Object { $_.id }
                    }
                    Write-Verbose -Message "[OK] Found $($AssignableScopes.Count) assignable scopes."
                } catch {
                    Write-Verbose -Message "[Error] Failed to get Azure assignable scopes: $($_.Exception.Message)"
                    throw
                }
                try {
                    # Use REST directly — Get/New-AzRoleAssignment also internally re-acquire tokens
                    # which fails under MFA/CA policies when using a token-only Az session.
                    $ReaderRoleDefinitionId = 'acdd72a7-3385-48ef-bd42-f606fba81ae7'
                    foreach ($Scope in $AssignableScopes) {
                        foreach ($Module in $TDCErhvervSecurityInsightsAnalyticsMSAzure) {
                            Write-Verbose -Message "Assigning Azure role [Reader] to scope: ${Scope}"
                            $ExistingAssignments = (Invoke-RestMethod -Method GET -Uri "https://management.azure.com${Scope}/providers/Microsoft.Authorization/roleAssignments?api-version=2022-04-01&`$filter=principalId eq '$($Module.id)'" -Headers $AzureAuthHeader -ErrorAction Stop).value
                            $ExistingAssignment = $ExistingAssignments | Where-Object { $_.properties.roleDefinitionId -like "*/$ReaderRoleDefinitionId" }
                            if (-not $ExistingAssignment) {
                                $RoleAssignmentId = [System.Guid]::NewGuid().ToString()
                                Invoke-RestMethod -Method PUT -Uri "https://management.azure.com${Scope}/providers/Microsoft.Authorization/roleAssignments/${RoleAssignmentId}?api-version=2022-04-01" -Headers $AzureAuthHeader -ContentType 'application/json' -Body (@{
                                        properties = @{
                                            roleDefinitionId = "${Scope}/providers/Microsoft.Authorization/roleDefinitions/${ReaderRoleDefinitionId}"
                                            principalId      = $Module.id
                                            principalType    = 'ServicePrincipal'
                                        }
                                    } | ConvertTo-Json) -ErrorAction Stop | Out-Null
                            }
                            Write-Verbose -Message "[OK] Assigned Azure role [Reader] to scope: ${Scope}"
                        }
                    }
                } catch {
                    throw "Unable to assign Azure role [Reader]: $($_.Exception.Message)"
                }
                try {
                    $Scope = '/providers/Microsoft.AADIAM'
                    foreach ($Module in $TDCErhvervSecurityInsightsAnalyticsMSAzure) {
                        Write-Verbose -Message "Assigning Azure role [Reader] to scope: ${Scope}"
                        $ExistingAssignments = (Invoke-RestMethod -Method GET -Uri "https://management.azure.com${Scope}/providers/Microsoft.Authorization/roleAssignments?api-version=2022-04-01&`$filter=principalId eq '$($Module.id)'" -Headers $AzureAuthHeader -ErrorAction Stop).value
                        $ExistingAssignment = $ExistingAssignments | Where-Object { $_.properties.roleDefinitionId -like "*/$ReaderRoleDefinitionId" }
                        if (-not $ExistingAssignment) {
                            $RoleAssignmentId = [System.Guid]::NewGuid().ToString()
                            Invoke-RestMethod -Method PUT -Uri "https://management.azure.com${Scope}/providers/Microsoft.Authorization/roleAssignments/${RoleAssignmentId}?api-version=2022-04-01" -Headers $AzureAuthHeader -ContentType 'application/json' -Body (@{
                                    properties = @{
                                        roleDefinitionId = "${Scope}/providers/Microsoft.Authorization/roleDefinitions/${ReaderRoleDefinitionId}"
                                        principalId      = $Module.id
                                        principalType    = 'ServicePrincipal'
                                    }
                                } | ConvertTo-Json) -ErrorAction Stop | Out-Null
                        }
                        Write-Verbose -Message "[OK] Assigned Azure role [Reader] to scope: ${Scope}"
                    }
                }
                catch {
                    throw "Unable to assign Azure role [Reader] on scope: ${Scope}: $($_.Exception.Message)"
                }
                Write-Host -ForegroundColor Black -BackgroundColor Green -Object ' OK '
            } catch {
                Write-Host -ForegroundColor White -BackgroundColor Red -Object " Failed: $($_.Exception.Message)"
            }
        } else {
            Write-Host -ForegroundColor Black -BackgroundColor Gray -Object ' Skipped '
        }
        Write-Host -NoNewline 'Configuring module [MSExchangeOnline]: '
        if ($TDCErhvervSecurityInsightsAnalyticsMSExchangeOnline) {
            try {
                try {
                    Write-Progress -Id 0 -Activity 'Configuring TDC Erhverv Security Insights permissions' -Status 'Configuring additional permissions for Microsoft Exchange Online' -PercentComplete ((6 / 9) * 100) -ErrorAction SilentlyContinue
                    Write-Verbose -Message 'Connecting to Exchange Online'
                    if ($env:AZUREPS_HOST_ENVIRONMENT -like 'cloud-shell/*') {
                        Connect-ExchangeOnline -ShowBanner:$false -ErrorAction Stop | Out-Null
                    } else {
                        $Authentication = Get-TDCErhvervSecurityInsightsToken -Scope 'https://outlook.office.com/.default' -ErrorAction Stop
                        Connect-ExchangeOnline -AccessToken $Authentication.AccessToken -UserPrincipalName $Authentication.AccountId -ShowBanner:$false -ErrorAction Stop | Out-Null 2>&1
                    }
                    Write-Verbose -Message '[OK] Connected to Exchange Online'
                } catch {
                    Write-Verbose -Message "[Error] Failed to connect to Exchange Online: $($_.Exception.Message)"
                    throw
                }
                try {
                    $EntraIDDirectoryRoleSecurityReader = $EntraIDDirectoryRoles | Where-Object { $_.roleTemplateId -eq '5d6b6bb7-de71-4623-b4af-96380a352509' }
                    if (-not $EntraIDDirectoryRoleSecurityReader) {
                        $EntraIDDirectoryRoleSecurityReader = Invoke-MgGraphRequest -Method POST -Uri 'https://graph.microsoft.com/v1.0/directoryRoles' -Body @{roleTemplateId = '5d6b6bb7-de71-4623-b4af-96380a352509' } -OutputType PSObject -ErrorAction Stop
                        Write-Verbose -Message '[OK] Enabled Entra ID role: Security Reader'
                    }
                } catch {
                    Write-Verbose -Message "[Error] Failed to enable Entra ID role [Security Reader]: $($_.Exception.Message)"
                    throw
                }
                try {
                    $EntraIDDirectoryRoleSecurityReaderMembers = (Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/beta/directoryRoles/$($EntraIDDirectoryRoleSecurityReader.id)/members" -OutputType PSObject).value
                    foreach ($Module in $TDCErhvervSecurityInsightsAnalyticsMSExchangeOnline) {
                        if ($Module.id -notin $EntraIDDirectoryRoleSecurityReaderMembers.id) {
                            Invoke-MgGraphRequest -Method POST -Uri "https://graph.microsoft.com/v1.0/directoryRoles/$($EntraIDDirectoryRoleSecurityReader.id)/members/`$ref" -Body @{'@odata.id' = "https://graph.microsoft.com/v1.0/directoryObjects/$($Module.id)" } -OutputType PSObject -ErrorAction Stop | Out-Null
                            Write-Verbose -Message "[OK] Assigned Security Reader role to: $($Module.id)"
                        }
                    }
                } catch {
                    Write-Verbose -Message "[Error] Failed to assign Entra ID role [Security Reader] to module id [$($Module.id)]: $($_.Exception.Message)"
                    throw
                }
                try {
                    foreach ($Module in $TDCErhvervSecurityInsightsAnalyticsMSExchangeOnline) {
                        if (-not (Get-ServicePrincipal -Identity $Module.id -ErrorAction SilentlyContinue)) {
                            New-ServicePrincipal -AppId $Module.appId -ObjectId $Module.id -DisplayName $Module.displayName -ErrorAction Stop | Out-Null
                            Write-Verbose -Message "[OK] Created Exchange Online Service Principal for module: $($Module.displayName)"
                        }
                    }
                } catch {
                    Write-Verbose -Message "[Error] Failed to create Exchange Online principal for module [$($Module.displayName)]: $($_.Exception.Message)"
                    throw
                }
                try {
                    foreach ($Module in $TDCErhvervSecurityInsightsAnalyticsMSExchangeOnline) {
                        if (-not (Get-ManagementRoleAssignment -Role 'View-Only Configuration' -RoleAssignee $Module.id -ErrorAction SilentlyContinue)) {
                            New-ManagementRoleAssignment -Name "View-Only Configuration-$($Module.appId)" -Role 'View-Only Configuration' -App $Module.displayName -ErrorAction Stop | Out-Null
                            Write-Verbose -Message "[OK] Assigned Exchange Online role [View-Only Configuration] to module: $($Module.displayName)"
                        }
                    }
                } catch {
                    Write-Verbose -Message "[Error] Failed to assign Exchange Online role [View-Only Configuration] to module [$($Module.displayName)]: $($_.Exception.Message)"
                    throw
                }
                try {
                    foreach ($Module in $TDCErhvervSecurityInsightsAnalyticsMSExchangeOnline) {
                        if (-not (Get-ManagementRoleAssignment -Role 'View-Only Recipients' -RoleAssignee $Module.id -ErrorAction SilentlyContinue)) {
                            New-ManagementRoleAssignment -Name "View-Only Recipients-$($Module.appId)" -Role 'View-Only Recipients' -App $Module.displayName -ErrorAction Stop | Out-Null
                            Write-Verbose -Message "[OK] Assigned Exchange Online role [View-Only Recipients] to module: $($Module.displayName)"
                        }
                    }
                } catch {
                    Write-Verbose -Message "[Error] Failed to assign Exchange Online role [View-Only Recipients] to module [$($Module.displayName)]: $($_.Exception.Message)"
                    throw
                }
                Write-Host -ForegroundColor Black -BackgroundColor Green -Object ' OK '
            } catch {
                Write-Host -ForegroundColor White -BackgroundColor Red -Object ' Failed '
            }
        } else {
            Write-Host -ForegroundColor Black -BackgroundColor Gray -Object ' Skipped '
        }
        Write-Host -NoNewline 'Configuring module [MSPowerPlatform]: '
        if ($TDCErhvervSecurityInsightsAnalyticsMSPowerPlatform) {
            try {
                try {
                    Write-Progress -Id 0 -Activity 'Configuring TDC Erhverv Security Insights permissions' -Status 'Configuring additional permissions for Microsoft Power Platform' -PercentComplete ((7 / 9) * 100) -ErrorAction SilentlyContinue
                    Write-Verbose 'Connecting to Power Platform'
                    $Authentication = Get-TDCErhvervSecurityInsightsToken -Scope 'https://management.azure.com/.default' -ErrorAction Stop
                    $Authorization = @{Authorization = "Bearer $($Authentication.AccessToken)" }
                    $PowerAppManagementApps = (Invoke-RestMethod -Method GET -Uri 'https://api.bap.microsoft.com/providers/Microsoft.BusinessAppPlatform/adminApplications?api-version=2020-06-01' -Headers $Authorization -ErrorAction Stop).value
                    Write-Verbose '[OK] Connected to Power Platform'
                } catch {
                    Write-Verbose -Message "[Error] Failed to connect to Power Platform: $($_.Exception.Message)"
                    throw
                }
                try {
                    foreach ($Module in $TDCErhvervSecurityInsightsAnalyticsMSPowerPlatform) {
                        if ($Module.appId -notin $PowerAppManagementApps.applicationId) {
                            Write-Verbose "Adding Power Platform management app: $($Module.appId)"
                            Invoke-RestMethod -Method PUT -Uri "https://api.bap.microsoft.com/providers/Microsoft.BusinessAppPlatform/adminApplications/$($Module.appId)?api-version=2020-06-01" -Headers $Authorization -ErrorAction Stop | Out-Null
                            Write-Verbose "[OK] Added Power Platform management app: $($Module.appId)"
                        }
                    }
                } catch {
                    Write-Verbose -Message "[Error] Failed to add Power Platform management app [$($Module.appId)]: $($_.Exception.Message)"
                    throw
                }
                Write-Host -ForegroundColor Black -BackgroundColor Green -Object ' OK '
            } catch {
                Write-Host -ForegroundColor White -BackgroundColor Red -Object ' Failed: A license is required (e.g. Power Automate Free). Please assign this to your user and try again. '
            }
        } else {
            Write-Host -ForegroundColor Black -BackgroundColor Gray -Object ' Skipped '
        }
        Write-Host -NoNewline 'Configuring module [MSPowerBI]: '
        if ($TDCErhvervSecurityInsightsAnalyticsMSPowerBI) {
            try {
                try {
                    Write-Progress -Id 0 -Activity 'Configuring TDC Erhverv Security Insights permissions' -Status 'Configuring additional permissions for Microsoft Power BI' -PercentComplete ((8 / 9) * 100) -ErrorAction SilentlyContinue
                    Write-Verbose -Message 'Connecting to Power BI'
                    $Authentication = Get-TDCErhvervSecurityInsightsToken -Scope 'https://analysis.windows.net/powerbi/api/.default' -ErrorAction Stop
                    $Authorization = @{Authorization = "Bearer $($Authentication.AccessToken)" }
                    Write-Verbose -Message '[OK] Connected to Power BI'
                } catch {
                    Write-Verbose -Message "[Error] Failed to connect to Power BI: $($_.Exception.Message)"
                    throw
                }
                try {
                    $EntraIDPowerBIGroup = (Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/v1.0/groups?`$filter=displayName eq 'TDC Erhverv Security Insights Analytics - MS Power BI'" -OutputType PSObject -ErrorAction Stop).value
                    if ($EntraIDPowerBIGroup.Count -gt 1) {
                        throw 'There are more than one group with the name: TDC Erhverv Security Insights Analytics - MS Power BI'
                    } elseif ($EntraIDPowerBIGroup) {
                        $EntraIDPowerBIGroupMembers = (Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/beta/groups/$($EntraIDPowerBIGroup.id)/members" -OutputType PSObject -ErrorAction Stop).value
                        $EntraIDPowerBIGroupMemberCompare = Compare-Object -ReferenceObject $TDCErhvervSecurityInsightsAnalyticsMSPowerBI -DifferenceObject @($EntraIDPowerBIGroupMembers | Select-Object) -Property 'appId' -PassThru
                        if ($EntraIDPowerBIGroupMemberCompare | Where-Object { $_.SideIndicator -eq '=>' }) {
                            throw 'Unknown members in Entra ID Group: TDC Erhverv Security Insights Analytics - MS Power BI'
                        } else {
                            foreach ($Module in $EntraIDPowerBIGroupMemberCompare | Where-Object { $_.SideIndicator -eq '<=' }) {
                                Invoke-MgGraphRequest -Method POST -Uri "https://graph.microsoft.com/v1.0/groups/$($EntraIDPowerBIGroup.id)/members/`$ref" -Body @{'@odata.id' = "https://graph.microsoft.com/v1.0/directoryObjects/$($Module.id)" } -OutputType PSObject -ErrorAction Stop
                                Write-Verbose -Message "[OK] Added group member to [TDC Erhverv Security Insights Analytics - MS Power BI]: $($Module.id)"
                            }
                        }
                    } else {
                        $EntraIDPowerBIGroup = Invoke-MgGraphRequest -Method POST -Uri 'https://graph.microsoft.com/v1.0/groups' -Body @{'displayName' = 'TDC Erhverv Security Insights Analytics - MS Power BI'; description = 'This group is used for allowing TDC Erhverv Security Insights read-only access to Power BI Admin API.'; mailEnabled = $false; securityEnabled = $true; mailNickname = 'NotSet' } -OutputType PSObject -ErrorAction Stop
                        do {
                            $EntraIDPowerBIGroupAttempts++
                            if ($EntraIDPowerBIGroupAttempts -gt 10) {
                                throw "Waiting for Power BI Group creation exceeded attempts: ${EntraIDPowerBIGroupAttempts}"
                            }
                            Start-Sleep -Seconds 5
                            Write-Verbose -Message "Waiting for Power BI Group creation attempt: ${EntraIDPowerBIGroupAttempts}"
                            $EntraIDPowerBIGroup = (Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/v1.0/groups?`$filter=displayName eq 'TDC Erhverv Security Insights Analytics - MS Power BI'" -OutputType PSObject -ErrorAction SilentlyContinue).value
                        } while (-not $EntraIDPowerBIGroup)
                        Write-Verbose -Message '[OK] Created Entra ID group: TDC Erhverv Security Insights Analytics - MS Power BI'
                        foreach ($Module in $TDCErhvervSecurityInsightsAnalyticsMSPowerBI) {
                            Invoke-MgGraphRequest -Method POST -Uri "https://graph.microsoft.com/v1.0/groups/$($EntraIDPowerBIGroup.id)/members/`$ref" -Body @{'@odata.id' = "https://graph.microsoft.com/v1.0/directoryObjects/$($Module.id)" } -OutputType PSObject -ErrorAction Stop | Out-Null
                            Write-Verbose -Message "[OK] Added group member: $($Module.id)"
                        }
                    }
                } catch {
                    Write-Verbose -Message "[Error] Failed to configure Entra ID group [TDC Erhverv Security Insights Analytics - MS Power BI]: $($_.Exception.Message)"
                    throw
                }
                try {
                    $PowerBIAdminAPISettings = Invoke-RestMethod -UseBasicParsing -Uri 'https://api.fabric.microsoft.com/v1/admin/tenantsettings' -Method 'GET' -Headers $Authorization -ContentType 'application/json;charset=UTF-8' -ErrorAction Stop
                    if ($EntraIDPowerBIGroup.id -notin $PowerBIAdminAPISettings.tenantSettings.Where({ $_.settingName -eq 'AllowServicePrincipalsUseReadAdminAPIs' }).enabledSecurityGroups.graphId) {
                        $PowerBIAdminAPIAllowedSecurityGroups = New-Object System.Collections.ArrayList($null)
                        if ($PowerBIAdminAPISettings.tenantSettings.Where({ $_.settingName -eq 'AllowServicePrincipalsUseReadAdminAPIs' }).enabledSecurityGroups.graphId) {
                            $PowerBIAdminAPIAllowedSecurityGroups.AddRange(@($PowerBIAdminAPISettings.tenantSettings.Where({ $_.settingName -eq 'AllowServicePrincipalsUseReadAdminAPIs' }).enabledSecurityGroups))
                        }
                        $PowerBIAdminAPIAllowedSecurityGroups.Add([PSCustomObject]@{graphId = $EntraIDPowerBIGroup.id; name = $EntraIDPowerBIGroup.DisplayName }) | Out-Null
                        Invoke-RestMethod -UseBasicParsing -Uri 'https://api.fabric.microsoft.com/v1/admin/tenantsettings/AllowServicePrincipalsUseReadAdminAPIs/update' -Method 'POST' -Headers $Authorization -ContentType 'application/json;charset=UTF-8' -Body "{`"enabled`": true,`"enabledSecurityGroups`": $(ConvertTo-Json -InputObject $PowerBIAdminAPIAllowedSecurityGroups -Compress)}" -ErrorAction Stop | Out-Null
                        Write-Verbose -Message '[OK] Added security group'
                    }
                } catch {
                    Write-Verbose -Message "[Error] Failed to add security group [TDC Erhverv Security Insights Analytics - MS Power BI] to [Service principals can access read-only admin APIs]: $($_.Exception.Message)"
                    throw
                }
                Write-Host -ForegroundColor Black -BackgroundColor Green -Object ' OK '
            } catch {
                Write-Host -ForegroundColor White -BackgroundColor Red -Object ' Failed: A license is required (e.g. Microsoft Fabric Free). Please assign this to your user and try again. '
            }
        } else {
            Write-Host -ForegroundColor Black -BackgroundColor Gray -Object ' Skipped '
        }
        if ($env:AZUREPS_HOST_ENVIRONMENT -notlike 'cloud-shell/*') {
            Write-Host -Object 'The enterprise registered application "TDC Erhverv Security Insights Configuration" should be removed from Entra ID.'
        }
    } catch {
        throw
    } finally {
        #Disconnect-MgGraph -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null
        #$AzAccountContext | Disconnect-AzAccount -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null
        #Disconnect-ExchangeOnline -Confirm:$false -WarningAction SilentlyContinue -ErrorAction SilentlyContinue | Out-Null
    }
}

Grant-TDCErhvervSecurityInsightsPermissions @PSBoundParameters