Bulk Password Reset for Microsoft 365 Users Using Graph PowerShell

This guide demonstrates how to perform a bulk password reset in Microsoft 365 using Microsoft Graph PowerShell. Learn how to reset passwords for multiple users efficiently with practical examples and scripts

Resetting user passwords individually can be time-consuming, especially in large organizations. Automating this process using PowerShell scripts and Microsoft Graph can save valuable time and reduce human errors. This article guides you through creating a PowerShell script to reset passwords in bulk, explaining how the script works, potential enhancements, common errors, and solutions.


PowerShell Script for Bulk Password Reset

Here's the PowerShell script to reset passwords for multiple users using the Microsoft Graph PowerShell module. Ensure you have a CSV file with user identifiers and new passwords before running the script.

Prerequisites:

  • Ensure Graph PowerShell module is installed and connected: Connect-MgGraph -Scopes "User.ReadWrite.All"
  • Only admins with the right roles (e.g., User Administrator, Global Administrator) can reset passwords.
  • CSV file must include the following columns: UserPrincipalName or UserId and NewPassword

CSV File Format

Note: You can use the Get-MgUser cmdlet to fetch the required User IDs.

# Import necessary modules
Import-Module Microsoft.Graph

# Connect to Microsoft Graph
Connect-MgGraph -Scopes "User.ReadWrite.All"

# Path to the CSV file containing the user IDs and new passwords
$csvFilePath = "C:\path\to\your\users.csv"

# Import the CSV file
$userList = Import-Csv -Path $csvFilePath

# Loop through each user in the CSV file
foreach ($user in $userList) {
    try {
        # Reset the user's password
        Update-MgUser -UserId $user.UserId -PasswordProfile @{ Password = $user.NewPassword; ForceChangePasswordNextSignIn = $true }
        
        Write-Host "Password reset successfully for user: $($user.UserId)" -ForegroundColor Green
    } catch {
        Write-Host "Failed to reset password for user: $($user.UserId). Error: $($_.Exception.Message)" -ForegroundColor Red
    }
}

# Disconnect from Microsoft Graph
Disconnect-MgGraph

How the Script Works

  • Import the Microsoft Graph PowerShell Module: The script starts by importing the Microsoft Graph PowerShell module.
  • Connect to Microsoft Graph: It connects to Microsoft Graph with the necessary permissions (User.ReadWrite.All).
  • Import CSV File: The script imports a CSV file that contains the user IDs and new passwords.
  • Loop through Each User: For each user in the CSV, the script resets the password and forces the user to change the password at the next sign-in.
  • Error Handling: If there is an error resetting the password, the script catches the exception and prints an error message.
  • Disconnect from Microsoft Graph: Finally, the script disconnects the session after completing the operations.

How the Script Can Be Further Enhanced

  • Logging: Enhance the script by adding logging functionality to record successful and failed password reset attempts in a log file.
  • $logFilePath = "C:\path\to\your\logfile.txt"
  • Email Notifications: Implement email notifications to inform administrators of the script's execution status.
  • # Send email notification function
    Function Send-EmailNotification {
        param (
            [string]$subject
            [string]$body
        )
    
        $smtpServer = "smtp.yourserver.com"
        $smtpFrom = "admin@yourdomain.com"
        $smtpTo = "admin@yourdomain.com"
    
        $message = New-Object system.net.mail.mailmessage
        $message.from = $smtpFrom
        $message.To.add($smtpTo)
        $message.Subject = $subject
        $message.Body = $body
        $smtp = New-Object Net.Mail.SmtpClient($smtpServer)
        $smtp.Send($message)
    }
    
    # Example usage
    Send-EmailNotification -subject "Password Reset Completed" -body "The password reset script has completed."
  • User Confirmation: Add a confirmation step to ensure that the correct users are being targeted before executing the password reset.
  • $userList | Format-Table -Property UserId, NewPassword
    $confirmation = Read-Host "Do you want to proceed with these changes? (Y/N)"
    if ($confirmation -ne "Y") {
        Write-Host "Operation canceled." -ForegroundColor Yellow
        exit
    }

Possible Errors and Solutions

Error Solution
Authentication Issues
Error: "Connect-MgGraph: Authorization_RequestDenied"
Ensure that you have the necessary permissions (User.ReadWrite.All) and that your account is not restricted.
Invalid User ID
Error: "Update-MgUser: Resource 'userId' does not exist or one of its queried reference-property objects are not present."
Verify that the User IDs in the CSV file are correct and exist in your directory.
Rate Limiting:
Error: "HTTP 429 Too Many Requests"
    Implement retry logic with exponential backoff to handle rate limiting. 
# Retry logic $retryCount = 0 $maxRetries = 5 $retryDelay = 5 while ($retryCount -lt $maxRetries) { try { Update-MgUser -UserId $user.UserId -PasswordProfile @{ Password = $user.NewPassword; ForceChangePasswordNextSignIn = $true } Write-Host "Password reset successfully for user: $($user.UserId)" -ForegroundColor Green break } catch { $retryCount++ Write-Host "Retrying in $retryDelay seconds... ($retryCount/$maxRetries)" -ForegroundColor Yellow Start-Sleep -Seconds $retryDelay $retryDelay = [math]::Min($retryDelay * 2, 60) } } if ($retryCount -eq $maxRetries) { Write-Host "Failed to reset password for user: $($user.UserId). Error: $($_.Exception.Message)" -ForegroundColor Red }

