powershellwindows-scripting

Grabbing Specific AD Groups that a User is a Member Of


Just can't for the life of me figure this out. What I am trying to do is get a list of all the groups that a user is a member of. Then I would like to pass those along and grab the specific groups that I am looking for.

Below is what I have so far:

(Get-ADUser $user -Properties MemberOf ).MemberOf | Where-Object {$_.Name -contains 'Part of Group Name'}

This returns nothing. I have a feeling that I am not referencing the right property in my Where-Object but I am having a hard time finding what that is. I know the results of (Get-ADUser $user -Properties MemberOf ).MemberOf are:

CN=App - dyn_readuser_prod_WeblogicApps_NS,OU=Groups,OU=USCC,DC=int,DC=usc,DC=local
CN=App - dyn_readuser_prod_osb_NS,OU=Groups,OU=USCC,DC=int,DC=usc,DC=local
CN=App - dyn_readuser_prod_openshift_NS,OU=Groups,OU=USCC,DC=int,DC=usc,DC=local
CN=App - dyn_readuser_nonprod_WeblogicApps_NS,OU=Groups,OU=USCC,DC=int,DC=usc,DC=local
CN=App - dyn_readuser_nonprod_osb_NS,OU=Groups,OU=USCC,DC=int,DC=usc,DC=local
CN=App - dyn_readuser_nonprod_openshift_NS,OU=Groups,OU=USCC,DC=int,DC=usc,DC=local

I just can't figure out how to reference "CN".


Solution

  • Try it this way:

    (Get-ADUser $user -Properties memberOf).memberOf |
      Where-Object { $_ -like 'CN=*Part of Group Name*,*' }
    

    The (...).memberOf syntax in PowerShell v3 and later is functionally equivalent to piping to Select-Object -ExpandProperty memberOf, so you could also write it this way:

    Get-ADUser $user -Properties memberOf |
      Select-Object -ExpandProperty memberOf |
      Where-Object { $_ -like 'CN=*part of group name*,*' }
    

    (The second variation would be required in PowerShell v2 which doesn't support the (...).memberOf "syntactic sugar.")