Return 广告帐户列表并检查是否为组成员

Return list of ad accounts and check if member of group

我写了下面的内容,它可以工作(基于 Check if the user is a member of a list of AD groups),但是它需要 令人难以置信的 很长时间才能 运行 - 我'假设这是因为它为每个用户检索完整的组。我曾尝试将 $members... 行从函数的开头移出以检索组列表一次,但似乎没有任何区别。

是否有更有效的方法返回此信息?

samaccountname   enabled   InDenyGroup 
--------------   -------   ----------- 
admin-abc        True      yes         
admin-def        True      yes         

在此示例中,帐户名过滤器是“king”,因为检查帐户是否在组中。

Get-ADUser -Filter "(SamAccountName -like 'admin*') -and (enabled -eq 'true')" | 
    ft -AutoSize samaccountname,enabled,@{Name='InBlockGroup'; Expression={InDenyGrp($_.samaccountname)}}


Function InDenyGrp([string]$UserID) {
    $members = Get-ADGroupMember -Identity "myBlockGroup" | Select -ExpandProperty SamAccountName

    If ($members -contains $UserID) {
        Return "yes"
    } Else {
        Return "not in group"
    }
}

谢谢。

您在 Foreach-Object 循环的每次迭代中一次又一次地查询同一个 ADGroup 的所有 ADGroup 成员(不仅是 DistinguishedNames)(这就是瓶颈)。

或者您只是查询“blockGroup”的成员(查看您发布的 link)并遍历成员并检查您的用户是否是其中的一部分(有一些属性可以与之比较)或者你试试下面的代码:

构建查找 table 应该可以提高性能。 此外,除了 DistinguishedNames,我们不需要更多关于组成员的信息,因此 Get-ADGroupMember 是多余的。

您可以使用不同组的成员扩展 LookupTable。

# query blocking group with it's members first (only DistinguishedNames)
$adGroup = Get-ADGroup -Identity '<myBlockGroup>' -Properties 'Members'

# build lookup table of members' DistinguishedNames 
$adGroupMemberLookupTable = [System.Collections.Generic.HashSet[string]]::new()
foreach ($member in $adGroup.Members) {
    [void]$adGroupMemberLookupTable.Add($member)
}

Get-ADUser -Filter "(SamAccountName -like 'admin*') -and (enabled -eq 'true')" | 
    Format-Table -AutoSize samaccountname, enabled, 
    @{Name ='InBlockGroup'; 
        Expression = { 
            # lookup if user is member of a "blocking" group
            $adGroupMemberLookupTable.Contains($_.DistinguishedName) 
        } 
    }