Doofus
Doofus

Reputation: 95

Upstream filtering a users AD users group membership list by wild-carded string

I have a requirement to combine Get-ADUser and Get-ADGroup (with filtering) to retrieve a list of a users groups, only where the group name matches a wildcard pattern I specify.

Getting the whole list of a users groups can be slow over VPN when WFH. So instead of retrieving all the users group names into an array, then looping through that to find the matching names I need, can I include the group name filtering further upstream in the Get-ADUser call, or the Get-ADGroup call?

My question isn't so much "how is it done?" but "can it be done?", and would it actually be any quicker than pulling all group names into an array then looping.

Something like:

$SEC_GROUPS = (Get-ADUser $_ –Properties MemberOf).memberof | 
Get-ADGroup -filter {Name -like "*SEC*"} -Properties Name,Description |
Select-Object Name,Description |
Sort-Object name

Thank you for any replies so far

I had another bash and thought this worked:

$SEC_GROUPS = (get-aduser $_ -properties Memberof).memberof |
Get-ADGroup -filter 'Name -like "*SEC*"' -Properties Name,Description -ErrorAction SilentlyContinue |
select-object Name,Description |
Sort-Object Name

But it pulls all matching AD groups, not just those the user is a member of.

Update: Using the comment from Santiago below was the trick. Remember, for speed I needed to retrieve only the user groups matching the group name pattern I specify, as early as possible, no manually processing on the full groups list.

$SEC_GROUPS = (get-aduser $_ -properties Memberof).memberof -like '*SEC*' |
Get-ADGroup -Properties Name,Description |
select-object Name,Description |
Sort-Object Name

I found that, even when my group names started with SEC I still needed to include the * on both side of the match pattern, using SEC* didn`t work. I'm guessing this is because the match target starts with CN=SEC_whatever

Upvotes: 2

Views: 852

Answers (1)

Santiago Squarzon
Santiago Squarzon

Reputation: 60110

You can use the Active Directory Filter to search for all groups having your user as member and having a name containing SEC. This is as fast as it gets in my opinion.

$user   = (Get-ADUser someUser).DistinguishedName
$groups = Get-ADGroup -LDAPFilter "(&(member=$user)(name=*SEC*))" -Properties Description |
    Select-Object Name, Description |
    Sort-Object Name

If you want to give it a try you can also filter the memberof property of your user including those having a CN (common name) containing SEC (I don't think this will be faster or more robust than before snippet):

$groups = (Get-ADUser someUser -Properties memberOf).memberOf -match '(?<=^CN=).*SEC.*?(?<!\\),' |
    Get-ADGroup -Properties Description |
    Select-Object Name, Description |
    Sort-Object Name

Upvotes: 0

Related Questions