← script library

Streamlining Microsoft Entra ID User Management with PowerShell

Microsoft 365 & Entra IDDecember 23, 2024

Managing user accounts effectively in Microsoft Entra ID is critical for maintaining security and operational efficiency within an organization. This PowerShell script automates the process of creating new user accounts, assigning roles, and sending a welcome email. By leveraging this automation, administrators can streamline user onboarding and ensure that new hires are set up correctly from the start. This script will: 1. Connect to Microsoft Entra ID using Microsoft Graph. 2. Create a new user with specified parameters. 3. Assign the user to a designated role. 4. Send a welcome email to the new user. Using this script can enhance productivity and reduce the time spent on manual user management tasks.

powershell
# Install Microsoft Graph module if not already installed
if (-Not (Get-Module -ListAvailable -Name Microsoft.Graph)) {
    Install-Module -Name Microsoft.Graph -Scope CurrentUser -AllowClobber
}
# Connect to Microsoft Graph
Connect-MgGraph -Scopes 'User.ReadWrite.All', 'Directory.AccessAsUser.All'
# Define parameters for the new user
$userPrincipalName = "[email protected]"
$displayName = "New User"
$password = "P@ssword123!"  # Use a secure password
$mailNickname = "newuser"
$roleId = "your-role-id"  # Replace with the role ID to assign
# Create the new user
$newUser = New-MgUser -UserPrincipalName $userPrincipalName -DisplayName $displayName -AccountEnabled $true -MailNickname $mailNickname -PasswordProfile @{
    ForceChangePasswordNextSignIn = $true
    Password = $password
}
# Assign the user to a role
New-MgUserAppRoleAssignment -UserId $newUser.Id -AppRoleId $roleId -ResourceId "your-resource-id"  # Replace with the resource ID
# Send a welcome email
$welcomeEmailBody = "Welcome $displayName! Your account has been created. Log in using: Username: $userPrincipalName Password: $password"
Send-MailMessage -To $userPrincipalName -From "[email protected]" -Subject "Welcome Aboard!" -Body $welcomeEmailBody -SmtpServer "smtp.yourdomain.com"
Write-Host "User account created and welcome email sent to $displayName."
# Disconnect from Microsoft Graph
Disconnect-MgGraph
Write-Host "User management process completed."

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.

Ready when you are.

Try ServerEngine free for 7 days.