Script to Export Members of an Azure AD Group to CSV Using Microsoft Graph
This script connects to the Microsoft Graph API and retrieves all members of a specified Azure AD group, filtering for a group named “365-2fa.” It exports selected properties like userPrincipalName and displayName for each group member into a CSV file at a defined output path. The script ensures the output directory exists before exporting and provides error handling for permissions or directory issues, making it useful for auditing group memberships in Azure AD.
Here is the script:
Prompt the user to enter Tenant Id or Primary domain
Section titled “Prompt the user to enter Tenant Id or Primary domain”$TenantId = Read-Host “Please enter Tenant Id or Primary domain”
Define the scopes needed for the Microsoft Graph API permissions
Section titled “Define the scopes needed for the Microsoft Graph API permissions”$Scopes = “User.Read.All,AuditLog.Read.All,Directory.Read.All”
Connect to Microsoft Graph
Section titled “Connect to Microsoft Graph”Connect-MgGraph -Scopes $Scopes
Define group id
Section titled “Define group id”$Group = Get-MgGroup -All | where {$_.DisplayName -like “365-2fa”} $GroupId = $Group.Id
Define the output path
Section titled “Define the output path”$OutputPath = “C:\temp\MembersExport.csv”
Check if the directory exists
Section titled “Check if the directory exists”if (!(Test-Path -Path (Split-Path -Path $OutputPath -Parent))) { Write-Host “The directory does not exist. Please check the output path and try again.” return }
Export Members with specified properties
Section titled “Export Members with specified properties”try { Get-MgGroupTransitiveMember -All -GroupId $GroupId | Select-Object Id, @{Name=“userPrincipalName”; Expression={$.AdditionalProperties.userPrincipalName}}, @{Name=“displayName”; Expression={$.AdditionalProperties.displayName}} | Export-Csv -Path $OutputPath -NoTypeInformation Write-Host “Export successful. The file is located at $OutputPath” } catch { Write-Host “Failed to export users. Please check your permissions and try again.” }