help with csom script for SPO, adding user to same default sharepoint group on multiple sites

sharepoint.stackexchange https://sharepoint.stackexchange.com/questions/261375

  •  06-02-2021
  •  | 
  •  

As described in the title, im trying to add a user to the same default sharepoint group on multiple sites with a csom powershell script. (e.g. "Visitors" group)

But the default groups has different names as the sites also have different names.

with the script below, how can i retrieve the group by only specifying "visitors" in the group name? In other words, that the group can be found by only specifiyng parts of the full group name, which is the group $Web.SiteGroups.GetByName will retrieve.

Thank you for all tips and responses.

$Sites = Import-Csv 'c:\PS\sposites.csv' (with one column named URL, with site url)

$UserAccount = "test@domain.no"

$GroupName= "Sitename Visitor"

foreach($site in $Sites.URL) 

{

    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($Site)
    $Ctx.Credentials = $Creds

    $Web = $Ctx.Web
    $Group = $Web.SiteGroups.GetByName($GroupName)

    $User=$web.EnsureUser($UserAccount)

    $Result = $Group.Users.AddUser($User)
    $Ctx.Load($Result)
    $Ctx.ExecuteQuery()

    write-host  -f Green "User '$UserAccount' has been added to '$GroupName'"
}
有帮助吗?

解决方案

If you are adding users to default visitors group for each site, then instead of getting group via groupname fetch the site associated visitor group

 $ctx.Load($web.AssociatedVisitorGroup)
 $ctx.ExecuteQuery() 

else you have to iterate all groups and get the group based on Match/Contains expression

许可以下: CC-BY-SA归因
scroll top