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
$userCredential = Get-Credential -UserName $adminUPN -Message "Type the password."
Connect-SPOService -Url https://$ -Credential $userCredential

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

$site = Get-SPOSite -Identity https://$$siteName
$groups = Get-SPOSiteGroup -Site $site -Limit $batchSize

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

    foreach($group in $groups)
            Write-Output "Skipping protected group $($group.LoginName)"
        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.