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

Requirement: Often while working with SharePoint Online using PowerShell, we got to loop through each site under a site collection.

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

This script iterates through each subsite and lists 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/projects"
 
#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 the Logo on each subsite: How to Change Logo in SharePoint Online using PowerShell?

How to iterate through all subsites in SharePoint Online using PnP PowerShell?

The PnP PowerShell version of looping through subsites goes like this:

#Parameter
$SiteURL = "https://crescent.sharepoint.com/sites/projects"
 
Try {
    #Connect to PnP Online
    Connect-PnPOnline -Url $SiteURL -Interactive
  
    #Get all subsites in a SharePoint Online site
    $Subsites = Get-PnPSubWeb -Recurse -IncludeRootWeb
      
    #Iterate through each subsite
    ForEach($site in $Subsites)
    {
        Write-host $Site.Url
    }
}
catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

Salaudeen Rajack

Salaudeen Rajack is a SharePoint Architect with Two decades of SharePoint Experience. He loves sharing his knowledge and experiences with the SharePoint community, through his real-world articles!

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

  • 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