powershell script to add only group with specific name


i have this comand line to copy group of user1 and add user 2 to this group.
i use a csv file with a list to group to not copy/exclude from this script:

$exclude = Get-Content groupexclusion.txt
            Get-ADPrincipalGroupMembership -Identity $user1 | ? {$exclude -notcontains $_.name} | % {Add-ADPrincipalGroupMembership -Identity $user2 -MemberOf $_}

what i need now is to continue to use this script and add this :

copy only group that name begin with "GR"  "GK"  AND CONTINUE TO USE the csv file extension, SO THE SCRIPT will select all group begin with this char that user1 is member, verify that this group is not in exclusion csv file and add it to user 2.

thank for help
Who is Participating?
Just add an extra condition on the where statement.

$exclude = Get-Content groupexclusion.txt
Get-ADPrincipalGroupMembership -Identity $user1 | ? {$exclude -notcontains $_.name -and ($_.name -like "GR*" -or $_.name -like "GK*")} | % {Add-ADPrincipalGroupMembership -Identity $user2 -MemberOf $_}

Open in new window

cawasakiAuthor Commented:

Thanks for this

Are this is work with your code:

On the csv exclusion file are the group named gkgroup1. So it begin with gk, are this group will be excluded or not? Because we have add on code to copy all group namébegin with gk?.

If the $exclusion array contains a group called gkgroup1 then no it will not be added. This is because there is a and condition. The where command is expecting either a true result. So...

$exclude -notcontains $_.name -and ($_.name -like "GR*" -or $_.name -like "GK*")

$exclude -notcontains $_.name will return false.
$_.name -like "GR*" -or $_.name -like "GK*" will return true.

Where will be only match if it returns true -and true. So the where conditions will fail so the group will not be added if gkgroup1 is in $exclusions.
cawasakiAuthor Commented:
thanks its work
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.