The estimated reading time 1 minutes
Clearing old or orphaned groups is also important in cloud environments, especially in larger structures. So an easy way is to check if there are disabled users in Azure AD groups. Of course there can be also some license savings in M365 if disabled users are removed.
This use case I wrote a small PowerShell script to check members of a group and finds all disabled users, if you like it can also remove the membership of this group.
Connect-AzureAD $grouptoclean = "XXXXX" $groupid = (Get-AzureADGroup -SearchString "$grouptoclean").ObjectId $groupmembers = (Get-AzureADGroupMember -ObjectId "$groupid" -All $true) | Sort-Object UserPrincipalname $inactiveusers = @() foreach($user in $groupmembers){ $upn = ($user).UserPrincipalname $enabled = Get-AzureADUser -SearchString $upn | Where-Object{$_.AccountEnabled -eq $false} $active = ($enabled).AccountEnabled $userid = ($enabled).ObjectId if($enabled){ Write-Host "UPN: $upn is disabeld, Status: $active" -ForegroundColor Yellow $inactiveusers += $upn #Remove-AzureADGroupMember -ObjectId $groupid -MemberId $userid } else{ $member = Get-AzureADUser -SearchString $upn $upnmember = ($member).UserPrincipalName $activemember = ($member).AccountEnabled Write-Host "UPN: $upnmember Status: $activemember" } } $inactiveusers | sort ($inactiveusers).count #$inactiveusers = $null
the yello output shows all disabled users included in this group. If you remove the # in line 19 this script removes all disabled users directly.
Remove-AzureADGroupMember -ObjectId $groupid -MemberId $userid
Have fun cleaning your M365 groups.
NOTE: if you edit distribution groups, please be careful if there are shared mailboxes as members in this groups. These users are disabled by default.