Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
1 like 0 dislike
41 views
in PowerShell by 20 36 42

I have to remove several unnecessary permission groups from multiple subsites, but there are some groups that I need to keep. How to delete permission groups and exclude others?


1 Answer

1 like 0 dislike
by 20 36 42
edited by

To delete SharePoint groups and exclude others using PowerShell

The following PowerShell script enables you to exclude some permission groups from being deleted

Add-PSSnapin Microsoft.SharePoint.PowerShell
$siteUrl = "https://rootSite/debug"
$site = Get-SPSite $siteUrl
$web = $site.RootWeb

#get all site groups 
$groups = $web.SiteGroups

#iterate through each group to be deleted or excluded 
for ($i = 0; $i -lt $groups.Count; $i++){

   try {

        $group = $groups[$i]
        $Gname = $group.Name

       $ExcludeItems = @(“Group 2”,”Group 3”,”Group 4")

     if($Gname -notin $ExcludeItems){

       #delete sharepoint group using powershell
       Write-Host "Deleting group:" $Gname -ForegroundColor Yellow
       $web.SiteGroups.Remove($Gname)
}
    }

catch {
        Write-Host "Error deleting group:" $group.Name -ForegroundColor Red
    }
}

$web.Dispose()
$site.Dispose() 
If you don’t ask, the answer is always NO!
...