Removing SharePoint Groups With PowerShell

Recently, I needed to load test a CRM plugin that created groups in SharePoint. The use case of interest is how the plugin performed when many or all of the groups did not currently exist in SharePoint.

The first test went well and we were able to collect the information that we needed. When it was time to redeploy our plugins and test our performance enhancements, we found that all of the SharePoint groups from the previous run were still present.

I started to clear out the groups one by one, only to find that the process is incredibly tedious and time consuming. Those two words set off alarms in my head; when I hear them together, I think “automation”.

Thus, I came up with this little script that:

  1. Connects to SharePoint Online
  2. Gets a small collection of SharePoint Groups
  3. If they are not a protected group, they are removed

Before you run this script, you will need to install the SharePoint Online Management module. Below is the script in full:

# Login Infomation
$adminUPN="james.stephens@mydomain.onmicrosoft.com"
$orgName="myOrg"
$userCredential = Get-Credential -UserName $adminUPN -Message "Type the password."
Connect-SPOService -Url https://$orgName-admin.sharepoint.com -Credential $userCredential

# Site Connection
$webName = "myWeb"
$siteName = "mySite"
$batchSize = 10

$site = Get-SPOSite -Identity https://$webName.sharepoint.com/sites/$siteName
$groups = Get-SPOSiteGroup -Site $site -Limit $batchSize

$protectedGroups = @("siteName Members", "siteName Owners", "siteName Visitors")

do 
{
    foreach($group in $groups)
    {
        if($protectedGroups.Contains($group.LoginName))
        {
            Write-Output "Skipping protected group $($group.LoginName)"
            continue
        }
    
        Write-Output "Removing group $($group.LoginName)"
        Remove-SPOSiteGroup -Site $site -Identity $group.LoginName
    }

    Write-Output "Getting next batch..."

    $groups = Get-SPOSiteGroup -Site $site -Limit $batchSize
} while ($groups.Length -gt $protectedGroups.Length)

Using this, I was able to save hours of clicking for me and my coworkers!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.