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 = ""
#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

    #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:

$SiteURL = ""
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 - SharePoint Expert with Two decades of SharePoint Experience. Love to Share my knowledge and experience with the SharePoint community, through real-time articles!

3 thoughts on “SharePoint Online: Loop Through All Subsites in a Site Collection using PowerShell

  • I am trying to nest inside foreach site in subsite a foreach list in subsite, but it keeps displaying the root web lists for each subsite, not the lists in each web/subsite… how do I load the lists for the current foreach $site

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


Leave a Reply

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