So you want to programmatically provision Personal Sites (One Drive for Business) in Office 365?


As part of the new Client Side Object Model (CSOM) assemblies released in the SharePoint Online Client Components SDK, we now have many new capabilities and improvements. One specifically is the capability to programmatically provision One Drive for Business sites in Office 365

There is basically two ways to provision a users One Drive for Business site, the first way is user initiated that is when the user navigates to their newsfeed, site or One Drive links that are within the suite bar, the other is by pre-provisioning leveraging CSOM. In some cases it might not be feasible to have the user initiate the provision process. Say for example, you are migrating from an on-premises SharePoint farm or other repositories, and you don’t want to wait for the user to click a link before you start your migration. The AMS team is in the process of publishing this sample at, but if you need it now and don’t want to wait here is a sample to get you going.

Use Cases

  • You have an custom on-boarding process and you want to create One Drive Sites when you on-board new employees
  • You are performing an on-premises migration to Office 365
  • You are migrating from the G word or other repositories

Dependencies Components 

SharePoint Online Client Redistributable













  • You must be a tenant administrator to provision One Drive for Business sites programmatically
  • Your code must have a context to your tenant admin URL. For example

Code Samples

Rest API Implementation

public void CreatePersonalSiteUsingRest(string tenantAdminUrl , string userName, string password , string emailIDs)
//Validate Arguments
Uri _uri = new Uri(tenantAdminUrl);
string _emailData = emailIDs;
if (_creds == null)
_creds = new SharePointOnlineCredentials(userName, Utilities.StringToSecure(password));
string authCookie = _creds.GetAuthenticationCookie(_uri);
_cookies = new CookieContainer();
_cookies.Add(new Cookie("FedAuth", authCookie.TrimStart("SPOIDCRL=".ToCharArray()), "", _uri.Authority));

Uri _apiContextInfo = new Uri(_uri, API_CONTEXTINFO);

HttpWebRequest _endpointRequest = (HttpWebRequest)HttpWebRequest.Create(_apiContextInfo.OriginalString);
_endpointRequest.Method = "POST";
_endpointRequest.Accept = "text/xml;charset=utf-8";
_endpointRequest.CookieContainer = _cookies;
_endpointRequest.ContentLength = 0;
_endpointRequest.Credentials = _creds;

//We need to get the form digest since we are submitting or writing data via rest.
//We need to make a call to _api/contextinnfo to retreive the digestvalue and attach the form digest value to all

HttpWebResponse _endpointResponse = (HttpWebResponse)_endpointRequest.GetResponse();
XmlNamespaceManager _xmlnspm = new XmlNamespaceManager(new NameTable());
_xmlnspm.AddNamespace("d", "");
StreamReader _contextinfoReader = new StreamReader(_endpointResponse.GetResponseStream(), System.Text.Encoding.UTF8);
var _formDigestXML = new XmlDocument();
var _formDigestNode = _formDigestXML.SelectSingleNode("//d:FormDigestValue", _xmlnspm);
_formDigest = _formDigestNode.InnerXml;

Byte[] _payLoad = System.Text.Encoding.ASCII.GetBytes(_emailData);
HttpWebRequest _spoMySiteRequest = (HttpWebRequest)HttpWebRequest.Create(new Uri(_uri, API_CREATEPERSONALSITE));
_spoMySiteRequest.Method = "POST";
_spoMySiteRequest.ContentType = "application/json;odata=verbose";
_spoMySiteRequest.Accept = "application/json;odata=verbose";
_spoMySiteRequest.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
_spoMySiteRequest.Headers.Add("X-RequestDigest", _formDigest);
_spoMySiteRequest.CookieContainer = _cookies;
_spoMySiteRequest.ContentLength = _emailData.Length;
_spoMySiteRequest.Credentials = _creds;

Stream _itemRequestStream = _spoMySiteRequest.GetRequestStream();
_itemRequestStream.Write(_payLoad, 0, _payLoad.Length);

HttpWebResponse _mysiteCreateResponse = (HttpWebResponse)_spoMySiteRequest.GetResponse();




