如何用PowerShell筛选所属组少于2的AD联系人并删除?
I totally get why you hit a wall here—Get-ADGroupMember is great for pulling members out of a specific group, but it doesn’t help you count how many groups each contact belongs to. Let’s flip the approach and fix this properly:
Step 1: Fetch all AD Contacts with their group membership data
First, we need to grab every contact object in AD and pull the MemberOf property (this stores the full list of groups the contact is part of):
$allContacts = Get-ADObject -Filter {ObjectClass -eq "contact"} -Properties MemberOf
Step 2: Filter contacts with fewer than 2 group memberships
The MemberOf property is an array, so we can use its Count value to narrow down our target contacts:
$contactsToRemove = $allContacts | Where-Object { $_.MemberOf.Count -lt 2 }
Step 3: Preview before deleting (don’t skip this!)
Always double-check which contacts you’re about to delete—this prevents accidental data loss:
$contactsToRemove | Select-Object Name, DistinguishedName, @{Name="GroupCount"; Expression={$_.MemberOf.Count}}
Step 4: Delete the contacts
Once you’re sure the preview looks correct, uncomment and run this line to remove them:
# $contactsToRemove | Remove-ADObject -Confirm:$false
Why your initial approach didn’t work
Get-ADGroupMember is built to list members of a group, not to tally up groups for a single object. By starting with the contact objects themselves and checking their MemberOf property, we get the group count we need directly.
Quick Notes
- If you only want to delete contacts with exactly 1 group (not zero), adjust the filter to
$_.MemberOf.Count -eq 1 - Make sure your account has the right AD permissions to read contact properties and delete objects
- Remove the
-Confirm:$falseflag if you want to approve each deletion individually
内容的提问来源于stack exchange,提问作者Mateusmm

