Office 365 guide series – Function to resolve a users OneDrive for Business URL

 Office365logo       SP2013logo

Hi SharePoint Online PowerShellers!

This time I will give you a Quick but great function to use if you are working with OneDrive for Business:

Function to resolve a users OneDrive for Business URL


Simple solution, great to have, unbelievably efficient…

Ok, this is perhaps my shortest post ever…I’ll just explain real Quick.
OneDrive for Business gets it URL from the tenantname and the users UserPrincipalName. Creating this every time can be troublesome…
This is what I use, a function I created last summer when I was tired of doing them one at the time…

It works even with users that have a different domain in the UPN than what is the tenant name.
This is it:

Function GetODfBURL($UserPrincipalName, $TenantName)
# Creates a correct ODfB URL from email and TenantName/OrgName, returns URL as a String
    # ConStructing OneDrive personal URL from the UPN/Email address
    $StrUser = $UserPrincipalName
    $pos= $StrUser.IndexOf("@")
    $len = $StrUser.Length -1
    $StrUser = $StrUser.SubString(0, $pos)
    $StrUser = $StrUser -replace "\.", "_"
    $Orgpos = $pos + 1
    $Orglen = $len - $pos
    $StrOrg = $UserPrincipalName.SubString($Orgpos, $Orglen)
    $StrOrgNamePos = $StrOrg.IndexOf(".")
    $StrOrgName = $StrOrg.SubString(0, $StrOrgNamePos)
    $StrOrgSuffixPos = $StrOrgNamePos +1
    $StrOrgNameLen = $StrOrg.Length - $StrOrgSuffixPos
    $StrOrgSuffix = $StrOrg.SubString($StrOrgSuffixPos, $StrOrgNameLen)
    $StrOrg = $StrOrg -replace "\.", "_"
    $PersonalOrgURL = "https://" + $TenantName + ""
    $SiteUrl= $PersonalOrgURL + $StrUser
    $SiteUrl= $SiteUrl+ "_" + $StrOrg
    return $SiteUrl
$ODfBURL = GetODfBURL "" "blksthl"

This will give the URL:

Thats it. Use it or not 🙂



References and Credits

Nope, not this time…

Credits & many thanks to

To all of you.




Twitter | Technet Profile | LinkedIn


Office 365 guide series – Provision OneDrive for Business using PowerShell

 Office365logo       SP2013logo

Hi SharePoint Online administrators!

This time I will show you how to:

Provision OneDrive for Business using only PowerShell.


Get the people up there…into the Clouds…(Liseberg, Gothenburg, Sweden)

Time to roll out OneDrive for Business in the Enterprise? Or maybe you just want to implement OneDrive for Business in a controlled way, and you may not be a hardcore developer either.

If you want to do any kind of preparation before letting the users into their OneDrives, then you will need to have them created/provisioned first, after that you can go ahead and give yourself permission (separate blogpost) and migrate a users files (separate blogpost), preconfigure, brand, and so on.
I have in this guide tried to offer a way to provision the OneDrive for Business to your users in a way that do not require you to know C#, Visual Studio or any development at all, how does that sound? All you need to do is follow this guide to the letter, and you will be sucessfull.

The only way I have found so far to provision a users OneDrive for Business as a administrator is to use code developed by the Office AMS Community Project. This includes among other things, a great Visual Studio sample Project for provisioning users OneDrive for business, and this is really spot on. But…it is not that easy to get going, for a non-developer it may prove to be impossible.

I have used code developed in the samples but I will only use PowerShell to execute it. This is what will make it easy for others (such as you?) to use.
The Office AMS Project also includes the SharePoint client assemblies needed to do anything with SPO using CSOM, Client Side Object Model(Code executed on the client).

In order to get started provisioning your users OneDrive for Business sites(or we can just as well call them MySites, since this is wat they really are…), you just follow these steps:


1. Download Download and unpack the Office App Model Samples from Codeplex, last tested version is currently 2.0 found here: DOWNLOAD Office AMS.
2. Get assemblies Locate the Microsoft.sharepoint.client assembles in the unpacked Office App Model Samples folders, located in <unpack location>\Office App Model Samples v2.0\Assemblies\16\ Copy the files Microsoft.SharePoint.Client.dll, Microsoft.SharePoint.Client.UserProfiles.dll and Microsoft.SharePoint.Client.Runtime.dll and put them in a folder of your choice, I used C:\Temp\ in my sample. (You can also leave the files as is, but then you have to alter the PowerShell code to reference the path in the Office AMS folders)
3. Run the script In a PowerShell prompt/ISE running as admin, run the PowerShell script available below andHERE (Download as Word file), this will load the code needed to access SPO and start provisioning. (Verify and update if needed the $MyAssemblies line at the very bottom)
4. Execute Execute the code in your PowerShell prompt/ISE running as admin (It has to be the same prompt/ISE used to execute the script), use this syntax: Syntax: [OneDriveforBusiness.Provision]::Execute(<SharePointAdminURL>,<GlobalTenantAdminAccount>,<AdminAccountPassword>,<ListofUsersEmailSeparatedbyCommas>)
5. Done – Verify… Done! Verify that the sites have been provisioned by entering the address in your browser of choice.
References/Credits Reference links and credits