Frequently Asked Questions

  • How can I reset a single user's password using Graph PowerShell?
    Use the Update-MgUser cmdlet with the passwordProfile parameter. Example:
    $Body = @{
        passwordProfile = @{
            forceChangePasswordNextSignIn = $true
            password = "NewSecurePassword123!"
        }
    }
    Update-MgUser -UserId "<UserPrincipalName>" -BodyParameter $Body
    
  • Can I reset passwords for multiple users using a CSV file?
    Yes, prepare a CSV file with the following format:
    UserPrincipalName,Password
    user1@domain.com,NewPassword123!
    user2@domain.com,AnotherSecurePassword!
    
  • Use this script to process the CSV and reset passwords:
    $Body = @{
        passwordProfile = @{
            forceChangePasswordNextSignIn = $true
            password = "NewSecurePassword123!"
        }
    }
    
  • How can I ensure users are required to change their password at the next sign-in?
    Set the forceChangePasswordNextSignIn property to $true in the passwordProfile. Example:
    $Body = @{
        passwordProfile = @{
            forceChangePasswordNextSignIn = $true
            password = "NewSecurePassword123!"
        }
    }
    Update-MgUser -UserId "<UserPrincipalName>" -BodyParameter $Body
    
  • What permissions are required to reset passwords?
    You need the User.ReadWrite.All or Directory.AccessAsUser.All permission in Microsoft Graph PowerShell. Ensure these permissions are granted before performing password resets.
  • Can I set different passwords for each user?
    Yes, you can add a Password column in the CSV file and customize the $params object inside the loop
  • Will users receive a notification after password reset?
    No, Microsoft Graph does not trigger email notifications on password reset. You must notify users manually or automate it via email scripts

Bulk Password Reset Using Admin Center

  1. Login into Microsoft 365 Admin Center
  2. Select Users >> Active Users page. Select the users >> Click "Reset Password" button.
  3. Reset Password flyout opens. Click the "Reset password" button.
  4. Passwords have been reset confirmation message gets displayed.

Tips

  • Avoid Common Passwords: Always use strong, unique passwords or generate random passwords to avoid triggering security policies.
  • Handle Errors Gracefully: Wrap the reset logic in a try-catch block to capture and log errors.
    try {
        Update-MgUser -UserId $user.UserPrincipalName -BodyParameter $params
    } catch {
        Write-Host "Failed to reset password for $($user.UserPrincipalName): $_"
    }
  • What permissions are required to reset passwords?
    You need the User.ReadWrite.All or Directory.AccessAsUser.All permission in Microsoft Graph PowerShell. Ensure these permissions are granted before performing password resets.
🔐 Enforce Password Reset by Setting forceChangePasswordNextSignIn

To make sure users update their passwords after a bulk reset, always set forceChangePasswordNextSignIn to $true inside the passwordProfile block.

$Body = @{ passwordProfile = @{ forceChangePasswordNextSignIn = $true password = "NewSecurePassword123!" } }
Update-MgUser -UserId "<string>" -BodyParameter $Body


This helps enforce compliance and enhances account security following a mass reset.
⚠️ You Need UserAuthenticationMethod.Write.All or User.ReadWrite.All Permissions

Performing password resets — especially in bulk — requires elevated Graph API permissions.

Make sure your session or app registration has either of the following:
  • UserAuthenticationMethod.Write.All
  • User.ReadWrite.All
These can be delegated or application permissions depending on your use case.

Conclusion

Automating the process of resetting passwords in bulk using Microsoft Graph PowerShell can significantly streamline administrative tasks and improve efficiency. The script provided in this article offers a robust solution for bulk password reset. By enhancing the script with logging, email notifications, and user confirmation, you can create a more comprehensive and user-friendly tool. Additionally, being aware of common errors and their solutions ensures smoother execution and troubleshooting.

By leveraging this script, administrators can save time and reduce errors, ultimately contributing to more efficient IT operations.


Related Articles:

Using Get-MgDirectoryRole in Graph PowerShell
Using Get-MgUserLicenseDetail in Graph PowerShell
Using Find-GraphMgCommand in Graph PowerShell
Connect to Microsoft 365 Using PowerShell
How to Create Bulk Users in Office 365 Using Graph PowerShell?
Create Microsoft 365 Group Using Microsoft Graph PowerShell
Block Microsoft 365 User Using Microsoft Graph PowerShell
Assign Microsoft 365 License Using Graph PowerShell
Microsoft 365 User Management Using Graph PowerShell
Checking Group Membership in Microsoft 365
Bulk Assign Microsoft 365 License
Find Inactive Users in Microsoft 365
Using Powershell Graph Search Query
Using Powershell Graph Filter Query
Using Where-Object In Graph PowerShell
Using Expand Property In Graph PowerShell
Using Select Object In Graph PowerShell
Using -Contains Operator In Graph PowerShell
Add User to Multiple Microsoft 365 Groups Using Graph PowerShell
Get Microsoft 365 User Location Using Graph PowerShell
Import Microsoft 365 Groups from CSV File Using Graph PowerShell
Microsoft 365 Group User Import Using Graph PowerShell

© m365corner.com. All Rights Reserved. Design by HTML Codex