Getting the owners for all SharePoint sites in tenant using Powershell

I need to get the owners of all SharePoint sites (both classic, modern and SharePoint sites connected to Teams)

I have run the following but it only gives me limited owners and not all the owners and for some sites only listing the site admins as owners instead of the actual site owners. I know and have verified through SharePoint Admin centre that every site has owners/has members in the site owners group.

$AdminCenterURL = “https://XXX-admin.sharepoint.com” ;
$CSVPath = “C:\Temp\SiteOwners.csv”

#Connect to SharePoint Online and Azure AD
Connect-SPOService -url $AdminCenterURL
Connect-AzureAD

#Get all Site Collections
$Sites = Get-SPOSite -Limit ALL

$SiteOwners = @()
#Get Site Owners for each site collection
$Sites | ForEach-Object {
If($.Template -like ‘GROUP*’)
{
$Site = Get-SPOSite -Identity $
.URL
#Get Group Owners
$GroupOwners = (Get-AzureADGroupOwner -ObjectId $Site.GroupID | Select -ExpandProperty UserPrincipalName) -join "; "
}
Else
{
$GroupOwners = $.Owner
}
#Collect Data
$SiteOwners += New-Object PSObject -Property @{
‘Site Title’ = $
.Title
‘URL’ = $_.Url
‘Owner(s)’ = $GroupOwners
}
}
#Get Site Owners
$SiteOwners

#Export Site Owners report to CSV
$SiteOwners | Export-Csv -path $CSVPath -NoTypeInformation

Can anyone help, where I have gone wrong, or let me know if there is a better way?
I need to get all the owners of all the SharePoint sites in the tenancy, there are over 1000 sites in the tenancy

Thanks in advance

Hey Brandccc

Welcome to Powershell.org!

Please take a moment and read the very first post on top of the list of this forum: Read Me Before Posting! You’ll be Glad You Did!.

When you post code, error messages, sample data or console output format it as code, please.
In the “Text” view you can use the code tags “PRE”, in the “Visual” view you can use the format template “Preformatted”. You can go back edit your post and fix the formatting - you don’t have to create a new one.