Hub Sites – Get Site Structure with PowerShell

Hub Sites – Get Site Structure with PowerShell

Like so many other Office 365 nerds, I have been playing around with the new hub sites for a couple of weeks. While I do see a lot of potential in the new feature, it still requires some fine tuning and (as always) some more customizing capabilities.

One of the main goals of the hub sites is to bring in some sort of site structure. But where can I find this site structure? What I was basically looking for, was a sitemap. Neither the PowerShell commands or REST API offers a possibility to get the structure of all sites.

Furthermore it is not possible to find all sites associated with a specific hub site.

The solution

The PowerShell command Get-SPOHubSite allows us to see if the site is a hub site, or if the site is associated with a hub site.

I am no PowerShell master, but managed to hack together a small script, which returns the site structure (could easily be changes/expanded to return all sites associated with a hub site).

The script writes the whole structure to a .txt file.

#Separate Hub Site Structured sites from non-structured sites
$structured = @()
$unstructured = @()

#Get All sites in Tenant
Get-SPOSite | ForEach {

    #Get the URL of each site
    $siteUrl =  $_.Url
    
    try{
        #Check if the site is a hub site or associated with one (expection, if not)
        $hubsite = Get-SPOHubSite $siteUrl
        
        #Check if the HubSite has already been added
        if($structured.SiteUrl -ne $hubsite.SiteUrl){
        
            #if not, add the hubsite
            [System.Collections.ArrayList]$arrList=@()
            $hubsite | Add-Member -MemberType NoteProperty -Name AssocSites -value $arrlist
            $structured += $hubsite
            
        }
        
        #Don't add the hubsite as an associated site
        if($_.Url -ne $hubsite.SiteUrl){
            ($structured | Where-Object { $_.SiteUrl -eq $hubsite.SiteUrl }).AssocSites += $_
        }
        
    }
    
    #If not a hub site 
    catch{
        $unstructured += $siteUrl
    }
}

#Output in text file
$output = ""
$structured | ForEach {
    $output += $_.Title + " - " + $_.SiteUrl + $("" | Out-String)
    $_.AssocSites | ForEach {
        $output += "    " + $_.TItle + " - " + $_.Url + $("" | Out-String)
    }
    $output += $("" | Out-String)
}
 
$output | Out-File C:\temp\site-structure.txt

I would appreciate feedback on the script! There are things which haven’t been done according to best practice, let me know, so it can be improved!

The PowerShell can also be found on GitHub: https://github.com/nannerup/sp-hubsites-tenant-structure

One thought on “Hub Sites – Get Site Structure with PowerShell

Leave a Reply

Your email address will not be published. Required fields are marked *