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()