Forum Discussion

michael1900's avatar
michael1900
Copper Contributor
Feb 24, 2023

SharePoint Online: Get the Site Owner using PowerShell

Need powershell code to  Get the Site Owner using PowerShell .

I tried to using below code but the data is no accurate and no incorrect .

 

#Variables for Admin Center

$AdminCenterURL = https://89889-admin.sharepoint.com

$CSVPath = "c:/temp/danny.csv"

 

#Get Credentials to connect

$Cred = Get-Credential

 

#Connect to SharePoint Online and Azure AD

Connect-SPOService -url $AdminCenterURL -Credential $Cred

Connect-AzureAD -Credential $Cred | Out-Null

  

#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 -Encoding utf8 -Append

 

Need other code to help catch the sharepoint owner/site admin with accurate .

 

 

 

  • AndySvints's avatar
    AndySvints
    Steel Contributor

    Hello michael1900,

    One of the options to get Site Admins is to get list of all members of the site and then identify who has IsSiteAdmin property equal to True:

    $SiteAdmins = (Get-SPOUser -Site $URL -Limit ALL | Where-Object { $_.IsSiteAdmin -eq $True} 

    Here is your code with the added line:

    $AdminCenterURL = "https://<TenantName>-admin.sharepoint.com/"
    $CSVPath = "c:/temp/danny.csv"
    Connect-SPOService -url $AdminCenterURL
    Connect-AzureAD
    $Sites = Get-SPOSite -Limit ALL
    $Results = New-Object 'System.Collections.Generic.List[psobject]'
    
    forEach($s in $Sites) {
        If($_.Template -like 'GROUP*')
        {
            $GroupOwners = (Get-AzureADGroupOwner -ObjectId $s.GroupID | Select -ExpandProperty UserPrincipalName) -join "; "     
    
        }
        Else{
            $GroupOwners = $s.Owner
        }
        $SiteAdmins = (Get-SPOUser -Site $s.URL -Limit ALL | Where-Object { $_.IsSiteAdmin -eq $True} | Select-Object -ExpandProperty DisplayName) -join "; "
        $Results.Add( $(New-Object PSObject -Property $([ordered]@{
        'Site Title' = $s.Title
        'URL' = $s.Url
        'Owner(s)' = $GroupOwners
        'Admin(s)' = $SiteAdmins
        })))
    }
    $Results| Export-CSV -path $CSVPath -NoTypeInformation -Encoding utf8

    Hope that helps.

Resources