Patrick Lamber
Patrick Lamber Microsoft Office Development MVP

Change the owner Group membership of all SharePoint Online sites

I was required to limit the permission of all owners added to the default owner Group and assign them to the default member Group. I created this script using PnP PowerShell taking all the members of the default owner group and assigning them to the default member Group. After that I am removing the identity from the owner Group.

This script uses a userNameOrPattern variable to allow you to limit the operation on selected identities.

$tenant = "tenantAdmin"
$adminUrl = "https://$tenant-admin.sharepoint.com"
$appId = "appId"
$appSecret = "secretKey"
$userNameOrPattern = '*'
Connect-PnPOnline $adminUrl -ClientId $appId -ClientSecret $appSecret
$tenantSites = Get-PnPTenantSite -Filter "Url -like 'prj_'"
$tenantSites = $tenantSites | Sort-Object Url -Descending
$i = 0
$total = $tenantSites.Count
$tenantSites | ForEach-Object {
$site = $_
$i++
Write-Host "Processing $($site.Url) $i/$total"
Connect-PnPOnline $site.Url -ClientId $appId -ClientSecret $appSecret
$group = Get-PnPGroup -AssociatedOwnerGroup
Get-PnPGroupMembers -Identity $group.LoginName | where { $_.Title -like '*$userNameOrPattern' } | ForEach-Object {
$user = $_
$group = Get-PnPGroup -AssociatedMemberGroup
Add-PnPUserToGroup -LoginName $user.LoginName -Identity $group.LoginName
Remove-PnPGroupMember -LoginName $user.LoginName -Group $group.LoginName
}
}