The detailed Guide:

1. Download


Download the latest version of SharePoint Server 2013 Client Components SDK x86 or x64. This SDK contains the dll’s needed.
During the install, the dll’s will be added to the following path:
C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\

Download the latest version (Office App Model Samples 2.0 – July 2014 – Update 1) of the Office App Model Samples, the Project has been renamed to the more formal Office365 Developer Patterns & Practices but it is still the same.
The last tested version is currently 2.0 found here: DOWNLOAD Office AMS


Back to Menu

2. Get the assemblies

Unpack the files to a location of choice. (The files will ironically enough not synch very well if stored in a OneDrive for Business synchronized folder – long path among other issues).
Locate the ‘assemblies\16’ folder, in this folder you will find the 3 files we need, Microsoft.SharePoint.Client.dll, Microsoft.SharePoint.Client.UserProfiles.dll and Microsoft.SharePoint.Client.Runtime.dll. Either you put these Three files in a better location, or you make a note of the path to the folder.

Back to Menu

3. Run the script

Start a PowerShell prompt/ISE running as administrator. This is where all the magic will happen. Copy the powershell script below, or download the scriptfile HERE (Word file), then add the script to the Prompt/ISE.
Before executing the script, you will need to alter one thing, the path to the assembly files. Update the line where we give a value to the $MyAssemblies to reflect where you have your SharePoint.client dll files. This is crucial since the code needs to be able to access these asseblies during execution.

$MyAssemblies = (‘C:\Temp\Microsoft.SharePoint.Client.dll’,’C:\Temp\Microsoft.SharePoint.Client.Runtime.dll’,’C:\Temp\Microsoft.SharePoint.Client.UserProfiles.dll’,’System’,’System.Security’)

Unless you have stored your SharePoint.client.dll’s in C:\Temp folder, you will have to update the Three paths to reflect where the files are stored. Example:

$MyAssemblies = (‘C:\Users\Thomas\Documents\Office App Model Samples v2.0\Assemblies\16\Microsoft.SharePoint.Client.dll’,’C:\Users\Thomas\Documents\Office App Model Samples v2.0\Assemblies\16\Microsoft.SharePoint.Client.Runtime.dll’,’C:\Users\Thomas\Documents\Office App Model Samples v2.0\Assemblies\16\Microsoft.SharePoint.Client.UserProfiles.dll’,’System’,’System.Security’)

Once this is done, you can go ahead and execute the script.

HERE (Download as Word file)

