How to find and delete Orphaned Users from SharePoint Online

Featured image

Most companies face the challenge in identifying and clean-up of Orphaned user accounts of their employees to prevent any possible security breach and to optimize the resource usage. Orphaned Users - When user account is removed from the Office 365 admin center, but the corresponding account still exists in SharePoint Online as Site User. So in this blog, we use PowerShell script for listing and deleting Orphaned users from SharePoint Online Site Collection.

Before starting the process, download and install the SharePoint Online Management Shell from this link and execute the following PowerShell Scripts in the SharePoint Online Management Shell by connecting to SharePoint Online using Global Administrator credentials.

How to find and delete Orphaned Users from SharePoint Online Site Collection

Input Parameters Required $domainname - Office 365 domain name (“tenantname.com” or “tenantname.onmicrosoft.com”) $Sitename - SharePoint Online Site Collection URL (Ex - https://tenantname.sharepoint.com) $Output - File path to store the list of Orphaned Users (Ex - D:\Foldername\OrphanedUsers.txt)

Following PowerShell script is used to find and delete Orphaned Users from SharePoint Online Site Collection,

NOTE: It is recommended to execute the below script as .ps1 file with elevated privilege (Run as Administrator).

Copy the below script to notepad and save it as .ps1 file or download ps1 from here.

step 1 :Get the Domain name

$url=Read-Host "Enter the admin URL(https://domainanme-admin.sharepoint.com):"
Import-Module Microsoft.Online.SharePoint.Powershell -Verbose
Import-Module MSOnline
$cred= Get-Credential

step 2 :Connecting Msol Service

Connect-MsolService -Credential $cred

step 3 :Connecting SharePoint Online Service

Connect-SPOService -Url $url -Credential $cred 

step 4 :Get Site Collection URL

$Sitename=Read-Host "Enter the Site Collection URL:"

step 5 :Get file Path for store output

$Output = Read-Host "Enter the Path to Store the Result:"
$strOut = "User Name"+"`r`n"

step 6 :Checking Sharepoint User in Azure AD

function Checkorphaneduser()
{
    Param( [Parameter(Mandatory=$true)] [string]$AzureUser )
    
    $ADUser=Get-Msoluser -UserPrincipalName $AzureUser -Erroraction SilentlyContinue
    if ($ADUser -ne $null)
         {
           return $true
         }
         Else
         {
         return $false 
         }
    }

step 7 :Get Orphaned Users from Site Collection

$Users = Get-SpoUser "$Sitename"         
$OrphanedUsers = @()
foreach($User in $Users)
    {
        #Exclude Built-in User Accounts , Security Groups 
        if(($User.DisplayName.ToLower() -ne "nt authority\authenticated users") -and
          ($User.LoginName.ToLower() -ne "sharepoint\system") -and
          ($User.LoginName.ToLower() -ne "App@Sharepoint") -and
          ($User.LoginName.ToLower() -notlike "ylo001\_spocrwl*") -and
          ($user.IsGroup -eq $false ) #-and
           )
        {
          $AccName = $User.LoginName    #UserName
            if ( ( Checkorphaneduser $AccName) -eq $false )
            {
                Write-Host "$($User.LoginName) from $($Sitename) doesn't Exists in Azure AD!"
                
                  $strOut += $User.LoginName+"`r`n"
                   $strOut|Out-File $Output                   
                  $OrphanedUsers+=$User.LoginName
            }
            }
        }

step 8 :Remove Orphaned Users from Site Collection

if($OrphanedUsers.Count -eq 0)
{
Write-host "There is no Orphaned user in $($Sitename)"
}
Else
{
   $Remove=Read-Host "Do You want remove Orphaned Users Yes:No :"
   If($Remove.ToUpper() -eq "YES")
      {
            
           foreach($OrpUser in $OrphanedUsers)
           {
            Remove-SPOUser -Site $Sitename -LoginName $OrpUser
           Write-host "Removed the Orphaned user $($OrpUser) from $($Sitename) "
           }
       }
   Else{
      }
     }
      Get-pssession |Remove-PSSession