PersonalSiteCreator _spoPersonalSiteCreator = new PersonalSiteCreator();
String _adminTenantUrl = "";
String _userName = "";
String _passWord = "myAdminPassword";

//You dont want to provision more than 200 users personal sites during a single request. If you have a large amount of users consider
//waiting for the last users site to be provisioned. The reason behind this is not to bombard the service with requests.

// One Users
string _restPayload = "{'emailIDs':['']}";

// Multiple Users
string _restPayload = "{'emailIDs':['', '']}";
_spoPersonalSiteCreator.CreatePersonalSiteUsingRest(_adminTenantUrl, _userName, _passWord, _restPayload);


CSOM Implementation

/// <summary>
/// Sample Member that provisions personal sites leveraging CSOM
/// </summary>
/// <param name="tenantAdminUrl">The Tenanat Admin URL for your SharePoint Online Subscription</param>
/// <param name="userName">The User name, who has tenant admin permssions</param>
/// <param name="password">The password for the user who has tenant admin permissions</param>
/// <param name="emailIDs">The email ids for users who personal site you want to create</param>
public void CreatePersonalSiteUsingCSOM(string tenantAdminUrl, string userName, string password, string[] emailIDs)
using (ClientContext _context = new ClientContext(tenantAdminUrl))
SharePointOnlineCredentials _creds = new SharePointOnlineCredentials(userName, Utilities.StringToSecure(password));
_context.Credentials = _creds;

ProfileLoader _profileLoader = ProfileLoader.GetProfileLoader(_context);
catch(Exception _ex)


PersonalSiteCreator _spoPersonalSiteCreator = new PersonalSiteCreator();
String _adminTenantUrl = "";
String _userName = "";
String _passWord = "myAdminPassword";

//You dont want to provision more than 200 users personal sites during a single request. If you have a large amount of users consider
//waiting for the last users site to be provisioned. The reason behind this is not to bombard the service with requests.

//Create Personal Sites using CSOM
string[] _usersToCreate = { "" , ""};
_spoPersonalSiteCreator.CreatePersonalSiteUsingCSOM(_adminTenantUrl, _userName, _passWord, _usersToCreate);


During execution of the above code you might notice in the User Profiles a similar view, that the users personal site is displaying a SPSSITEERROR. This is expected during provisioning and will later be updated once the back-end processes have completed.


After this service has provisioned the site you will see a similar screen below which displays the users personal site.




Q: Do we have an API to provision on-premises One Drive Sites?

I’m sorry at this time no.

Q: Should I use the Rest API or CSOM?

That depends, use what you are comfortable with however, our opinion is that CSOM is more intuitive in this scenario. 

Q: Can I batch more than 200 users at a time?

No, there is limit of 200 users per request.

Q: I have more than 200 users and I will need to submit multiple requests can I do that?

Sure you can, but you must batch the requests. Before you submit the next batch of users you should validate that the last user in your batch has had their One Drive site created. In the background all requests are queued up to the maximum 200.

Q: What happens, if we don’t listen to the above guidance?

You will receive an exception. We told you so.

Q: How long can does it take to provision a One Drive Site?

That depends we have seen it take up to 5 minutes per site during the day. During testing we provisioned 4,000 site collections and it took sometime to provision all the users. We are always improving the service.

Q - Can I use this code and material within any project I'm involved?

Feel free to use this on your engagements or solutions, but remember we told you no more than 200 users per requests

Q – Where can we provide feedback or we have other comments? or

Q – These code snippets are nice, but can you point me to the Visual Studio Solution?

EDITED: The solution has been released and is available at

Q – Do you have a PowerShell example?

Glad you asked. Here you go.

Open up SharePoint PowerShell console and run the following commands:

$webUrl = ""
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($webUrl)

$web = $ctx.Web
$username = ""
$password = read-host -AsSecureString

$ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username,$password )



$loader =[Microsoft.SharePoint.Client.UserProfiles.ProfileLoader]::GetProfileLoader($ctx)

#To Get Profile
$profile = $loader.GetUserProfile()

#To enqueue Profile

