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 -NoWelcomeConnect-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 -UseWindowsPowerShellConnect-SPOService -Url $SPOAdminRootIf (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 accountsWrite-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 lookupWrite-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 = 0ForEach ($Site in $ODSites) {If (!($UserAccounts.Item($Site.Owner))) { #Allocate a new owner to the OneDrive siteWrite-Host "Adding administator to" $Site.URL$Status = $nullTry {$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 doneSite = $Site.URL"Previous Owner" = $Site.TitleOwnerUPN = $Site.Owner"New Owner" = $NewSiteAdminLastModified = Get-Date($Site.LastContentModifiedDate) -format gStorageUsage = $Site.StorageUsageCurrent }$Report.Add($ReportLine) } # End If} #End If} # End ForEachIf ($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
Author
Office365itpros