SharePoint Online: Find and Delete Orphaned Users using PowerShell
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 $ReportOutputThis script checks each and every user of the given site collection and generates a CSV file:
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 Orphan Users!" $_.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 $ReportInputYou 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 }
Oh awesome! This is great information. Thanks much for sharing such an informative post about SharePoint Online. In addition, I really thank you for defining "Orphaned Users" in SharePoint Online and explaining on how to find and delete the orphaned users in SharePoint Online using PowerShell. Great help!
ReplyDeleteThis is so great! One question: where do I add this line?
ReplyDeleteGet-SPOSite -Limit all | ForEach-Object {
#Call the function to find and generate orphaned users report
Generate-OrphanedUsersReport -AdminURL $AdminURL -SiteURL $_.Url -ReportOutput $ReportOutput
}
At the end of First script in this post, paste these lines from Line#79
DeleteI'm pretty sure that will just overwrite the csv file for each site collection?
DeleteThanks for the script Salaudeen, its great !
Yes! Use: -Append switch in Export-CSV cmdlet.
Delete$OrphanedUsers | Export-csv $ReportOutput -append -notypeinformation
Hi , Please can you help em to delete the Orphaned users. I used above scripts i could able to get the list orphaned users . but while using delete the user as given below script i have error msg like "Error deleting unique permissions!Could not find file "C:temp\one.csv"
ReplyDelete#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://xyz-admin.sharepoint.com"
$SiteURL = "https://xyz.sharepoint.com/sites/dummysite"
$ReportInput="C:\temp\one12345678.csv"
#Call the function to Remove Orphaned users
Remove-OrphanedUsers -AdminURL $AdminURL -SiteURL $SiteURL -ReportInput $ReportInput
As the Error message says: Could not find file "C:temp\one.csv", Make sure you have the one.CSV file at "C:\temp\one.csv" with all orphan users list.
DeleteThanks for your help. Here, as per your script for multiple site collection it's keep on asking user ID and pwd for each site.
ReplyDeleteGet-SPOSite -Limit all | ForEach-Object {
#Call the function to find and generate orphaned users report
Generate-OrphanedUsersReport -AdminURL $AdminURL -SiteURL $_.Url -ReportOutput $ReportOutput
}
However, we have more than 2000+ site collections. so it's difficult to identify the orphaned users for 2000+ sites.Here, I have modified script but it's not working .Please refer the below.
#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 = @()
#Create a Txt File with multiple Site URL's
$SiteURLs= Get-Content "E:\Siteurl.txt"
Foreach($SiteURL in $ SiteURLs)
{
#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://abcd-admin.sharepoint.com"
$SiteURL = "https://abcd.sharepoint.com/sites/abcd1"
$ReportOutput="E:\OrphanedUserslist/Testurlslist.csv"
#Call the function to find and generate orphaned users report
Generate-OrphanedUsersReport -AdminURL $AdminURL -SiteURL $SiteURL -ReportOutput $ReportOutput
great script, is there any way to do the same process but with PnP? Thanks.
ReplyDeleteThere are not cmdlets available to find and remove orphaned users. But you can use "Remove-PnPUser" to remove any user from site collection.
DeleteThanks Salaudeen.....
DeleteHi, the remove script doesn't work for me
ReplyDeleteI get this error=
Error Deleting Orphan Users! Cannot bind argument to parameter 'LoginName' because it is null.
Any idea?
The "LoginName" column from the CSV file is populated from the first script in this article. Make sure you have the correct Login Names populated!
DeleteThe CSV file was correctly generated by the first script.
DeleteIt looks like this
LoginName,"DisplayName"
[email protected],"firstname lastname"
Looks fine to me, don't understand why I'm getting this error
Can we run this powershell as job on daily basis. Where can we keep and how can we run it daily automatically?
ReplyDeleteYes, You can schedule the script in Windows Task scheduler: How to Schedule PowerShell Script in Windows Task Scheduler?
DeleteIs there a way to replace the orphaned user with active user instead of deletion at library level?
ReplyDeleteIs there a way we can provide input file to get report on orphan users?
ReplyDeleteNice article! Have you thought about making a version of the script that would use App permissions? Is it possible?
ReplyDeleteNice article! Have you thought about making a version of the script that would use App permissions? Is it possible?
ReplyDelete