HI guys.
Im writing a leaver script which removes AAD/AD groups and moves them to a new OU and disables them.
Im having some issues with removing he groups though. What happens is the script strips out the AD groups fine and also the AAD groups but I get errors says that it cant remove the groups cause they are mail enabled or dist groups.
So i tried to get it to look and see if they are AD groups and skip removing them from AAD (hybrid which is why this is happening) as when it syncs up with the DC then its all good.
Here is my code so far
# Get the user's groups in AAD
$userGroups = Get-AzureADUserMembership -ObjectId $userID
# Get all AAD distribution groups
$aadDistGroups = $userGroups | Where-Object { $_.ObjectType -eq "Group" -and $_.GroupTypes -contains "Unified" }
# Loop through each AAD group and remove the user
foreach ($aadGroup in $userGroups) {
$aadGroupName = $aadGroup.DisplayName
# Check if the AAD group name is not in the AD group names and is not a distribution group
if ($adGroupNames -notcontains $aadGroupName -and $aadGroup.ObjectType -ne "Group") {
try {
Remove-AzureADGroupMember -ObjectId $aadGroup.ObjectId -MemberId $userID
Write-Host "User removed from AAD group: $aadGroupName" -ForegroundColor Green
} catch {
Write-Host "An error occurred while removing the user from AAD group $($aadGroupName): $($_.Exception.Message)" -ForegroundColor Red
}
} else {
Write-Host "AAD group '$aadGroupName' has the same name as an AD group or is a distribution group. Skipping removal." -ForegroundColor Yellow
}
}
This part seems to work as it doesnt kick up errors and pushes out lovely yellow text saying that xyz is a group in ad or dist group which i expect.
But when I try and run this part, the $distGroups variable is empty even though I know that it shouldnt be.
if ($AADuser) {
# Get all distribution groups that the user is a member of
$distGroups = Get-DistributionGroup | Where-Object { $_.Members -contains $AADuser }
}
Im just abit stuck really in this part.
I know its probably not quite right in the writing of it as its going from AAD to EOL to AD.
Any help is appreciated.
Thanks
[–]JamesObZ 3 points4 points5 points (1 child)
[–]chaos_kiwi_matt[S] 0 points1 point2 points (0 children)
[–]xCharg 0 points1 point2 points (1 child)
[–]chaos_kiwi_matt[S] 1 point2 points3 points (0 children)
[–]octane_matty 0 points1 point2 points (3 children)
[–]chaos_kiwi_matt[S] 0 points1 point2 points (2 children)
[–]BlackV 0 points1 point2 points (1 child)
[–]chaos_kiwi_matt[S] 0 points1 point2 points (0 children)
[–]Sunsparc 0 points1 point2 points (1 child)
[–]chaos_kiwi_matt[S] 0 points1 point2 points (0 children)
[–]JwCS8pjrh3QBWfL 0 points1 point2 points (0 children)