I’m trying to pull together a report of all the members that are inside specific Azure AD groups , everything works fine until one of the members is another AD group instead of a regular username. On the following picture, the row # 3 has Username and UserPrincipalName blank because the UserId is actually a group ID
Below is the powershell I’m running in Azure runbook POwershell 7.2
$resultsarray =@()
$groups = get-mggroup -All | Where-Object {$.DisplayName -eq ‘MT’
-or $.DisplayName -like ‘MT_ *’}ForEach ($group in $groups) { $members = Get-MgGroupMember -GroupId
$group.Id ForEach ($member in $members) {$username = (get-mguser -UserId $member.Id).DisplayName
$principalusername = (get-mguser -UserId $member.Id).UserPrincipalName$UserObject = new-object PSObject $UserObject | add-member
-membertype NoteProperty -name “GroupId” -Value $group.Id $UserObject | add-member -membertype NoteProperty -name “GroupName” -Value
$group.DisplayName $UserObject | add-member -membertype NoteProperty
-name “UserId” -Value $member.Id $UserObject | add-member -membertype NoteProperty -name “UserName” -Value $username $UserObject |
add-member -membertype NoteProperty -name “UserPrincipalName” -Value
$principalusername $resultsarray += $UserObject}
}
$resultsarray | Export-CSV -Encoding ASCII
($env:TEMP2+”ADGroupsANDUsers.csv”) -Notype$Context = New-AzStorageContext -StorageAccountName ‘teststorage01’
Set-AzStorageBlobContent -Context $Context -Container “test” -File
($env:TEMP2+”ADGroupsANDUsers.csv”) -Blob “ADGroupsANDUsers.csv”
-Force
This is just an idea how to get the users the member of an AD group is another AD group but you guys might have a better solution , I just need some guidance on the ideal solution on this type of scenario. I wish I can tell everyone to not add an AD group as member of another AD group 🙁
I’m looking for the ideal powershell code to handle this situation