Get all Sites and Subsites from SharePoint Online Sites

$User = “admin@M365x086769.onmicrosoft.com”
$Creds = Get-Credentials

$AllSites = @()
function Get-SPOSubWebs{
    Param(
        [Microsoft.SharePoint.Client.ClientContext]$Context,
        [Microsoft.SharePoint.Client.Web]$RootWeb
    )
 
 
    $Webs = $RootWeb.Webs
    $Context.Load($Webs)
    $Context.ExecuteQuery()
 
    ForEach ($sWeb in $Webs)
    {
        Write-Output $sWeb
        $SiteObject = [PSCustomObject]@{Site = $sWeb.Url }
        $AllSites +=$SiteObject
        Get-SPOSubWebs -RootWeb $sWeb -Context $Context
    }
}

Connect-SPOService -Url “https://M365x086769-admin.sharepoint.com” -Credential $Creds
$Sites = Get-SPOSite -Limit All | Select Url
foreach($Site in $Sites)
{
   
    Set-SPOUser -Site $Site.Url -LoginName $Creds.UserName -IsSiteCollectionAdmin $true -Verbose
    $credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Creds.UserName, $Creds.Password)
    $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($Site.Url)
    $ctx.Credentials = $credentials
    $Web = $ctx.Web
    $ctx.Load($Web)
    $ctx.ExecuteQuery()
    $SiteObject = [PSCustomObject]@{SiteUrl = $Web.Url }
    $AllSites +=$SiteObject
    Get-SPOSubWebs -RootWeb $Web -Context $ctx   
}

$AllSites

$AllSites | Export-Csv -Path C:\temp\AllSites.csv -NoTypeInformation –Force

Link on Technet

https://gallery.technet.microsoft.com/Get-all-Sites-and-Subsites-a0972bdb

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s