piersmh
piersmh

Reputation: 30

Return list of ad accounts and check if member of group

I've written the below, and it works (based on Check if the user is a member of a list of AD groups), however it takes an incredibly long time to run - I'm assuming this is because it retrieves the full group for every user. I've tried moving the $members... line out of the function at the start to retrieve the group list once, but doesn't seem to make any difference.

Is there a more efficient way of returning this info?

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

In this example, the account name filter is "king", as the check is whether an account is in a group or not.

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"
    }
}

Thanks.

Upvotes: 0

Views: 476

Answers (1)

swbbl
swbbl

Reputation: 864

You query all ADGroup members (not only the DistinguishedNames) of the same ADGroup on each iteration in your Foreach-Object loop again and again (That's the bottleneck).

Either you just query the "blockGroup"'s members (see your posted link) and loop over the members and check whether your users are part of them (there are some properties to compare it with) or you try the code below:

Building a lookup table should increase the performance. Furthermore, we don't need more information about group members than the DistinguishedNames, therefore Get-ADGroupMember is overkill.

You can extend the LookupTable with members of different groups.

# 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) 
        } 
    }

Upvotes: 1

Related Questions