← script library
Automating User Onboarding in Microsoft 365 with PowerShell
Microsoft 365 & Entra IDJanuary 4, 2025
In this post, we will explore a PowerShell script for automating user onboarding in Microsoft 365. This script simplifies the process of adding new users, assigning licenses, and configuring their roles within Microsoft 365, ensuring they have immediate access to necessary resources. By automating user onboarding, you can save valuable time and minimize the potential for errors.
powershell
# Define parameters for the new user
$firstName = "Alice"
$lastName = "Johnson"
$userPrincipalName = "$($firstName.ToLower()).$($lastName.ToLower())@yourdomain.com"
$password = "SecureP@ssw0rd!" # Ensure this meets your organizations password policy
$license = "yourdomain:ENTERPRISEPACK" # Replace with the appropriate license
# Import the required module (if not already imported)
Import-Module Microsoft.Graph
# Create the new user
New-MgUser -DisplayName "$firstName $lastName" `
-UserPrincipalName $userPrincipalName `
-AccountEnabled $true `
-MailNickname "$($firstName.ToLower())$($lastName.ToLower())" `
-PasswordProfile @{ ForceChangePasswordNextSignIn = $true; Password = $password }
Write-Host "User $firstName $lastName created successfully."
# Assign a license to the new user
Set-MgUserLicense -UserId $userPrincipalName -AddLicenses $license
Write-Host "License $license assigned to user $firstName $lastName."
# Add user to specified groups
$groups = @("group-id-1", "group-id-2") # Replace with your actual group Object IDs
foreach ($group in $groups) {
Add-MgGroupMember -GroupId $group -DirectoryObjectId $userPrincipalName
Write-Host "User $firstName $lastName added to group with ID: $group."
}
# Verify the new user
$user = Get-MgUser -UserId $userPrincipalName
if ($user) {
Write-Host "User $($user.DisplayName) successfully created with UPN: $($user.UserPrincipalName)."
} else {
Write-Host "ERROR: User creation failed."
}Run it across your fleet
This script runs as-is on a single host. Paste it into ServerEngine to schedule it, run it on a whole server group in parallel, and keep the credentials out of the file — see the scripts documentation and the credential store.
More in Microsoft 365 & Entra ID
Automate M365 User License Assignment with PowerShell
2025-01-09Manage M365 Users with PowerShell
2025-01-09Automate Microsoft 365 User License Management with PowerShell
2025-01-09Streamlining M365 User Management with PowerShell
2025-01-09PowerShell Script to Retrieve M365 User License Info
2025-01-09Automate Microsoft 365 User Report Generation with PowerShell
2025-01-09Ready when you are.
Try ServerEngine free for 7 days.