Skip to content

Instantly share code, notes, and snippets.

@jamiechalmerzlp
Created March 14, 2025 20:00
Show Gist options
  • Select an option

  • Save jamiechalmerzlp/41804153f47405ec5c2292715a34cc83 to your computer and use it in GitHub Desktop.

Select an option

Save jamiechalmerzlp/41804153f47405ec5c2292715a34cc83 to your computer and use it in GitHub Desktop.
This script automates the provisioning of OneDrive for licensed users in a SharePoint Online environment. It connects to Microsoft Graph and SharePoint Online, retrieves licensed users, and provisions their OneDrive accounts in batches.
<#
Author: Jamie Chalmers of Agilico - 3rd Line Tech & Telco Engineer
Description: This script automates the provisioning of OneDrive for licensed users in a SharePoint Online environment.
It connects to Microsoft Graph and SharePoint Online, retrieves licensed users, and provisions their OneDrive accounts in batches.
#>
Param(
[Parameter(Mandatory = $True)]
[String]
$SharepointURL,
[Parameter(Mandatory = $True)]
[String]
$tenantID
)
# Check if the Microsoft.Graph module is installed, and install it if necessary
Write-Host "Checking if the Microsoft.Graph module is installed..."
if (-not (Get-Module -ListAvailable -Name Microsoft.Graph)) {
Write-Host "Microsoft.Graph module is not installed. Installing now..."
try {
Install-Module -Name Microsoft.Graph -Scope CurrentUser -Force -ErrorAction Stop
Import-Module Microsoft.Graph -ErrorAction Stop
Write-Host "Microsoft.Graph module installed and imported successfully."
} catch {
Write-Host "Failed to install or import the Microsoft.Graph module. Error: $_" -ForegroundColor Red
exit 1
}
} else {
Write-Host "Microsoft.Graph module is already installed."
Import-Module Microsoft.Graph -ErrorAction Stop
}
# Define the required scope for Microsoft Graph API
$scope = 'User.Read.All'
# Connect to Microsoft Graph and SharePoint Online
Connect-MgGraph -TenantId $tenantID -Scopes $scope
Connect-SPOService -Url $SharepointURL
# Initialize variables
$userBatchList = @() # List to hold UPNs for batch processing
$totalUsersProvisioned = 0 # Counter for total users processed
# Retrieve all licensed users from Microsoft Graph
Write-Host "Fetching licensed users..."
$licensedUsers = Get-MgUser -Filter 'assignedLicenses/$count ne 0' -ConsistencyLevel eventual -CountVariable licensedUserCount -All -Select UserPrincipalName
# Process each user and provision OneDrive in batches
foreach ($user in $licensedUsers) {
$totalUsersProvisioned++
Write-Host "Processing user $totalUsersProvisioned of $($licensedUsers.Count): $($user.UserPrincipalName)"
$userBatchList += $user.UserPrincipalName
# Check if the batch limit is reached (199 users per batch)
if ($userBatchList.Count -eq 199) {
Write-Host "Batch limit reached. Requesting OneDrive provisioning for the current batch."
Request-SPOPersonalSite -UserEmails $userBatchList -NoWait
Start-Sleep -Milliseconds 655 # Add a short delay to avoid throttling
$userBatchList = @() # Clear the batch list for the next set of users
}
}
# Handle any remaining users in the final batch
if ($userBatchList.Count -gt 0) {
Write-Host "Requesting OneDrive provisioning for the remaining $($userBatchList.Count) users."
Request-SPOPersonalSite -UserEmails $userBatchList -NoWait
}
# Disconnect from services
Disconnect-SPOService
Disconnect-MgGraph
# Final output
Write-Host "OneDrive provisioning completed successfully for $totalUsersProvisioned users." -Foreground Green
@changchichung
Copy link

changchichung commented Jan 29, 2026

the problem is that I can not pass the SPOSerevice , always return 400 bad Request

PS C:\m365-cli> Connect-SPOService -Url https://abc-admin.sharepoint.com -UseSystemBrowser $true
Connect-SPOService: The remote server returned an error: (400) Bad Request.
PS C:\m365-cli>
m365-cli> Connect-SPOService -Url https://abc-admin.sharepoint.com -ClientId "3ab86d546b63" -Tenant "cbbabb6d795f" -CertificatePath "certs\M365Automation.pfx" -CertificatePassword $password
Connect-SPOService: The remote server returned an error: (400) Bad Request.
m365-cli> Connect-SPOService -Url https://abc-admin.sharepoint.com -UseSystemBrowser $true -ModernAuth $true -AuthenticationUrl https://login.microsoftonline.com/organizations
Connect-SPOService: The remote server returned an error: (400) Bad Request.
PS C:\Users\eric.chang\Documents\AntiGravity\m365-cli>
m365-cli> Connect-MgGraph -TenantId "cbbabb6d795f" -Scopes 'User.Read.All'
WARNING: Note: Sign in by Web Account Manager (WAM) is enabled by default on Windows. If using an embedded terminal, the interactive browser window may be hidden behind other windows.
Welcome to Microsoft Graph!

Connected via delegated access using 296a70dab67e
Readme: https://aka.ms/graph/sdk/powershell
SDK Docs: https://aka.ms/graph/sdk/powershell/docs
API Docs: https://aka.ms/graph/docs

NOTE: You can use the -NoWelcome parameter to suppress this message.
NOTE: Sign in by Web Account Manager (WAM) is enabled by default on Windows systems and cannot be disabled. Any setting stating otherwise will be ignored.

m365-cli> Connect-SPOService -Url https://abc-admin.sharepoint.com
Connect-SPOService: No valid OAuth 2.0 authentication session exists

this one will open sytembrowser and I could pass the authentication , but it still return 400 error

m365-cli> Connect-SPOService -Url https://abc-admin.sharepoint.com -UseSystemBrowser $true
Connect-SPOService: The remote server returned an error: (400) Bad Request.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment