SharePoint Online: Loop Through All Subsites in a Site Collection using PowerShell

Requirement: Often while working with SharePoint Online using Client Side object model, we need to loop through each site site under a site collection and here is the PowerShell script to iterate through each subsite and get its title.

PowerShell CSOM Script to Iterate Through All Subsites in a Site Collection in SharePoint Online:

This script iterates through each subsite and list all subsite URLs.

#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

#Variables for Processing
$SiteCollUrl = "https://crescent.sharepoint.com/sites/test/"
 
#Get Credentials to connect
$Cred= Get-Credential
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
 
#Custom function to get all subsites in a given site collection
Function Get-SPOWebs($Url, $Credentials)
{
    #Set up the context
    $Context = New-Object Microsoft.SharePoint.Client.ClientContext($Url) 
    $Context.Credentials = $credentials

    $web = $Context.Web
    $Context.Load($web)
    $Context.Load($web.Webs)
    $Context.ExecuteQuery()

    #Do Something Here
    Write-host $Web.URL

    #Process Each subsite in current site
    ForEach($web in $web.Webs)
    {
        #call the function recursively
        Get-SPOWebs $web.Url $Credentials
    }
} 

#call the function                   
Get-SPOWebs $SiteCollUrl $Credentials

Here is a practical example of looping through all sub-site in a site collection and changing Logo on each subsite: How to Change Logo in SharePoint Online using PowerShell?

Salaudeen Rajack

Information Technology Professional with Two decades of SharePoint Experience.

One thought on “SharePoint Online: Loop Through All Subsites in a Site Collection using PowerShell

  • October 21, 2019 at 11:30 PM

    Could you please let me know how to output this to CSV in the format SiteCollURL SubsiteURL (level does not matter)?

    Reply

Leave a Reply