🔧 New: User Management Graph PowerShell Toolkit

Simplify user tasks like bulk creation, updates, password resets, deletions, license checks & more — all from one place.

🚀 Launch Toolkit

Fetch and Email Activated and Non-Activated Directory Roles

Microsoft Entra ID (Azure Active Directory) provides numerous directory roles to delegate administrative responsibilities. Some roles are activated (in use), while others remain available but not activated. Keeping track of these roles is essential for governance, auditing, and security management.

This script uses Microsoft Graph PowerShell to list both activated and non-activated directory roles in the tenant, export the results to CSV, and send the report to the administrator by email.


i) The Script


    # ============================
    # Config
    # ============================
    # Admin mailbox to receive the report
    $AdminUPN = "samadmin@7xh7fj.onmicrosoft.com"   
   
    Connect-MgGraph -Scopes "Directory.Read.All" ,"Mail.Send"
                                                          
    $activatedRoles=Get-MgDirectoryRole
                                                          
    $roleTemplates=Get-MgDirectoryRoleTemplate
                                                          
    $activatedRoleIds=$activatedRoles.RoleTemplateId
    $nonActivatedRoles=$roleTemplates | Where-Object { $_.Id -notin $activatedRoleIds }
    $NonActivatedReport=$nonActivatedRoles | Select-Object @{n="RoleType" ;e={"Non-Activated"}}, DisplayName, @{n="RoleId" ;e={$_.Id}}
    $ReportRows=$ActivatedReport + $NonActivatedReport
    $ReportRows | Sort-Object RoleType, DisplayName | Export-Csv -Path $ReportPath -NoTypeInformation -Encoding UTF8
    $nonActivatedCount=@($NonActivatedReport).Count
    $totalCount=@($ReportRows).Count
    $Subject="Directory Roles Report — $(Get-Date -Format 'yyyy-MM-dd')"
    $Body=@"
                                                          Hello Admin,

Attached is the latest report of directory roles in the tenant.

- Activated Roles: $activatedCount
- Non-Activated Roles: $nonActivatedCount
- Total: $totalCount

Regards,
Graph PowerShell Script "@ # Read and attach the CSV $AttachmentContent = [System.Convert]::ToBase64String([System.IO.File]::ReadAllBytes($ReportPath)) $Attachments = @( @{ "@odata.type" = "#microsoft.graph.fileAttachment" Name = [System.IO.Path]::GetFileName($ReportPath) ContentBytes = $AttachmentContent } ) # Build the message payload $Message = @{ Message = @{ Subject = $Subject Body = @{ ContentType = "HTML" Content = $Body } ToRecipients = @( @{ EmailAddress = @{ Address = $AdminUPN } } ) Attachments = $Attachments } SaveToSentItems = "true" } # Send the email Send-MgUserMail -UserId $AdminUPN -BodyParameter $Message Write-Host "Directory roles report emailed successfully to $AdminUPN"

ii) How the Script Works

  1. Configuration – The administrator’s email ($AdminUPN) is set as the recipient for the report.
  2. Graph Connection – The script connects to Microsoft Graph with Directory.Read.All (to read roles) and Mail.Send (to send email).
  3. Fetch Roles –
    • Get-MgDirectoryRole retrieves activated roles.
    • Get-MgDirectoryRoleTemplate retrieves all possible roles.
    • By comparing these two, the script identifies non-activated roles.
  4. Build Report – Both activated and non-activated roles are combined into a single dataset with fields: RoleType, DisplayName, and RoleId.
  5. Export Report – The results are exported to a CSV file.
  6. Email Report – A summary of counts (activated, non-activated, total) is included in the email body, and the full CSV is sent as an attachment.

iii) Further Enhancements

  • Add Role Descriptions – Extend the report with role descriptions for better context.
  • Include Assignments – Add details about who is assigned to each activated role.
  • Separate CSVs – Export activated and non-activated roles into two separate files for clearer segregation.
  • Scheduled Reports – Automate the script with Task Scheduler or Azure Automation for recurring governance checks.
  • Compliance Logging – Store historical CSVs in SharePoint or OneDrive for audit purposes.

iv) Possible Errors & Solutions

Error Cause Solution
Insufficient privileges to complete the operation Missing permissions when connecting to Graph. Ensure Directory.Read.All and Mail.Send are included in Connect-MgGraph.
Resource not found Invalid admin mailbox in $AdminUPN. Provide a valid mailbox-enabled account.
CSV File Empty No roles were retrieved due to permission issues or API throttling. Verify Graph connection and re-run the script.
Slow performance in large tenants Fetching all templates and roles may take longer. Optimize by selecting only necessary properties or splitting tasks into multiple runs.

v) Conclusion

This Graph PowerShell script helps administrators maintain visibility into both activated and available directory roles in Microsoft Entra ID. By emailing the report directly to the administrator, it eliminates manual effort, provides quick insights into role activation status, and improves governance.

With enhancements such as adding assignments, scheduling, and compliance logging, the script can become a powerful component of an organization’s role-based access control (RBAC) auditing strategy.


Graph PowerShell Explorer Widget

20 Graph PowerShell cmdlets with easily accessible "working" examples.


Permission Required

Example:


                


                


                

© m365corner.com. All Rights Reserved. Design by HTML Codex