$TenantID = "721c10dd-5f6e-43e5-9c8c-3a19c09632d2" $ManagedIdentity = "cqre-intune" $Permissions = @( "DeviceManagementManagedDevices.Read.All", "DeviceManagementManagedDevices.ReadWrite.All", "AuditLog.Read.All", "User.Read.All", "Group.Read.All", "Directory.Read.All" ) $GraphAppId = "00000003-0000-0000-c000-000000000000" Connect-AzureAD -TenantId $TenantID $ManagedIdentityServicePrincipal = Get-AzureADServicePrincipal -Filter "displayName eq '$ManagedIdentity'" $GraphServicePrincipal = Get-AzureADServicePrincipal -Filter "appId eq '$GraphAppId'" foreach ($Permission in $Permissions) { $AppRole = $GraphServicePrincipal.AppRoles | Where-Object { $_.Value -eq $Permission -and $_.AllowedMemberTypes -contains "Application" } $ExistingAssignment = Get-AzureADServiceAppRoleAssignment -ObjectId $ManagedIdentityServicePrincipal.ObjectId | Where-Object { $_.ResourceId -eq $GraphServicePrincipal.ObjectId -and $_.Id -eq $AppRole.Id } if (-not $ExistingAssignment) { New-AzureAdServiceAppRoleAssignment -ObjectId $ManagedIdentityServicePrincipal.ObjectId -PrincipalId $ManagedIdentityServicePrincipal.ObjectId -ResourceId $GraphServicePrincipal.ObjectId -Id $AppRole.Id } else { Write-Verbose "Permission $Permission is already assigned to $ManagedIdentity." } }