Modern SharePoint Online Programming - Chapter 6

Introduction 

 
Hi guys, I am sharing the below PowerShell script where you can add a bunch of Users to the Group, Owners/Members/Visitors Hub site-wise, as well as their associated sites in the SP Modern Environment. You can do the necessary tuning by going through my comments, mentioned with a # special character.

If you want to assign the User permissions individually to a particular site collection[Hub/Communication/Team] please follow the steps discussed:

Steps 

Go to Top Gear->Site Permissions->Advanced Permission Settings-> **Select the Group as per the Permissions you want to provide -> Add Users -> Uncheck the Email Invitation -> Click Share Button.

Please go ahead with the below PS script after opening your SharePoint Online Management Shell:

cls
$tenantAdmin = "https://<TenantName>-admin.sharepoint.com/"
#Hub name change just replace below value
$hubSite = "https://<TenantName>.sharepoint.com/sites/Executive"
Connect-PnPOnline -Url $tenantAdmin -UseWebLogin
$HubSite = Get-PnPHubSite $hubSite
$HubSiteId = $HubSite.SiteId
$ModernSites = (Get-PnPTenantSite -Template 'GROUP#0') + (Get-PnPTenantSite -Template 'SITEPAGEPUBLISHING#0')
$SitesFromHub = New-Object System.Collections.ArrayList
Write-Host ("Searching {0} sites:" -f $HubSite.Title) -BackgroundColor Gray
foreach ($ModernSite in $ModernSites){
$site = Get-PnPHubSite $ModernSite.Url
if($site.SiteUrl){
if($site.SiteId -eq $HubSiteId){
Write-Host ("* {0} - {1}" -f $ModernSite.Title, $ModernSite.Url)
$SitesFromHub.Add($ModernSite) | Out-Null
}
}
}
Write-Host ""
Write-Host "Adding Users:" -BackgroundColor Gray
foreach ($SiteHub in $SitesFromHub){
Write-Host ("* {0} - {1} ... " -f $SiteHub.Title, $SiteHub.Url)
#Write-Host ("* {0} - {1} ... " -f $SiteHub.Title, $SiteHub.Url) -NoNewline
Connect-PnPOnline -Url $SiteHub.Url -UseWebLogin
try{
#$group=Get-PnPGroup -AssociatedOwnerGroup
$group=Get-PnPGroup -AssociatedVisitorGroup
#Replace above value as per the Permissions Read-AssociatedMemberGroup/Full Control-AssociatedOwnerGroup/-AssociatedVisitorsGroup
#Use below format for other Users that you want to add
Add-PnPUserToGroup -LoginName [email protected] -Identity $group
Add-PnPUserToGroup -LoginName [email protected] -Identity $group
#You can add as many valid Users as required in the same above format 
Write-Host "Below User(s) Adding Done to the:"$group.LoginName -BackgroundColor Green
Get-PnPGroupMembers -Identity $group
#Get-PnPGroupPermissions -Identity $group
}
catch{
Write-Host $_.ToString() -BackgroundColor Red
}
}
Write-Host "All Done"
Write-Host "Press any key to Close..."
$Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
 

Feel free to touch base for any other clarification or quick support. Have a great day!