I have a very large and complex SharePoint 2016 site with hundreds of groups. I'm writing a powershell script to add a specific user to a group if the group's name matches some text.

For example, I need to add UserX to any group that has the word "English" in the name of the group.

I have the following code working to add to the user to an individual group, but not sure how to loop through and add them only when the partial text matches.

$site=get-spsite https://site
#get web object

#Enumarate site groups
$web.SiteGroups |select name
#get user object
#Get group object
$group=$web.SiteGroups["Year 10 ENGLISH Staff"]
#add user to group

Thanks for any help



Use the following commands:

$site=get-spsite http://sp/sites/team
#get web object

#Enumarate names of site groups which the group name has the specific word
$web.SiteGroups | select Name | where {$_.Name -like "*English*"}

#get user object
#get groups that has the specific word in the group name
$groups = $web.SiteGroups | where {$_.Name -like "*English*"}
#iterate group object
foreach ($group in $groups) {
    #add user to the group
  • Thanks for that. If I needed a more complex selection, like English and staff then would I use where {$_.Name -like "English" -and $_.Name -like "Staff"} in both places. Dec 4 '18 at 22:10
  • Have just tweaked that to include the more complex selection and it's working perfectly! Dec 4 '18 at 23:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.