Author Posts

September 5, 2018 at 1:00 pm

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


September 5, 2018 at 1:20 pm

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

September 5, 2018 at 8:35 pm

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