Thursday, January 4, 2018

SharePoint Online: Find and Delete Orphaned Users using PowerShell

find and delete orphaned users in sharepoint online

What is "Orphaned Users" in SharePoint Online?
In short, Orphaned users are those who deleted from the authentication provider (such as removed from Active Directory when user leaves the organization), and still continue to exist in SharePoint online sites! scanning each user in SharePoint online site collection for orphaned users could take days to complete! Since, Here is my PowerShell script to search for orphan users and delete them.

Pr-Requisites: Before using this script, you need to have SharePoint Online Management Shell (https://www.microsoft.com/en-us/download/details.aspx?id=35588) and Azure Active Directory Module (https://technet.microsoft.com/en-us/library/dn975125.aspx) installed on your machine!

Find Orphan Users in SharePoint Online using PowerShell:
This script scans each and every user from the given site collection URL and exports list of orphaned users to a CSV file.

#Import SharePoint Online and Azure Online modules
Import-Module Microsoft.Online.SharePoint.Powershell
Import-Module MSOnline

Function Generate-OrphanedUsersReport ()
{
param
    (
        [Parameter(Mandatory=$true)] [string] $AdminURL,
        [Parameter(Mandatory=$true)] [string] $SiteURL,
        [Parameter(Mandatory=$true)] [string] $ReportOutput        
    )
Try {
    #Get Credentials to connect
    $Cred = Get-Credential

    #Connect to SharePoint and Azure AD
    Connect-MsolService -Credential $cred
    Connect-SPOService -Url $AdminURL -Credential $Cred

    #Function to check if a user account exists
    Function Check-UserExists()
    {
        Param( [Parameter(Mandatory=$true)] [string]$UserID )
    
        $User=Get-Msoluser -UserPrincipalName $UserID -Erroraction SilentlyContinue
        if ($User -ne $null)
        {
            Return $True
        }
        else
        {
            Return $false
        }
    }
    $OrphanedUsers = @()

    #Get all users of a given SharePoint Online site collection
    $AllUsers = Get-SPOUser $SiteURL -Limit ALL

    Foreach($User in $AllUsers)
    {
        #Exclude Built-in User Accounts and Security Groups 
        if(($User.DisplayName.ToLower() -ne "nt authority\authenticated users") -and ($User.LoginName.ToLower() -ne "sharepoint\system") -and 
        ($User.DisplayName.ToLower() -ne "sharepoint app") -and ($user.IsGroup -eq $false ) -and(-not $user.DisplayName.ToLower().Contains("_spocache")) -and 
        (-not $user.DisplayName.ToLower().Contains("_spocrawl")) -and ($User.DisplayName.ToLower() -ne "sharepoint service administrator") -and 
        ($User.DisplayName.ToLower() -ne "guest contributor") -and ($User.DisplayName.ToLower() -ne "everyone except external users")-and ($User.DisplayName.ToLower() -ne "company administrator"))
        {
            Write-host "Checking user $($user.DisplayName)" -f Yellow
            #Check if user exists
            if((Check-UserExists $User.LoginName) -eq $False)
            {
                Write-Host "User Doesn't Exists: $($user.DisplayName) - $($User.LoginName)" -f Red

                #Send the Result to CSV 
                $Result = new-object PSObject
                $Result| add-member -membertype NoteProperty -name "LoginName" -Value $User.LoginName
                $Result | add-member -membertype NoteProperty -name "DisplayName" -Value $User.DisplayName
                $OrphanedUsers += $Result
            }
        }
    }
    #Export results to CSV
    $OrphanedUsers | Export-csv $ReportOutput -notypeinformation

        Write-host "Orphan Users Report Generated to $ReportOutput" -f Green
   }

    Catch {
    write-host -f Red "Error Deleting Unique Permissions!" $_.Exception.Message
    }
}

#Config Parameters
$AdminURL ="https://crescent-admin.sharepoint.com"
$SiteURL = "https://crescent.sharepoint.com"
$ReportOutput="C:\Temp\OrphanUsers.csv"

#Call the function to find and generate orphaned users report
Generate-OrphanedUsersReport -AdminURL $AdminURL -SiteURL $SiteURL -ReportOutput $ReportOutput
Be sure the CSV generated doesn't include any built-in user accounts and groups, prior providing the CSV file as an input to the next step of removing orphan users!

How to Delete Orphan Users from SharePoint Online with PowerShell: 
While its possible to remove each user from SharePoint online site collection individually, it becomes cumbersome when we have large number of orphan users to  remove! Here is the PowerShell script to read orphan users from the CSV file generated in previous step and remove them all in one go!
#Import SharePoint Online module
Import-Module Microsoft.Online.SharePoint.Powershell

Function Remove-OrphanedUsers ()
{
param
    (
        [Parameter(Mandatory=$true)] [string] $AdminURL,
        [Parameter(Mandatory=$true)] [string] $SiteURL,
        [Parameter(Mandatory=$true)] [string] $ReportInput        
    )
    Try {
        #Get Credentials to connect
        $Cred = Get-Credential
   
        #Connect to SharePoint online
        Connect-SPOService -Url $AdminURL -Credential $Cred

        #Get the Data from CSV and Add to SharePoint List
        $OrphanUsers = Import-Csv $ReportInput
        Foreach ($Row in $OrphanUsers) 
        {
            #Remove user from site
            Remove-SPOUser -Site $SiteURL -LoginName $Row.LoginName
            Write-host "Removed the Orphaned User $($Row.DisplayName) from $($SiteURL)"   
        }
            Write-host "Orphaned Users Removed from SharePoint Online Site!"
       }
    Catch {
    write-host -f Red "Error Deleting Unique Permissions!" $_.Exception.Message
    }
}

#Config Parameters
$AdminURL ="https://crescent-admin.sharepoint.com"
$SiteURL = "https://crescent.sharepoint.com"
$ReportInput="C:\Temp\OrphanUsers.csv"

#Call the function to Remove Orphaned users
Remove-OrphanedUsers -AdminURL $AdminURL -SiteURL $SiteURL -ReportInput $ReportInput
You can use these functions to find and/or remove orphaned users from all site collections. Just add:
Get-SPOSite -Limit all | ForEach-Object { 
  #Call the function to find and generate orphaned users report
  Generate-OrphanedUsersReport -AdminURL $AdminURL -SiteURL $_.Url -ReportOutput $ReportOutput
}



You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Check out these SharePoint products:

No comments :

Post a Comment

Please Login and comment to get your questions answered!


You might also like:

Related Posts Plugin for WordPress, Blogger...