Private/PartnerActions/Set-SAMConsent.ps1

function Set-SAMConsent {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [String]
        $CustomerTenantId,
        [Parameter()]
        [bool]$Retry
    )
    # Get SAM tokens if not already available
    begin {
        if (!$SAMTokens) {
            $SAMTokens = Get-SAMTokens
        }  
    }
    process {
        # Get the access token needed for subsequent requests
        $AccessToken = New-CustomPartnerAccessToken -Scopes "https://api.partnercenter.microsoft.com/user_impersonation" -TenantId $PartnerTenantId
        $AuthHeader = @{
            Authorization = "Bearer $($AccessToken.access_token)"
            Accept      = 'application/json'
        }
        try {
            # Get the relevant customer
            $Customers = (Invoke-RestMethod -Uri "https://api.partnercenter.microsoft.com/v1/customers?size=9999" -Headers $AuthHeader).items
            $Customer = $Customers | Where-Object { $_.companyProfile.tenantId -eq $CustomerTenantId }
        } catch {
            throw "Failed to find customer with ID $($CustomerTenantId): $_"
        }

        $ConsentBody = @{
            applicationGrants = @(
                @{
                    enterpriseApplicationid = "00000003-0000-0000-c000-000000000000"
                    scope = "Application.ReadWrite.All,AppRoleAssignment.ReadWrite.All,AuditLog.Read.All,BitlockerKey.Read.All,Channel.Create,Channel.Create,Channel.Delete.All,Channel.ReadBasic.All,ChannelMember.ReadWrite.All,ChannelMessage.Edit,ChannelMessage.Read.All,ChannelMessage.Send,ChannelSettings.ReadWrite.All,ConsentRequest.Read.All,CrossTenantInformation.ReadBasic.All,DelegatedAdminRelationship.ReadWrite.All,Device.Command,Device.Read,Device.ReadWrite.All,DeviceLocalCredential.Read.All,DeviceManagementApps.ReadWrite.All,DeviceManagementConfiguration.ReadWrite.All,DeviceManagementManagedDevices.PrivilegedOperations.All,DeviceManagementManagedDevices.ReadWrite.All,DeviceManagementRBAC.ReadWrite.All,DeviceManagementServiceConfig.ReadWrite.All,Directory.AccessAsUser.All,Directory.ReadWrite.All,Domain.Read.All,Domain.Read.All,Files.ReadWrite.All,Group.Create,Group.Read.All,Group.ReadWrite.All,Group.ReadWrite.All,GroupMember.ReadWrite.All,GroupMember.ReadWrite.All,Mail.Send,Mail.Send,Mail.Send.Shared,Member.Read.Hidden,offline_access,openid,Organization.ReadWrite.All,Policy.Read.All,Policy.ReadWrite.ApplicationConfiguration,Policy.ReadWrite.AuthenticationFlows,Policy.ReadWrite.AuthenticationMethod,Policy.ReadWrite.Authorization,Policy.ReadWrite.ConditionalAccess,Policy.ReadWrite.ConditionalAccess,Policy.ReadWrite.ConsentRequest,Policy.ReadWrite.ConsentRequest,Policy.ReadWrite.CrossTenantAccess,Policy.ReadWrite.DeviceConfiguration,Policy.ReadWrite.MobilityManagement,Policy.ReadWrite.IdentityProtection,PrivilegedAccess.Read.AzureResources,PrivilegedAccess.ReadWrite.AzureADGroup,PrivilegedAccess.ReadWrite.AzureResources,profile,Reports.Read.All,ReportSettings.ReadWrite.All,RoleManagement.ReadWrite.Directory,SecurityActions.ReadWrite.All,SecurityEvents.Read.All,SecurityEvents.ReadWrite.All,SecurityIncident.Read.All,SecurityIncident.ReadWrite.All,ServiceHealth.Read.All,ServiceMessage.Read.All,SharePointTenantSettings.ReadWrite.All,Sites.FullControl.All,Sites.ReadWrite.All,Team.Create,Team.ReadBasic.All,TeamMember.ReadWrite.All,TeamMember.ReadWriteNonOwnerRole.All,TeamsActivity.Read,TeamsActivity.Send,TeamsAppInstallation.ReadForChat,TeamsAppInstallation.ReadForTeam,TeamsAppInstallation.ReadForUser,TeamsAppInstallation.ReadWriteForChat,TeamsAppInstallation.ReadWriteForTeam,TeamsAppInstallation.ReadWriteForUser,TeamsAppInstallation.ReadWriteSelfForChat,TeamsAppInstallation.ReadWriteSelfForTeam,TeamsAppInstallation.ReadWriteSelfForUser,TeamSettings.Read.All,TeamSettings.ReadWrite.All,TeamsTab.Create,TeamsTab.Read.All,TeamsTab.ReadWrite.All,TeamsTab.ReadWriteForChat,TeamsTab.ReadWriteForTeam,TeamsTab.ReadWriteForUser,ThreatAssessment.ReadWrite.All,UnifiedGroupMember.Read.AsGuest,User.ManageIdentities.All,User.ReadWrite.All,UserAuthenticationMethod.ReadWrite,UserAuthenticationMethod.ReadWrite.All"
                },
                @{
                    enterpriseApplicationid = "00000002-0000-0ff1-ce00-000000000000"
                    scope = "Exchange.Manage,Exchange.ManageAsApp"
                },
                @{
                    enterpriseApplicationid = "00000003-0000-0ff1-ce00-000000000000"
                    scope = "AllSites.FullControl"
                },
                @{
                    enterpriseApplicationid = "48ac35b8-9aa8-4d74-927d-1f4a14a0b239"
                    scope = "user_impersonation"
                },
                @{
                    enterpriseApplicationid = "c5393580-f805-4401-95e8-94b7a6ef2fc2"
                    scope = "ActivityFeed.Read"
                },
                @{
                    enterpriseApplicationid = "fc780465-2017-40d4-a0c5-307022471b92"
                    scope = "Vulnerability.Read,Vulnerability.Read.All"
                },
                @{
                    enterpriseApplicationid = "fc780465-2017-40d4-a0c5-307022471b92"
                    scope = "Directory.AccessAsUser.All,Directory.Read.All,User.Read"
                })
                applicationId = "$($SAMTokens.ApplicationId)"
                displayName = 'Jysk IT - SAM Partner Application'
        } | ConvertTo-Json

        $AppCreationResponse = Invoke-RestMethod -Uri "https://api.partnercenter.microsoft.com/v1/customers/$CustomerTenantId/applicationconsents" -Method POST -ContentType 'application/json' -Body $ConsentBody  -Headers $AuthHeader -SkipHttpErrorCheck -StatusCodeVariable StatusCode
        
        switch($StatusCode) {
            {$_ -eq "200" -or $_ -eq "201"} {
                Write-Host "Successfully created consent for $($Customer.companyProfile.companyName)" -ForegroundColor Green
                Write-Host "Waiting 60 seconds for consent to propogate fully..." -foregroundcolor yellow
                Start-Sleep -Seconds 60
            }
            409 {
                Write-Host "Consent already exists for $($Customer.companyProfile.companyName)" -ForegroundColor Yellow
                if(!$Retry) {
                    Write-Host "Trying to delete and recreate, in case customer has gotten new licenses (e.g. Teams, Exchange Online)..." -ForegroundColor Yellow
                    $ConsentUri = "https://api.partnercenter.microsoft.com/v1/customers/$CustomerTenantId/applicationconsents/$($SAMTokens.ApplicationId)"
                    Invoke-Restmethod -Uri $ConsentUri -Method DELETE -ContentType 'application/json' -Headers $AuthHeader -SkipHttpErrorCheck | Out-Null
                    Set-SAMConsent -CustomerTenantId $CustomerTenantId -Retry:$true
                }
            }
            400 {
                # This just means, that one of the applications we are trying to get consent for, does not exist in the tenant.
                # Microsoft still creates the consent for the applications that do exist, so we can ignore this error.
                if($AppCreationResponse.message -like "*doesnt exist in customer tenant*") {
                    Write-Host "Successfully created consent for $($Customer.companyProfile.companyName)" -ForegroundColor Green
                    Write-Host "Waiting 60 seconds for consent to propogate fully..." -foregroundcolor yellow
                    Start-Sleep -Seconds 60
                } else {
                    throw "Failed to create consent for $($Customer.companyProfile.companyName): $($_)"
                }
            }
            default {
                throw "Failed to create consent for $($Customer.companyProfile.companyName): $AppCreationResponse"
            }
        }
    }
}