I used to have a Powershell script that used the AzureAD module to list all users and their managers in active directory, and then a separate script for getting all users of a security group. Now that the AzureAD module is deprecated I’m trying to use a script that uses Microsoft Graph to both get a list of users of that security group and also show their managers email, but I keep getting a blank CSV, despite the group having 30 or so members.
I initially sent individual Powershell commands to get a list of all User Ids belonging to the group successfully, but anytime I try to use a script that exports to a csv, it’s a blank 0KB file
Import-Module Microsoft.Graph
Connect-MgGraph -Scopes "User.Read.All", "Group.Read.All", "User.ReadBasic.All"
$securityGroupName = "redgroup"
$csvFilePath = "C:UsersbruceDocumentsredgroup_userlist.csv"
$group = Get-MgGroup -Filter "displayName eq '$securityGroupName'"
if ($null -eq $group) {
Write-Host "Group '$securityGroupName' not found." -ForegroundColor Red
exit
}
$groupMembers = Get-MgGroupMember -GroupId $group.Id -All -Property "id,displayName,userPrincipalName"
$userDetails = @()
foreach ($member in $groupMembers) {
if ($member.'@odata.type' -eq "#microsoft.graph.user") {
$user = Get-MgUser -UserId $member.Id -Property "displayName,userPrincipalName,manager"
$managerEmail = $null
if ($user.Manager) {
$manager = Get-MgUser -UserId $user.Manager.Id -Property "userPrincipalName"
$managerEmail = $manager.UserPrincipalName
}
$userDetails += [PSCustomObject]@{
"UserDisplayName" = $user.DisplayName
"UserEmail" = $user.UserPrincipalName
"ManagerEmail" = $managerEmail
}
}
}
$userDetails | Export-Csv -Path $csvFilePath -NoTypeInformation
Disconnect-MgGraph
Write-Host "Red Group's manager list created at $csvFilePath" -ForegroundColor Green
Bruce M is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.