You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PowerShell筛选所属组少于2的AD联系人并删除?

Solution: Delete AD Contacts with Fewer Than 2 Group Memberships

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:$false flag if you want to approve each deletion individually

内容的提问来源于stack exchange,提问作者Mateusmm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:37:01