# By Thomas Balkeståhl - August 6 2014
# 1. Run script to load the C# code into the Assembly
# 2. Execute using the following syntax:
# Syntax:  [OneDriveforBusiness.Provision]::Execute(<SharePointAdminURL>,<GlobalTenantAdminAccount>,<AdminAccountPassword>,<ListofUsersEmailSeparatedbyCommas>)
# Example: PS C:\> [OneDriveforBusiness.Provision]::Execute("","","MyVerySecretPassWord1!",",,")
# Input:            
# adminurl = The Tenanat Admin URL for your SharePoint Online Subscription, example: "".
# adminuser = The Credentials of the user who has tenant admin permission, example: "".
# password = The password in cleartext to your tenant admin account(I know, not ideal...but it was a quick and dirty to make it work).
# users = The email IDs for users who's personal site you want to create in the form of a comma-separated string, example: ",,". Do not enter more than 200 users at a time.
$MyCSharpSource = @" 
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.UserProfiles;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;
namespace OneDriveforBusiness
    public class ProvisionOneDrive
        public static void Execute(string adminurl, string adminuser, string password, string users)
            string siteUrl = adminurl;
            string userName = adminuser;
            SecureString pwd = GetPassword(password);
            string[] emailIds = GetEmailId(users);
            /* End Program if no Credentials */
            if (string.IsNullOrEmpty(userName) || (pwd == null) || emailIds == null || string.IsNullOrEmpty(siteUrl))
            SharePointOnlineCredentials _creds = new SharePointOnlineCredentials(userName, pwd);
            CreatePersonalSiteUsingCSOM(_creds, siteUrl, emailIds);
        public static SecureString StringToSecure(string nonSecureString)
            SecureString _secureString = new SecureString();
            foreach (char _c in nonSecureString)
            return _secureString;
        // tenantAdminUrl = The Tenanat Admin URL for your SharePoint Online Subscription
        // spoCredentials = The Credentials of the user who has tenant admin permission.
        // emailIDs = The email IDs for users whos personal site you want to create.
        public static void CreatePersonalSiteUsingCSOM(SharePointOnlineCredentials spoCredentials, string tenantAdminUrl, string[] emailIDs)
            using (ClientContext _context = new ClientContext(tenantAdminUrl))
                    _context.AuthenticationMode = ClientAuthenticationMode.Default;
                    _context.Credentials = spoCredentials;
                    ProfileLoader _profileLoader = ProfileLoader.GetProfileLoader(_context);
                    Console.Write("Provisioning of the users supplied has been initiated, please allow for the provisioning to finish, this can take up to 5 minutes.");
                catch (Exception _ex)
                    Console.WriteLine(string.Format("Provisioning failed, find the problem and try again. The error message is {0}", _ex.Message));
        public static SecureString GetPassword(string password)
            SecureString sStrPwd = new SecureString();
            foreach (char ch in password) sStrPwd.AppendChar(ch);
            return sStrPwd;
        public static string[] GetEmailId(string users)
            string[] emailID;
                string Output = "Provisioning the supplied list of users: " + users;
                string emailInput = users;
                if (!string.IsNullOrEmpty(emailInput))
                    emailID = emailInput.Split(new char[] { ',' });
                    return emailID;
                    return null;
            catch (Exception e)
            return null;
$ass1 = [System.Reflection.Assembly]::LoadFile("c:\temp\Microsoft.SharePoint.Client.dll") 
$ass2 = [System.Reflection.Assembly]::LoadFile("c:\temp\Microsoft.SharePoint.Client.Runtime.dll") 
$ass3 = [System.Reflection.Assembly]::LoadFile("C:\temp\Microsoft.SharePoint.Client.UserProfiles.dll")
$MyAssemblies = @( $ass1.FullName, $ass2.FullName,$ass3.Fullname,"System","System.Core","System.Security")
Add-Type -ReferencedAssemblies $MyAssemblies -TypeDefinition $MyCSharpSource -Language CSharp -PassThru

HERE (Download as Word file)

Back to Menu

4 Executing the provisioning code


We have now loaded the code into memory (a .NET Framework class in your Windows PowerShell session), where it will be available just like if we had created a C# DLL and loaded it into the GAC. Remember though, the code is now static and connot be altered. If you need to make any Changes, have a look in the references section where I will show how to be able to alter the code after it has been loaded once.

Now, we have to call on the code laoded into memory, this is done from the same prompt/ISE used to load the code, the code only exists in that prompt session so it will not be available in any other prompt.

Use the following syntax to execute:

Syntax: [OneDriveforBusiness.ProvisionOneDrive]::Execute(<SharePointAdminURL>,<GlobalTenantAdminAccount>,<AdminAccountPassword>,<ListofUsersEmailSeparatedbyCommas>)

Example: PS C:\> [OneDriveforBusiness.ProvisionOneDrive]::Execute(“;,””,”MyVerySecretPassWord1!”,”,,”) 

What you need to supply when running the code, is your SharePoint online admin address, a tenent admin account and password, plus a list of emailadresses to the users that will be provisioned with a OneDrive for Business.

Start by typing in this:



What this does is call the code we just loaded from PowerShell, The Namespace is OneDriveforBusiness, the Class is ProvisionOneDrive and finally, the void or function is Execute.

<SharePointAdminURL>: The Admin address is available if you go the the Admin/SharePoint administration web. This will be visible in the address field of your browser:



Note the address:

<GlobalTenantAdminAccount>: An account that is a global Office 365 Tenant Administrator.
The account must have this setting in Office 365 Admin Center/Users & Groups – User object:


<AdminAccountPassword>: The password of the <GlobalTenantAdminAccount>. This will be entered in cleartext, not the ideal security solution but this is the only way I could solve it.
(Suggestions on how to prompt for the password in a secure way is welcome!)

<ListofUsersEmailSeparatedbyCommas>: This is the users that will have provisioned with OneDrive for Business. A list of UPN’s (User Principal Name) separated by commas. The UPN must be the one registered in Office 365. The UPN is in the form of a emailadress, for example: Enter the string using double quotes on both sides.

This is what the string should look like: “,,,,”

When you have all the values in order, type in the command with your parameters and execute the provisioning:

