I am attempting to write a script where if there is a user in SharePoint Online that has Full Control, that it gets updated to a new Full Control - No Subwebs permission level.
Despite that it saying it has made the necessary change, when I go to check in SharePoint, the permission stays the same. The permission level is created successfully and I can get it working for the group side of my script. Just not for users that are explicitly added.
It also for some reason won't work recursively through the subsites. Any help would be much appreciated!
#Connect to Site Collection
Connect-PnPOnline -Url https://foo.sharepoint.com/sites/testmodernsitecollection/ -UseWebLogin
#Get All Subsites
$Sites = Get-PnPSubWebs
#Create New Permission Level by cloning Full Control and excluding ManageSubWebs.
Add-PnPRoleDefinition -RoleName "Full Control - No Subwebs" -Clone "Full Control" -Exclude ManageSubwebs -Description "Full Control - No Subwebs"
Foreach ($Site in $Sites)
{
$Groups = Get-PnPGroup
$Users = Get-PnPUser -WithRightsAssigned -Web $Site
#Loop for setting User Permissions
Foreach ($User in $Users | Where-Object {$_.PrincipalType -eq "User"}){
$UserPermission = Get-PnPUser -Identity $User.LoginName -ErrorAction SilentlyContinue
if ($UserPermission.RoleTypeKind -eq "Administrator")
{
Set-PnPWebPermission -Identity $User -RemoveRole "Full Control" -AddRole "Full Control - No Subwebs"
}
Write-host "Updated Permission Level for $($User.Title) at $($Site.Title)"
}
#Loop for setting Group Permissions
Foreach ($Group in $Groups | Where-Object {$_.PrincipalType -eq "SharePointGroup"}) {
$GroupPermission = Get-PnPGroupPermissions -Identity $Group.Title -ErrorAction SilentlyContinue
if ($GroupPermission.RoleTypeKind -eq "Administrator")
{
Set-PnPGroupPermissions -Identity $Group -RemoveRole "Full Control" -AddRole "Full Control - No Subwebs"
}
Write-host "Updated Permission Level for $($Group.Title) at $($Site.Title)" -f Green
}
}
Disconnect-PnPOnline