Try the following
$Groups = "Domain Admins", "Enterprise Admins", "Schema Admins", "Administrators"
# Get the members of all groups
$groupMembers = @{}
foreach ($group in $Groups) {
$groupMembers[$group] = Get-ADGroupMember $group -Recursive | Select-Object -ExpandProperty SamAccountName
}
# Get users with adminCount = 1
$adminUsers = Get-ADUser -Filter {enabled -eq $true} -Properties name, adminCount, sAmAccountName | Where-Object {$_.adminCount -eq '1'}
# Check if each user is in all groups
foreach ($user in $adminUsers) {
$isInAllGroups = $true
foreach ($group in $Groups) {
if ($groupMembers[$group] -notcontains $user.sAmAccountName) {
$isInAllGroups = $false
break
}
}
if ($isInAllGroups) {
Write-Host "$($user.sAmAccountName) exists in all groups"
} else {
Write-Host "$($user.sAmAccountName) is not in all groups"
Set-ADUser -Identity $user.sAmAccountName -Replace @{adminCount = 0}
}
}
If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.
hth
Marcin