Cleaning Up SharePoint Orphaned Users After Migration using PnP PowerShell

Loading

After migrating to SharePoint Online, some users may become orphaned—users who no longer exist in Azure AD but still appear in SharePoint permissions or people picker. These orphaned users can cause security risks and access errors.

Using PnP PowerShell, we can identify and remove orphaned users efficiently, ensuring a clean and secure SharePoint environment.


Step 1: Connect to SharePoint Online

To clean up orphaned users, first, connect to your SharePoint Online site.

$siteUrl = "https://yourtenant.sharepoint.com/sites/MigratedSite"
Connect-PnPOnline -Url $siteUrl -Interactive

✔ Ensures secure authentication for accessing SharePoint.


Step 2: Retrieve All Users from SharePoint

Fetch the list of all users in the SharePoint site.

$users = Get-PnPUser
$users | Select LoginName, Title, Email | Format-Table -AutoSize

✔ Displays all users assigned to the SharePoint site.


Step 3: Identify Orphaned Users

An orphaned user exists in SharePoint but is missing from Azure AD. To check:

$orphanedUsers = @()

foreach ($user in $users) {
$aadUser = Get-MgUser -Filter "UserPrincipalName eq '$($user.LoginName)'" -ErrorAction SilentlyContinue

if (-not $aadUser) {
$orphanedUsers += $user
}
}

$orphanedUsers | Select LoginName, Title, Email | Format-Table -AutoSize

✔ Lists users who no longer exist in Azure AD.


Step 4: Export Orphaned Users to CSV (Optional)

Save the orphaned users report for review.

$orphanedUsers | Export-Csv -Path "C:\SharePoint_Audit\OrphanedUsers.csv" -NoTypeInformation
Write-Host " Orphaned Users Report Generated"

✔ Provides a backup before deletion.


Step 5: Remove Orphaned Users

To remove orphaned users safely, use:

foreach ($user in $orphanedUsers) {
Remove-PnPUser -LoginName $user.LoginName -Force
Write-Host " Removed orphaned user: $($user.LoginName)"
}

✔ Ensures only orphaned users are removed.


Step 6: Verify Cleanup

Re-run the Step 2 script to confirm removal.

$users = Get-PnPUser
$users | Select LoginName, Title, Email | Format-Table -AutoSize

✔ Ensures orphaned users are no longer in SharePoint.


Step 7: Automate Cleanup with Scheduled Task

To automate cleanup monthly, follow these steps:

1️⃣ Save script as CleanOrphanedUsers.ps1.
2️⃣ Open Task Scheduler → Create Basic Task.
3️⃣ Set Trigger → Monthly.
4️⃣ Action → Start a program → powershell.exe -File C:\Scripts\CleanOrphanedUsers.ps1.
5️⃣ Allow script execution:

Set-ExecutionPolicy RemoteSigned -Scope CurrentUser

✔ Keeps SharePoint clean and secure automatically.

Leave a Reply

Your email address will not be published. Required fields are marked *