Add user(s) to AdGroup with exceptions

Welcome Forums General PowerShell Q&A Add user(s) to AdGroup with exceptions

This topic contains 2 replies, has 2 voices, and was last updated by

Ben
 
Participant
3 months, 2 weeks ago.

  • Author
    Posts
  • #110995
    Ben

    Participant
    Points: 1
    Rank: Member

    Hi guys,

    I'm trying to add a new user in our department to several groups, basically cloning another user's AD group membership, however, there are certain groups that I do not want to include, but not sure how to exclude them from code. Any suggestions? Here's the code to do the actual cloning, without anything for an exception to a group:

    Get-ADUser -Identity user0 -Properties memberof |
    Select-Object -ExpandProperty memberof |
    Add-ADGroupMember -Members user1
    
    
    
  • #111008

    Participant
    Points: 350
    Helping Hand
    Rank: Contributor

    See below

    #memberOf is an array of distinguished names for the groups
    #the user is a member of
    $memberOf = @(
        'CN=Group1,OU=Groups,DC=mydomain,DC=com',
        'CN=Group2,OU=Groups,DC=mydomain,DC=com',
        'CN=Group3,OU=Groups,DC=mydomain,DC=com',
        'CN=Group4,OU=Groups,DC=mydomain,DC=com',
        'CN=Group10,OU=Groups,DC=mydomain,DC=com'
    )
    
    #Filter with WildCard
    $memberOf | Where{$_ -notlike '*Group1*'}
    

    Output:

    
    PS C:\Users\Rob> $memberOf | Where{$_ -notlike '*Group1*'}
    
    CN=Group2,OU=Groups,DC=mydomain,DC=com
    CN=Group3,OU=Groups,DC=mydomain,DC=com
    CN=Group4,OU=Groups,DC=mydomain,DC=com
    
    #or Filter with static reference
    $exclude = @(
        'CN=Group1,OU=Groups,DC=mydomain,DC=com',
        'CN=Group3,OU=Groups,DC=mydomain,DC=com'
    )
    
    $memberOf | Where{$exclude -notcontains $_}
    

    Output

    CN=Group2,OU=Groups,DC=mydomain,DC=com
    CN=Group4,OU=Groups,DC=mydomain,DC=com
    CN=Group10,OU=Groups,DC=mydomain,DC=com
    

    So you code would be something like:

    Get-ADUser -Identity user0 -Properties memberof |
    Select-Object -ExpandProperty memberof |
    Where{$_ -notlike '*Group1*'} |
    Add-ADGroupMember -Members user1
    
  • #111062
    Ben

    Participant
    Points: 1
    Rank: Member

    Thank you so much. This is helpful, and helps me learn Powershell better.

The topic ‘Add user(s) to AdGroup with exceptions’ is closed to new replies.