Export Site Collection Admins from SharePoint Online Sites

Basic but handy script to export Site Collection Administrators using SharePoint Online Client Object Model and SharePoint Online Management Shell.  I hope there is a better to way get that information as the script can take long time to run if you have large number of users.  I ran the script on multiple tenants with 90K users.  I have a minor updated script that also works for SharePoint Online sites created by Office 365 Groups.

$Creds = Get-Credential

$site = ‘https://tenant.sharepoint.com’
$spoadminsite = ‘https://tenant-admin.sharepoint.com’

Connect-SPOService -Url “https://ucsfonline-admin.sharepoint.com” -Credential $Creds
Connect-MsolService -Credential $Creds

Add-Type -Path “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll”
Add-Type -Path “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll”
Add-Type -Path “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.UserProfiles.dll”

$Sites = Get-SPOSite -Limit All

$OneDriveWithcollection = @()
$SitesData = IMport-csv -Path $OneDrivePath
foreach($Site in $Sites)
    $Url = $Site.Url
    Write-host $Url
    Set-SPOUser -Site $Url -LoginName $Creds.UserName -IsSiteCollectionAdmin $true
    $context = New-Object Microsoft.SharePoint.Client.ClientContext($Url)
    $spoadminusers = Get-SPOUser -Site $Url | where {$_.IsSiteAdmin}
    foreach($Admin in $spoadminusers)
        Write-Host “Site :” $Url
        $OneDriveData = “” | Select “Url” , “OwnerName”, “Email”
        $OneDriveData.Url = $Url
        $OneDriveData.OwnerName = $Admin.LoginName
        $OneDriveData.Email = $Admin.Email   
        $OneDriveWithcollection += $OneDriveData

$OneDriveWithItemsPath= “C:\temp\SPO-SitesAdmins.csv”
$OneDriveWithcollection | Export-Csv $OneDriveWithItemsPath -NoTypeInformation -Encoding UTF8

Update: The script is also available