Back to script library
Entra / Microsoft 365 · SharePoint & OneDrive

Find orphan OneDrive for Business sites

Find orphan OneDrive for Business accounts and add an admin user so the sites can be accessed and managed.

Connect & set up

Run these once per session. All scopes are read-only unless the script makes changes.

Connect-MgGraph -Scopes User.Read.All, Organization.Read.All -NoWelcome
Connect-SPOService -Url $SPOAdminRoot

Run it

The main script. Copy it, or download the .ps1 and run it from your console.

Connect-MgGraph -Scopes "User.Read.All", "Organization.Read.All" -NoWelcome
# Define the account to add to each orphan site
$NewSiteAdmin = "Administrator@office365itpros.com"
[array]$Domains = (Get-MgOrganization).verifiedDomains
$DefaultDomain = $Domains | Where-Object {$_.IsDefault -eq $true}
$SPOAdminRoot = ("https://{0}-admin.sharepoint.com" -f $DefaultDomain.Name.split('.')[0])
Write-Host "Connecting to SharePoint Online..."
Import-Module Microsoft.Online.SharePoint.PowerShell -UseWindowsPowerShell
Connect-SPOService -Url $SPOAdminRoot
If (Get-SPOTenant) {
Write-Host ("Connected to SharePoint Online at {0}" -f $SPOAdminRoot)
} Else {
Write-Host "Failed to connect to SharePoint Online"
Break
}
# Create list for output report
$Report = [System.Collections.Generic.List[Object]]::new()
# Find OneDrive for Business accounts
Write-Host "Finding OneDrive for Business accounts..."
[array]$ODSites = Get-SPOSite -IncludePersonalSite $True -Limit All -Filter "url -like '-my.sharepoint.com/personal/'"
# Find Entra ID acounts and create hash table for lookup
Write-Host "Finding Entra ID user accounts..."
[array]$Users = Get-MgUser -All -Filter "Usertype eq 'Member'" -Property Id, DisplayName, UserPrincipalName
$UserAccounts = @{}
$Users.ForEach( {
$UserAccounts.Add([String]$_.UserPrincipalName, $_.DisplayName) } )
# Process the sites
[int]$i = 0
ForEach ($Site in $ODSites) {
If (!($UserAccounts.Item($Site.Owner))) { #Allocate a new owner to the OneDrive site
Write-Host "Adding administator to" $Site.URL
$Status = $null
Try {
$Status = Set-SPOUser -Site $Site.URL -LoginName $NewSiteAdmin -IsSiteCollectionAdmin $True -ErrorAction Stop
}
Catch {
Write-Host "Couldn't add" $NewSiteAdmin "to" $Site.URL -ForegroundColor Red
}
If ($Status) { #Update output report file
$i++
$ReportLine = [PSCustomObject]@{ #Update with details of what we have done
Site = $Site.URL
"Previous Owner" = $Site.Title
OwnerUPN = $Site.Owner
"New Owner" = $NewSiteAdmin
LastModified = Get-Date($Site.LastContentModifiedDate) -format g
StorageUsage = $Site.StorageUsageCurrent }
$Report.Add($ReportLine) } # End If
} #End If
} # End ForEach
If ($i -gt 0) {
Write-Host $NewSiteAdmin "added to" $i "OneDrive for Business accounts - details in c:\temp\OrphanOneDrive.csv"
$Report | Export-CSV -NoTypeInformation c:\temp\OrphanOneDrive.csv }
Else {
Write-Host "No orphan OneDrive for Business accounts found"
}
Attribution