Introduction
Hi guys, I am sharing the below PowerShell script where you can remove a bunch of Users from 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 below steps:
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/"
$hubSite = "https://<TenantName>.sharepoint.com/sites/ExecutiveHub"
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 -AssociatedMemberGroup
#Get-PnPGroupPermissions -Identity $group
#You can Remove more valid Users in the same above kind of syntax
Write-Host "User(s) Removing Done to the:"$group.LoginName -BackgroundColor Magenta
#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")
Thanks for reading!