Remove a site admin from all SharePoint online sites using PowerShell

This is a PowerShell script to remove a site admin from all sites in SharePoint online.

You may find an account which has been added to every site as a site admin. This can happen when a user is added to SharePoint Admin role group, and they are no longer required. Even when the account is remove it may remain stamped across all of your sites.

This script can report on all the site admins for your SharePoint sites, and also optionally remove a site admin if there’s one you want to remove from every site. It can easily used for individual sites as well.

This requires the SharePoint Online Management Shell, see https://docs.microsoft.com/en-us/powershell/sharepoint/sharepoint-online/connect-sharepoint-online?view=sharepoint-ps if you need to install that.

So without further ado, here is the script.

# Script to remove an admin from all sharepoint sites, or just report on all the site admins

Import-Module "Microsoft.Online.SharePoint.PowerShell"

write-host "Connecting to SharePoint (SPOService)..." -ForegroundColor Yellow

$sharepointadmin = "https://tenant-admin.sharepoint.com"

try { 
    $var = Get-SPOGeoStorageQuota # Just using this as it is quick to test connection
} 
catch {
    Write-Host "Not connected, authenticate in other window"; Connect-SPOService -Url $sharepointadmin
}



# UPN of the user who we want to remove from being a site admin
$siteadmin = "[email protected]"

$timestamp = (Get-Date).ToString('MM.dd.yyyy,hh.mm.ss.tt')
$logfile = "c:\temp\Logs\SiteAdmins$timestamp.csv" # make sure this folder exists

write-host "Processing..."

$sites= Get-SPOSite -Limit All -Filter { Url -notlike "*-my.sharepoint.com*" }   # Get all sites excluding onedrive
#$sites = Get-SPOSite -Identity https://tenant.sharepoint.com/sites/sitename # or just get one site
foreach ($site in $sites)
{
$site.Url
$allusers = Get-SPOUser -Site $site.Url -Limit all | Where-Object {$_.IsSiteAdmin -eq $true} | select DisplayName,LoginName,IsSiteAdmin
foreach ($user in $allusers) {
    $array += @( @{DisplayName=$user.DisplayName;LoginName=$user.LoginName;IsSiteAdmin=$user.IsSiteAdmin;URL=$site.Url})
    # Remove this loop if you just want to report
    if ($user.LoginName -eq $siteadmin) {
        write-host "Removing site admin $siteadmin from"$site.Url
        Set-SPOUser -Site $site -LoginName $siteadmin -IsSiteCollectionAdmin $false
    }

}

}
write-host "List of site admins"
$array | ForEach-Object {[PSCustomObject]$_} | Sort-Object URL | Format-Table DisplayName,LoginName,IsSiteAdmin,URL
$array | ForEach-Object {[PSCustomObject]$_} | select-object DisplayName,LoginName,IsSiteAdmin,URL | Sort-Object DisplayName | export-csv $logfile -NTI

Posted in Office 365, SharePoint

Related Posts

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.