Get All Site Collections from SharePoint Online Tenant

After the arrival of modern experience, SharePoint Online drastically change in the functionalities, look and feel etc.. Among them, modern Communication and Team site templates are one of the major revamp in SharePoint Online User Interface.

SharePoint Online CSOM from PnP also grows with lot of new properties and methods to access against SharePoint new functionalities.

To retrieve the site collections from SharePoint Online Tenant, so far we have used the Tenant.GetSiteProperties method from CSOM.
And the snippet using this method is as follows,

[code lang=”js”]
Tenant tenant = new Tenant(context);
SPOSitePropertiesEnumerable siteProps = tenant.GetSiteProperties("0", true);
context.Load(siteProps);
context.ExecuteQuery();
Console.WriteLine("Total Site Collections: " + siteProps.Count.ToString());
foreach (var site in siteProps)
{
Console.WriteLine(site.Title + "\t" + site.Template.ToString());
}
[/code]

Disadvantage to this method is, it won’t return the Site Collections created on new modern site templates.

We have another method under Microsoft.Online.SharePoint.TenantAdministration namespace for retrieving all site collections created under SharePoint online Tenant is Tenant.GetSitePropertiesFromSharePoint. The snippet given below uses this method and retrieve the all Site Collections irrespective of any webtemplates.

[code lang=”js”]

var credentials = new SharePointOnlineCredentials(userName, password);
ClientContext context = new ClientContext(siteUrl);
context.Credentials = credentials;

Tenant tenant = new Tenant(context);
SPOSitePropertiesEnumerable siteProps = tenant.GetSitePropertiesFromSharePoint("0", true);
context.Load(siteProps);
context.ExecuteQuery();
Console.WriteLine("Total Site Collections: " + siteProps.Count.ToString());
foreach (var site in siteProps)
{
Console.WriteLine(site.Title +"\t"+ site.Template.ToString());
}

[/code]

For the sample, I have created a windows console application and imported the Microsoft.SharePointOnline.CSOM Nuget Package and added the above code to retrieve the enitre site collections from the SharePoint online  tenant.

The full code of above snippets is available in Github, https://github.com/ktskumar/PnPCSOM/tree/master/Samples/GetTenantSiteCollections

 

Shantha Kumar
Shantha Kumar
Articles: 280

24,849 Comments

  1. Hello Shanta Kumar, how to get all site collections with a particular template and then apply retention policies to it.

Comments are closed.