How to remove SCA users from Site Collection Admins?

Summary

This is kind of similar requirement from my previous blog article.

How to remove users from multiple Azure AD Groups?

But in this article I will provide only the code for removing the Site collection Admins from SharePoint Site. The steps for running this code is same as the above article.

$Users2Remove = (
    "BobK.GOV963094.onmicrosoft.com",
    "DebraB.GOV963094.onmicrosoft.com"
)

$ClientId = "7c244c08-9875-4ffe-b39d-34f9b6853f6b"
$Tenant = "gov963094.onmicrosoft.com" # replace your tenant name

Import-Csv C:\Contoso\teamSites.CSV | 
    ForEach-Object {
        try
        {
            $newSiteUrl = $_.SiteURL
            $newSiteConn = Connect-PnPOnline -ClientId $ClientId -Url $newSiteUrl -Tenant $tenant -CertificatePath 'MyPnPApplication.pfx' -ReturnConnection

            # Get the site collection administrators  
            $scaColl = Get-PnPSiteCollectionAdmin -Connection $newSiteConn
            foreach($sca in $scaColl)  
            {          
                Write-Host $sca.LoginName
                $modifiedLoginName = $sca.LoginName
                $modifiedLoginName = $modifiedLoginName -replace "i:0#.f\|membership\|", ""
        
                if ( ( $Users2Remove -contains  $modifiedLoginName ) -eq $true )
                {
                    Write-Host $("Remove {0}" -f $sca.LoginName)
                    Remove-PnPSiteCollectionAdmin -Owners $sca.LoginName
                    Write-Host $("Removed..")
                }
            }         
        }
        catch
        {
            $ErrorMessage = $_.Exception |  Out-String
            Write-Host $("Exception {0}" -f $ErrorMessage);
        }
        finally
        {
            Write-Host $("Disconnecting to {0}" -f $newSiteUrl);
            Disconnect-PnPOnline -Connection $newSiteConn
            Write-Host $("Disconnected to {0}" -f $newSiteUrl);
        }
    }

About Pankaj

I am a Developer and my linked profile is https://www.linkedin.com/in/pankajsurti/
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s