Saturday, May 25, 2024
HomeMicrosoft 365How to Delete Orphan Users from SharePoint Online with PowerShell

How to Delete Orphan Users from SharePoint Online with PowerShell

#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 Orphan Users!" $_.Exception.Message
    }
}
 
#Config Parameters
$AdminURL ="https://test-admin.sharepoint.com"
$SiteURL = "https://test.sharepoint.com"
$ReportInput="C:\Temp\OrphanUsers.csv"
 
#Call the function to Remove Orphaned users
Remove-OrphanedUsers -AdminURL $AdminURL -SiteURL $SiteURL -ReportInput $ReportInput

Most Popular