woter,
I wanted to say your script was extremely helpful, though I made a few additional modifications to it since your version still contained the "Get-AzADServicePrincipal" command. MgGraph now has a command that fully replaces this one (Get-MgServicePrincipal), though I don't personally know whether this new MgGraph command was available at your time of writing or now. I know it exists now at least! I also added the required MgGraph scopes to the "Connect-MgGraph" command so it's known the prerequisite permissions in order to run this script without error. Hope this helps everyone!
#Requires -Modules Microsoft.Graph.Applications
$DestinationTenantId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" # Azure Tenant ID, can be found at https://portal.azure.com/#view/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/~/Overview
$MsiName = "ManagedIdentityName" # Name of system-assigned or user-assigned managed service identity. (System-assigned use same name as resource).
$oAssignPermissions = @(
"Files.Read.All"
"Sites.Read.All"
)
$MgRequiredScopes = @(
"Application.Read.All"
"AppRoleAssignment.ReadWrite.All"
"Directory.Read.All"
)
$GraphAppId = "00000003-0000-0000-c000-000000000000" # Don't change this. This is the immutable application ID of the Microsoft Graph service principal.
Connect-MgGraph -TenantId $DestinationTenantId -Scopes $MgRequiredScopes #-NoWelcome #Uncomment NoWelcome if desired
$oMsi = Get-MgServicePrincipal -Filter "displayName eq '$MsiName'"
$oGraphSpn = Get-MgServicePrincipal -Filter "appId eq '$GraphAppId'"
$oAppRole = $oGraphSpn.AppRoles | Where-Object {($_.Value -in $oAssignPermissions) -and ($_.AllowedMemberTypes -contains "Application")}
foreach($AppRole in $oAppRole)
{
$oAppRoleAssignment = @{
"PrincipalId" = $oMSI.Id
"ResourceId" = $oGraphSpn.Id
"AppRoleId" = $AppRole.Id
}
New-MgServicePrincipalAppRoleAssignment `
-ServicePrincipalId $oAppRoleAssignment.PrincipalId `
-BodyParameter $oAppRoleAssignment `
-Verbose
}