Office 365 License User and Provision OneDrive via Powershell Scheduled Task


Office 365 accounts and Active Directory can be synchronized, but licensing the users and provisioning OneDrive takes some extra steps.  If a user does not have licensing specified they cannot use Office 365 applications.  Licensing 20 users at a time via the online interface is tedious and doing so long term for new users is even more tedious.

If the user does not have OneDrive provisioned they cannot login to Office 365 via the iPad Office applications (Word, Excel, PowerPoint).  The login fails even if the user has a license and correctly specifies their username and password.  OneDrive is provisioned by going to the OneDrive online application for the first time.  Training new users to take this extra step is difficult and tedious.  New users become frustrated quickly and do not understand why it doesn’t just work as expected.


Automate the Office 365 user licensing and OneDrive provisioning process for new users:

Generate Encrypted Password File for Office 365 global admin user.  The password is stored and later used.  This is a security risk, but is necessary for automation.  If you don’t want the security risk you can run the second script manually and specify the password at run time.

$passwordfile = 'c:\ScheduledTasks\passwordfile.txt'

$secpasswd = ConvertTo-SecureString "GlobalAdminPassword" -AsPlainText -Force
$secpasswd | ConvertFrom-SecureString | Out-File $passwordfile

Once you have the password file you can bring it into the next script and use it to connect to Office 365.  Run the script from your active directory and Office 365 synchronization server.  Make sure your Office 365 global admin user has a license for Onedrive and is provisioned (you just login to the web interface and click on OneDrive).   Make sure to the items below are installed


Reboot the server after any installs.  Make sure that scripting permissions are allowed for the Office 365 global administrator Tile -> Admin -> Admin -> SharePoint -> Settings.  The script below adds the license for any unlicensed users and provisions their OneDrive as well.  After you test and verify that it is working for you, you can make a scheduled task and have it run automatically.

#This script automatically licenses Office 365 unlicensed users and Provisions OneDrive/Personal Site for the new users

#Install-Module -Name AzureAD 
Import-Module AzureAD
Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking

#Fix Powershell ISE and powershell to be able to run .net 2.0 and .net 4.0 code and clr version for powershell     
#    or
#Windows Management Framework 5.0
#Azure AD Module (x64):  or
#.NET 4.6.2 or newer
#SharePoint Online SDK? install
#SharePoint Online Management Shell
#Microsoft Online Services Sign-In Assistant
#Powershell 3.0
#Make sure one drive for admin account already has onedrive provisioned and licensed for onedrive
#Tile -> Admin -> Admin -> SharePoint -> Settings ->
#SharePoint Online Management Shell
#Turn Scripting capabilities on in Office365

#License Information:

#Must be SharePoint Administrator URL
$webUrl = "https://[ORGANIZATION SITE]";

#update and store password as necessary
$logfile = 'c:\ScheduledTasks\StudentLicensesAdded.txt';
$passwordfile = 'c:\ScheduledTasks\passwordfile.txt';

$username = "";

$secpasswd = Get-Content $passwordfile | ConvertTo-SecureString;

$mycreds = New-Object System.Management.Automation.PSCredential($username, $secpasswd);

#Connect to msolservice
Connect-AzureAD -credential $mycreds;

#test get user
#Get-AzureADUser -UserPrincipalName

#Find and get all unlicensed Student Users and filter as desired
$filter = 'accountEnabled eq true';
$unlicenseduserList = Get-AzureADUser -All $True -Filter $filter | Where { ($_.AssignedLicenses -eq $Null -or $_.AssignedLicenses.Count -eq 0) }

#View License Information
#License and Service Plan Options to disable 
$sku = Get-AzureADSubscribedSku | Where { $_.SkuPartNumber -eq "STANDARDWOFFPACK_IW_FACULTY" }
$license1 = New-Object -TypeName Microsoft.Open.AzureAD.Model.AssignedLicense
$license1.SkuId = $($sku.SkuId)
#Disable Service Plans
$license1.DisabledPlans += ($sku.ServicePlans | Where { $_.ServicePlanName -eq "YAMMER_EDU" }).ServicePlanID
$license1.DisabledPlans += ($sku.ServicePlans | Where { $_.ServicePlanName -eq "FLOW_O365_P2" }).ServicePlanID
#$license1.DisabledPlans += ($sku.ServicePlans | Where { $_.ServicePlanName -eq "POWERAPPS_O365_P2" }).ServicePlanID
#$license1.DisabledPlans += ($sku.ServicePlans | Where { $_.ServicePlanName -eq "MCOSTANDARD" }).ServicePlanID

$sku2 = Get-AzureADSubscribedSku | Where { $_.SkuPartNumber -eq "CLASSDASH_PREVIEW" }
$license2 = New-Object -TypeName Microsoft.Open.AzureAD.Model.AssignedLicense
$license2.SkuId = $($sku2.SkuId)

#Assign both licenses
$newLicenses = New-Object -TypeName Microsoft.Open.AzureAD.Model.AssignedLicenses
$newLicenses.RemoveLicenses = $null;
$newLicenses.AddLicenses += $license1;
$newLicenses.AddLicenses += $license2;

#Setup new students in Office 365
if ($unlicenseduserList)
 foreach ($eachuser in $unlicenseduserList)
 Write-Host "Assigning License to user:";
 $upnstaff = [string]$($eachuser.UserPrincipalName);
 Write-Host $upnstaff
 Set-AzureADUser -ObjectId $upnstaff -UsageLocation "US";
 #This activates the licenses and all plans are active
 Set-AzureADUserLicense -ObjectId $upnstaff -AssignedLicenses $newLicenses
 Start-Sleep -Seconds 15
 Add-Content $logfile $upnstaff;
 Write-Host "No Users to License";
Write-Host "Licensing Finished" -ForegroundColor Green;

Write-Host "OneDrive Provisioning";

$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $username, $secpasswd

Connect-SPOService -Url $webUrl -Credential $cred

Write-Host "Connected to site: $webUrl" -ForegroundColor Green;

#Test view all sites, connection working?

if ($unlicenseduserList)
	$usercount = 1;
	$usersToProvision = @();
	foreach ($eachuser in $unlicenseduserList)
		#Break up the work into batches of 10 you can try up to 200
		if ($usercount -gt 10)
			Write-Host "Provisioning OneDrive for users:";
			#CreatePersonalSiteEnqueueBulk does not work! use the code below instead
			Request-SPOPersonalSite -UserEmails $usersToProvision;
			$usersToProvision = @();
			$usercount = 1;
		#Add to queue 
		$onedriveuser = [string]$($eachuser.UserPrincipalName);
		$usersToProvision += $onedriveuser;
		#Write-Host $onedriveuser;
	#Run the last batch 
	if ($usercount -gt 1)
		Write-Host "Provisioning OneDrive for users:";
		#CreatePersonalSiteEnqueueBulk does not work! use the code below instead
		Request-SPOPersonalSite -UserEmails $usersToProvision;
		$usersToProvision = @();
		$usercount = 1;
	Write-Host "No Users to Provision";

Write-Host "One Drive Provisioning Completed" ;

#to Test Provisioning succeeded
#Wait a few hours before testing
#Login to Office 365 using an account then hit the url below replacing username as desired
#https://[ORGANIZATION SITE][UserPrincipalName replace "@" with "_"    and "." with "_"]




2 thoughts on “Office 365 License User and Provision OneDrive via Powershell Scheduled Task

  1. Pingback: Office 365 Mass Provision PersonalSite/OneDrive | Question Driven

  2. Pingback: Move Multiple Mailboxes to Exchange Online via Powershell | Question Driven

Leave a Reply

%d bloggers like this: