Thursday, December 5, 2024

Assign permissions to enterprise app using powershell

You might be required to add this storage account to Directory Reader role 



#find-module Microsoft.Graph.Authentication | install-module

Disconnect-Graph
Get-MgContext
Connect-MgGraph -Scopes "Application.Read.All","AppRoleAssignment.ReadWrite.All,RoleManagement.ReadWrite.Directory" -TenantId "XXXXXXXXXXXXXXXXXXXXXXXXX"

Select-MgProfile Beta


$MdId_Name = "ManagementAutomation"

$MdId_ID = (Get-MgServicePrincipal -Filter "displayName eq '$MdId_Name'").id

$graphApp = Get-MgServicePrincipal -Filter "AppId eq '00000003-0000-0000-c000-000000000000'"

$graphScopes = @(
    "User.Read.All"
    "Mail.Send"
    "Mail.ReadWrite"
)


ForEach($scope in $graphScopes){
 
  $appRole = $graphApp.AppRoles | Where-Object {$_.Value -eq $scope}
 
  if ($null -eq $appRole) { Write-Warning "Unable to find App Role for scope $scope"; continue; }
 
 
 
   #Check if permissions isn't already assigned
  $assignedAppRole = Get-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $MdId_ID | Where-Object { $_.AppRoleId -eq $appRole.Id -and $_.ResourceDisplayName -eq "Microsoft Graph" }
 
 
 
  if ($null -eq $assignedAppRole) {
    New-MgServicePrincipalAppRoleAssignment -PrincipalId $MdId_ID -ServicePrincipalId $MdId_ID -ResourceId $graphApp.Id -AppRoleId $appRole.Id
  }else{
    write-host "Scope $scope already assigned"
  }
}



No comments:

Post a Comment