Q – What if I submit a user who already has a One Drive Site?

We will process the request within the service and we will handle gracefully, however you should validate the user doesn’t have a site already to reduce the burden. See the AMS samples on how to determine if a user has One Drive site.

Q –   I want to add additional users or apply custom branding to the One Drive site how can I do that using this API?

The CreatePersonalSiteEnqueueBulk method only provisions the Site Collection, you can use the AMS sample Deploy branding to personal SkyDrive Pro sites automatically for possible options.

Special Thanks to

Kimmo Forss, Bob Fox, Vesa Juvonen, Rob Howard, Kirk Daues, Steve Walker, Ali Mazaheri, Bert Jansen, Jeremy Mazner, Phil Newman, Luca Bandinelli, Neil Hodgkinson, Bill Baer, Microsoft America Cloud Services & Office 365 CoE 


Comments (9)
  1. Joe Gasper says:

    Can you please provide the opposite, deprovision a batch of OneDrive sites.

    There are 3 ways to remove a OneDrive site:

    1) If you remove the user profiles associated to the site, the personal site should be removed automatically after some time.

    2) You can also append /_layouts/15/deleteweb.aspx and delete them one by one after clicking through confirmations

    3) Remove the SPO license – and wait 14 days for the OneDrive site to be fully deleted.

    Manipulating sites below the root level is not supported with the cmdlets available currently.

    There is no way to programmatically delete a OneDrive. We need to deprovision 3000 per year, while maintaining the SPO license.

    It used to be possible back through late 2013 to use User Profile permissions with a security group for creation of personal sites where removing the user from the security would deprovision their OneDrive. This functionality was removed I understand because too many people were accidentally delete OneDrive sites.  

    We need to have another method to deprovision.

    Also, we need a method to disable offline sync for OneDrive libraries. Can you please put ExcludeFromOfflineClient in CSOM.

    Thank you.

  2. PowerShell issue says:

    I attempted your powershell command to create the sites, but the loader variable keeps failing with the error:

    PS C:> $loader = [Microsoft.SharePoint.Client.UserProfiles.ProfileLoader]::GetP


    Cannot convert argument "context", with value:

    "Microsoft.SharePoint.Client.ClientContext", for "GetProfileLoader" to type

    "Microsoft.SharePoint.Client.ClientRuntimeContext": "Cannot convert the

    "Microsoft.SharePoint.Client.ClientContext" value of type

    "Microsoft.SharePoint.Client.ClientContext" to type


    At line:1 char:1

    + $loader =

    [Microsoft.SharePoint.Client.UserProfiles.ProfileLoader]::GetProfileLo …

    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


       + CategoryInfo          : NotSpecified: (:) [], MethodException

       + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument

  3. Luqman Hussain says:

    Thanks for this great post.

    To make it a little easier for everyone ive created a WinForms app for this purpose. Available free to download from:…/Auto-provision-OneDrive-for-users—programmatically

  4. FeliceG says:


    thank you for a great post. I am using the AMS samples but using visual studio I keep getting this error when executing: "For security reasons DTD is prohibited in this XML document. To enable DTD processing set the DtdProcessing property on XmlReaderSettings to Parse and pass the settings into XmlReader.Create method.


    any idea why?


  5. smartdat says:


    Thanks for nice article.

    is there any was to programmatically update OneDrive site ?  we wanted to write script to bulk update them.  We want to setup site properties and some branding.

  6. jj_the_Skeptic says:

    When I try to provision a user for OneDrive for Business using PowerShell, I keep getting error below when executing the line



    Method invocation failed because [Microsoft.SharePoint.Client.UserProfiles.ProfileLoader] doesn't contain a

    method named 'CreatePersonalSiteEnqueueBulk'.

    I can't find any explanation of this – am I missing something?

  7. @smartdat you can look at the AMS Samples Provisioning.OneDrive. It shows a pattern of updating OneDrive site collections

  8. @FeliceG, which sample are you referring too?

  9. @JJ. You have the write client sdk version? You can get it at…/details.aspx

Comments are closed.

Skip to main content