kwizcom banner advertisement

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 get all subsites from a site collection in SharePoint Online:
This script iterates through each subsite and list all subsites
#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?
SharePoint Online: Loop Through All Subsites in a Site Collection using PowerShell SharePoint Online: Loop Through All Subsites in a Site Collection using PowerShell Reviewed by Salaudeen Rajack on January 29, 2017 Rating: 5

No comments:

Please Login and comment to get your questions answered!

Powered by Blogger.