PS C:\PSScripts> [OneDriveforBusiness.ProvisionOneDrive]::Execute(“;,””,”**********”,””)

When executed ok, you will see this:


The limit for submitting users to be provisioned have been set by Microsoft to 200 at the time. This code do allow more but it will cause issues. Better to do them 200 at the time, wait unitl done and then do 200 more, alternatively, alter the code to include a check so that every user have been provisioned ok Before moving onto the next.

Now, you can execute the commend again and again. You can also use the code obviously for other tenants. Simple provide the commend with a different account, a different admin URL and you are good to go. Good luck!

Back to Menu

5. Done! Verify….

For a tool to verify your list of users directly, check out this guide: Office 365 guide series – Verify Provisioned OneDrives using PowerShell

Verify that the sites have been provisioned by browsing to the direct URL using your admin account. The URL will look like this:



Since you are using your admin account, you have access to the private part of the OneDrive/MySite.

Note: All the steps in this guide have been verified on a Windows 8.1 Update 1 machine, using PowerShell ISE and the Office AMS July 2014 Update 1. All tests have been done during August of 2014, the functionality of Office 365 may change over time and may thus cause this guide to fail. If this happens I will try to be alert and update the guide accordingly. 

Possible errors

1. You need to alter the script, then run the script again?

You have two choices if this happens, you have loaded the code once and you need to edit it and run again. If you do this you may get the error message saying that the ‘Type has already been added’ or similar. If you get this, simply restart your PowerShell prompt/ISE, OR, Change the name of the public class:


Add for example a number after, so that the class is called: ProvisionOneDrive1, then 2 and so on.

2. Nothing happens, no OneDrive shows up?

Verify all your values, then execute the command again. Remember though, that the time it takes for a site to show up may vary and can take up to 5 minuter PER SITE. Wait a moment longer, try it again

If you have the wrong address when verifying, you will see either of these pages depending on the URL used:

A link like:


A link like:


404 could also just mean that the site is in queue and has not been provisioned yet.

References and Credits

Stefan Gossners old post: Using CSharp (C#) code in Powershell scripts

Office365 Developer Patterns & Practices/Office App Model Samples

TechNet Add-Type

Credits & many thanks to

Kimmo Forss, Microsoft

Jörgen Andersson, Xperta

All the contributors of Office AMS

Always, Mattias Gutke at CAG

Stefan Gossner, Microsoft (Blog) for that short and concise post written a few years back.

My love for putting up with me while solving this problem and writing this post!





Twitter | Technet Profile | LinkedIn

Update the UI quick on ALL subwebs with SPWeb.UIVersion

When you migrate SharePoint 2007 to 2010, it sometimes happens that the UI gets ‘stuck’ in v.3.0 mode. When you move a database from 2007 and do an attach upgrade, you have a choice to use the -UpdateUserExperience flag when you run the Mount-SPContentDatabase command. This is usefull so that you don’t have to manually update the Visual UI, but this flag can be dangerous as well.

I have used it and sometimes, it causes most sites UI to be upgraded to v.4, but not all. On the not upgraded, the option to upgrade the visual UI is gone which puts you in the spot a bit.

For this occasion, I created this short but effective snippet:

$SPSite = Get-SPSite http://MySiteCollection
foreach ($SPWeb in $SPSite.AllWebs)
    $SPWeb.UIVersion = 4;


Stay tuned!



More on SharePoint 15 – SDK preview

If you missed that MS released a Tech Preview on SP15 Managed OM SDK…

SharePoint 15 Technical Preview Interoperability API Documentation

‘SharePoint 15 Technical Preview Managed Object Model SDK: This compiled help (.chm) file contains reference topics focusing only on types and members that are called by other Microsoft applications. This reference does not document the full SharePoint 15 managed object model. That documentation will accompany a later release of SharePoint 15.’

Early release as it is, its still interesting…

Others on SP15:

SharePoint Joel:
So it begins… SharePoint 15 & Office 15 Wave of Products – Happy Days

Rincón de Héctor Calvarro
SharePoint 15 SDK CTP has been released (Only documentation)

The 2012 Scripting Games!

Don’t miss the Hey, Scripting Guy’s 2012 Scripting Games.

“…The 2012 Windows PowerShell Scripting Games begin on April 2, 2012, and they run through April 13, 2012. The Scripting Games are the premier learning event of the year for IT pros, devs, and others who want to learn Windows PowerShell…”

Everyhting is told here at the ‘all links on one page
More info on related topics, PowerSHell for the mostpart, can be found on the Hey, Scripting Guy‘s blog.

2012 Scripting Games

Grab this badge here!