Below is a script that can get a SharePoint online root site and subsites. How do I get 2 , 3 and 4th level of subsites? For example:

Generate ClientContext function so we can reuse

function GetClientContext($SiteCollectionUrl, $username, $password) 
     $securePassword = ConvertTo-SecureString $password -AsPlainText -Force
     $context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteCollectionUrl) 
     $credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $securePassword) 
     $context.Credentials = $credentials
     return $context

Function to loop through subsites

function catchsubsites ($subsiteurl)
    $clientContext = GetClientContext $subsiteurl $username $password
    $rootWeb = $clientContext.Web
    $childWebs = $rootWeb.Webs
    #do something on top level site
    write-host $rootWeb.url -ForegroundColor Yellow
    foreach ($childWeb in $childWebs)
        #do something for each subsite
        write-host $childWeb.url -ForegroundColor Yellow
        #see if there are any subsites beneath this and loop all of them too
        #catchsubsites $childWeb.url

Finally run the function to get it all started!

catchsubsites $SiteCollectionUrl

2 Answers 2


In your foreach loop, you commented out the line #catchsubsites $childWeb.url. That's the recursive call you need so that you can travel throughout the tree of sites in your collection.


There is generally no need to create ClientContext multiple times. I have tested equivalent code in c# and it worked fine without duplicates (in your current solution if you uncomment recursive call you will have duplicated entries) and with single ClientContext:

function GetSubsitesRecursively($clientContext, $web){
 $subsites = $web.Webs;
 foreach($subsite in $subsites)
    write-host $subsite.Url -ForegroundColor Yellow
    GetSubsitesRecursively $clientContext $subsite 

function GetSitesTree($rootSiteUrl){
 $clientContext = GetClientContext $rootSiteUrl $username $password
 $rootSite = $clientContext.Web

 write-host $rootSite.Url -ForegroundColor Yellow
 GetSubsitesRecursively $clientContext $rootSite

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.