Bulk Password Reset Using Microsoft Graph PowerShell

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.

CSV File Format

Your CSV file should have the following headers:

  • UserId: User Principal Name or Object ID
  • NewPassword: The new password for the user

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

Authentication Issues:

Error: "Connect-MgGraph: Authorization_RequestDenied"

Solution: 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."

Solution: Verify that the User IDs in the CSV file are correct and exist in your directory.

Rate Limiting:

Error: "HTTP 429 Too Many Requests"

Solution: 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
}

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