Get all subsites from a site collection in SharePoint Online using CSOM

This SharePoint CSOM tutorial, we will discuss how to get all subsites from a site collection in SharePoint Online using .net managed object model (csom). Also, we will see how to get all subsites under a site collection using PowerShell in SharePoint Online Office 365.

We will see how to retrieve all sites excluding the apps or add-in websites from a SharePoint Online site using.Net managed code in SharePoint Online.

Here I will create a console application to run the csom code and we will connect to the SharePoint Online sites.

Get all subsites from a site collection in SharePoint using CSOM

Whenever you will try to retrieve all the subsites of a site collection in SharePoint programmatically using .Net managed object model (csom) code, it will return all the subsites as well as it will return all the apps or add-in websites if you have deployed any SharePoint hosted add-in.

In this SharePoint site collections, I have deployed some SharePoint hosted add-ins.

If you will run the below code it will give you all the sites including the Add-in webs of the site collection from SharePoint Online.

public static void GetAllSubSites()
{
Hashtable mySites = new Hashtable();
ClientContext context = new ClientContext("https://onlysharepoint2013.sharepoint.com/sites/Bhawana");
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
var web = context.Web;
context.Load(web, w => w.Webs);
context.Load(web, w => w.WebTemplate);
context.ExecuteQuery();
foreach (Web orWebsite in web.Webs)
{
if (orWebsite.WebTemplate != "APP")
{
context.Load(orWebsite, w => w.Title, w => w.Url);
context.ExecuteQuery();
mySites.Add(orWebsite.Url, orWebsite.Title);
}
}
}

private static SecureString GetSPOSecureStringPassword()
        {
            try
            {
                var secureString = new SecureString();
                foreach (char c in "MyPassword")
                {
                    secureString.AppendChar(c);
                }
                return secureString;
            }
            catch
            {
                throw;
            }
        }

        private static string GetSPOAccountName()
        {
            try
            {
                return "bijay@<tenantname@onmicrosoft.com>";
            }
            catch
            {
                throw;
            }
        }

All the sites you can see like below:

get all subsites in sharepoint online csom

But sometimes we might not need all our Add-in webs. So we can filter based on the Site template while retrieving all the subsites programmatically in SharePoint.

public static void GetAllSubSites()
{
Hashtable mySites = new Hashtable();
ClientContext context = new ClientContext("https://onlysharepoint2013.sharepoint.com/sites/Bhawana");
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
var web = context.Web;
context.Load(web, w => w.Webs);
context.ExecuteQuery();
foreach (Web orWebsite in web.Webs)
{
context.Load(orWebsite, w => w.Title, w => w.Url);
context.ExecuteQuery();
mySites.Add(orWebsite.Url, orWebsite.Title);
}
}

private static SecureString GetSPOSecureStringPassword()
        {
            try
            {
                var secureString = new SecureString();
                foreach (char c in "MyPassword")
                {
                    secureString.AppendChar(c);
                }
                return secureString;
            }
            catch
            {
                throw;
            }
        }

        private static string GetSPOAccountName()
        {
            try
            {
                return "bijay@<tenantname@onmicrosoft.com>";
            }
            catch
            {
                throw;
            }
        }

Now if you will check I have only 3 sites which it is returning and is required.

Get all subsites from a site collection in SharePoint Online using CSOM

Get Subsites of a SharePoint Online Site Collection using PowerShell

This PowerShell SharePoint Online tutorial explains how to get or retrieve all the subsites from a site collection in SharePoint Online Office 365 using PowerShell.

A user wants to see the list of all the subsites in a given Site Collection in SharePoint Online. It is unfortunate that my site collection was pretty old and was filled with many subsites with multiple levels. So it is closely impossible to harvest the information manually without any slippage.

Below is the PowerShell Script to retrieve subsites from a SharePoint Online site collection.

<# This Script is to get all the subsites in a given site collection from SPO #>

function GetSubSiteDetails {
try {
#Reading artifacts/prerequisites
$strSiteCollURL = Read-Host "Enter the Site Collection URL of SPO (eg. https://onlysharepoint2013.sharepoint.com/sites/krishna)"
$strUserId = Read-Host "Enter the username of SPO (eg. userName@OnlySharePoint2013.onmicrosoft.com)"
$strPassword = Read-Host "Please enter the password for $($strUserId)" -AsSecureString

$startedTime = Get-Date
Write-Host "Time Started = " $startedTime
Write-Host "`nAll the Sub Sites in Site Collection $($strSiteCollURL) are::"

#Add references to SharePoint client assemblies and authenticate to Office 365 site – required for CSOM
Add-Type -Path "C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.SharePoint.Client\v4.0_16.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.SharePoint.Client.Runtime\v4.0_16.0.0.0__71e9bce111e9429c\Microsoft.SharePoint.Client.Runtime.dll"

#Bind to site collection
$ObjContext = New-Object Microsoft.SharePoint.Client.ClientContext($strSiteCollURL)
$ObjCreds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($strUserId,$strPassword)
$ObjContext.Credentials = $ObjCreds
#Iterating through the Site Collections
Get-SPOWebs($strSiteCollURL)

$completedTime = Get-Date
Write-Host "`nTime Completed = " $completedTime
Write-Host "Script Excecuted Successfully !!!"
}
catch {
write-host "Error: $($_.Exception.Message)" -foregroundcolor red
}
}
function Get-SPOWebs($url) {
#Creating object to Site Collection
$objClientCntx = New-Object Microsoft.SharePoint.Client.ClientContext($url)
$objClientCntx.Credentials = $ObjCreds
$objWeb = $objClientCntx.Web
$objClientCntx.Load($objWeb)
$objClientCntx.Load($objWeb.Webs)
try {
$objClientCntx.ExecuteQuery()
#Iterate through all the subsites in a site collection
foreach ($objWeb in $objWeb.Webs) {
write-host "Site Name::$($objWeb.Title)`t`t Site URL :: $($objWeb.url)" -foregroundcolor green
Get-SPOWebs($objWeb.url)
}
}
catch {
write-host "Could not find web" -foregroundcolor red
}
}
GetSubSiteDetails
<# To run this script you need to set the PowerShell Command-let execution policies as follows
Check the execution policies
Get-ExecutionPolicy -List
Step 2 Set the execution policy to "RemoteSigned" with the below command
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
Step 3 Execute the PS1
Step 4 remove the execution policies
Set-ExecutionPolicy Undefined -Scope LocalMachine
#>

The above script has made my life simply and smooth. The output will be as follows:

Get Subsites of a SharePoint Online Site Collection using PowerShell

This PowerShell SharePoint Online tutorial explains how to retrieve all subsites under a site collection using PowerShell in SharePoint Online Office 365.

You may like following SharePoint CSOM tutorials:

This SharePoint tutorial, we discussed how to retrieve all the subsites from a site collection using .Net client object model (csom) code. It will display all the subsites other than the SharePoint hosted add-in subsites.

free sharepoint training

SharePoint Online FREE Training

JOIN a FREE SharePoint Video Course (3 Part Video Series)

envelope
envelope

Bijay Kumar

I am Bijay from Odisha, India. Currently working in my own venture TSInfo Technologies in Bangalore, India. I am Microsoft Office Servers and Services (SharePoint) MVP (5 times). I works in SharePoint 2016/2013/2010, SharePoint Online Office 365 etc. Check out My MVP Profile.. I also run popular SharePoint web site SharePointSky.com

>