Question

I am looking for a c# snippet for getting all OneDrive's. There is a lot of sample for PowerShell, but I am looking for c# snippet that can provide all OneDrives in a tenant.

Was it helpful?

Solution

OneDrive's are simply specialized/personalized site collections in SharePoint that were created from the SPSPERS template. To find all OneDrives you can use Brian Jackett's technique for enumerating site collections with CSOM, just add an additional filter to only get sites based on the SPSPERS template using the SPOSitePropertiesEnumerableFilter.Template property.

Here is a sample (this is nearly identical to Mr. Jackett's, with the addition of the line sspFilter.Template = "SPSPERS") :

List <SiteProperties> list = new List <SiteProperties>();

SPOSitePropertiesEnumerable ssp = null;
SPOSitePropertiesEnumerableFilter sspFilter = new SPOSitePropertiesEnumerableFilter();
SharePointOnlineCredentials creds = new SharePointOnlineCredentials("myUsernameGoesHere", securePassword);

using (ClientContext cc = new ClientContext("myURLGoesHere"))
{
    cc.Credentials = creds;

    String nextIndex = null;
    Tenant tenant = new Tenant(cc);

    //loop through all site collections including personal sites 
    //borrowed this code from after decompiling SPO Management Shell assemblies
    sspFilter.IncludePersonalSite = PersonalSiteFilter.Include;
    sspFilter.IncludeDetail = true;
    sspFilter.Template = "SPSPERS";

    do
    {
        sspFilter.StartIndex = nextIndex;
        ssp = tenant.GetSitePropertiesFromSharePointByFilters(sspFilter);

        cc.Load(ssp);
        cc.ExecuteQuery();

        list.AddRange(ssp);
        nextIndex = ssp.NextStartIndexFromSharePoint;
    }while(nextIndex != null);

    foreach (SiteProperties sp in list)
    {
        //DO YOUR WORK HERE FOR EACH SITE COLLECTION, such as looping through subwebs
        // OR Logging to a file, or determining user ownership, etc.
        cc.Load(cc.Web, w => w.NoCrawl,
                                    w => w.Webs,
                                    w => w.Url);
        cc.ExecuteQuery();

        //check subweb(s)
        foreach (var subweb in cc.Web.Webs)
        {
            cc.Load(subweb, sw => sw.NoCrawl,
                                        sw => sw.Url);
            cc.ExecuteQuery();
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top