Automating User Onboarding in Microsoft Entra ID with PowerShell

Onboarding new users efficiently is essential for any organization. This PowerShell script simplifies the onboarding process for new employees by automating user creation and assigning basic roles in Microsoft Entra ID. With this script, IT administrators can ensure that new hires are set up with minimal manual intervention, speeding up the time it takes to get them productive.
This script will:
1. Connect to Microsoft Entra ID.
2. Create a new user with specified attributes.
3. Assign the user to a predefined role or group.
By utilizing this script, organizations can streamline their onboarding processes, reduce errors, and ensure that all new users receive the appropriate access from day one.

# Import 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', 'Group.ReadWrite.All'
# Define parameters for the new user
$newUser = @{
    UserPrincipalName = "[email protected]"
    DisplayName = "New User"
    MailNickname = "newuser"
    AccountEnabled = $true
    PasswordProfile = @{
        ForceChangePasswordNextSignIn = $true
        Password = "P@ssw0rd!" # Consider generating a stronger password
    }
}
# Create the new user
$createdUser = New-MgUser -BodyParameter $newUser
# Assign the user to a group (optional)
$groupId = "your-group-id" # Replace with the target group ID
Add-MgGroupMember -GroupId $groupId -DirectoryObjectId $createdUser.Id
# Output the results
Write-Host "User '$($createdUser.DisplayName)' created successfully with UPN: $($createdUser.UserPrincipalName)"
# Disconnect from Microsoft Graph
Disconnect-MgGraph
Write-Host "User onboarding process completed."