Get all Sites and Subsites from SharePoint Online Sites

$User = “”
$Creds = Get-Credentials

$AllSites = @()
function Get-SPOSubWebs{
    $Webs = $RootWeb.Webs
    ForEach ($sWeb in $Webs)
        Write-Output $sWeb
        $SiteObject = [PSCustomObject]@{Site = $sWeb.Url }
        $AllSites +=$SiteObject
        Get-SPOSubWebs -RootWeb $sWeb -Context $Context

Connect-SPOService -Url “” -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
    $SiteObject = [PSCustomObject]@{SiteUrl = $Web.Url }
    $AllSites +=$SiteObject
    Get-SPOSubWebs -RootWeb $Web -Context $ctx   


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

Link on Technet

Leave a Reply

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

You are commenting using your 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