首页 > 解决方案 > 查找不属于多个组的用户

问题描述

我的公司使用 Microsoft Intune。我们在控制条件访问的本地 AD 中有 4 个组。我们只称它们为AllowGroup1AllowGroup2BlockGroup1BlockGroup2。我想知道找到的是不在所有组中的所有用户。我想要找到的结果是任何不在上述组中的用户对象。这样我就可以证明我们的整个系统是合规的。有关我从这篇文章中借用的 Powershell 代码,请参见下文列出不属于多个组之一的 AD 用户

我正在我的家庭域控制器上运行这些测试。我遇到的问题是脚本没有在整个域中查找用户。具体来说,我的个人 DC 中有一个称为Home (我创建了 OU)的 OU,并且在一个名为Users的子 OU 中有 2 个用户对象,该脚本没有从中提取。我正在使用 Enterprise Admins 组中的用户运行此脚本,因此我知道它具有足够的权限。它应该通过 PowerShell 在 AD 中搜索不在多个组中的用户,并将这些用户放在一个名为 NotInGroup 的组中

更详细地说,一些用户将位于AllowGroup1BlockGroup2中。一些用户将在BlockGroup1BlockGroup2中。我想查找不在上面列出的任何组中的所有用户。

Import-Module ActiveDirectory
$groupname = "NotInGroup"
$members = Get-ADGroupMember -Identity $groupname

    foreach($member in $members)
    {
     Remove-ADGroupMember -Identity $groupname -Member $member.samaccountname
    }
    $users = Get-ADUser -Filter 
    {
        ((memberof -notlike "CN=AllowGroup1,OU=Intune,OU=Groups,DC=domain,DC=local") 
    -AND (memberof -notlike "CN=AllowGroup2,OU=Intune,OU=Groups,DC=domain,DC=local")
    -AND (memberof -notlike "CN=BlockGroup1,OU=Intune,OU=Groups,DC=domain,DC=local") 
    -AND (memberof -notlike "CN=BlockGroup2,OU=Intune,OU=Groups,DC=domain,DC=local"))
     } 
    -SearchBase "dc=domain,dc=local" -SearchScope Subtree
    
    foreach($user in $users)
    {
    Add-ADGroupMember -Identity $groupname -Members $user.samaccountname -ErrorAction SilentlyContinue
    }

标签: powershellactive-directoryuser-management

解决方案


我不认为像这样的复杂过滤器会起作用,我会选择使用正则表达式。

也许像

# get users not in groups 'AllowGroup1', 'AllowGroup2', 'BlockGroup1', 'BlockGroup2'
$regex = 'CN=(AllowGroup[12]|BlockGroup[12])'
$users = Get-ADUser -Filter * -Properties MemberOf | Where-Object { ($_.MemberOf -join ';') -notmatch $regex }

或者您可以尝试使用LDAPFilter参数:

$filter = '(!(|(memberof=CN=AllowGroup1,OU=Intune,OU=Groups,DC=domain,DC=local)
               (memberof=CN=AllowGroup2,OU=Intune,OU=Groups,DC=domain,DC=local)
               (memberof=CN=BlockGroup1,OU=Intune,OU=Groups,DC=domain,DC=local)
               (memberof=CN=BlockGroup2,OU=Intune,OU=Groups,DC=domain,DC=local)))'
$users = Get-ADUser -LDAPFilter $filter

两个参数FilterLDAPFilter需要一个字符串,而不是一个脚本块


推荐阅读