Enable MFA for Microsoft 365 Users Using Graph Powershell
This PowerShell script is useful for M365 administrators managing Microsoft 365 environments to ensure all users have Multi-Factor Authentication (MFA) enabled, enhancing security by protecting accounts against unauthorized access. It automates the process of checking MFA status and enabling it where needed, saving time and reducing manual effort.
Graph PowerShell Script for Enabling Microsoft 365 User MFA
# Import the Microsoft Graph module
Import-Module Microsoft.Graph
# Connect to Microsoft Graph with the required scopes
Connect-MgGraph -Scopes "User.Read.All", "Directory.ReadWrite.All", "UserAuthenticationMethod.ReadWrite.All"
# Function to get MFA status of a user
function Get-MFAStatus {
param (
[string]$UserId
)
# Retrieve all authentication methods for the specified user
$userMethods = Get-MgUserAuthenticationMethod -UserId $UserId
# Filter the authentication methods to check if any of them are phone or email (common MFA methods)
$mfaEnabled = $userMethods.AuthenticationMethod | Where-Object { $_.methodType -eq 'phone' -or $_.methodType -eq 'email' }
# Return true if any MFA methods are enabled, otherwise false
return $mfaEnabled.Count -gt 0
}
# Function to enable MFA for a user (
function Enable-MFA {
param (
[string]$UserId,
[string]$PhoneNumber
)
try {
# Add a new phone method for MFA using the provided phone number
New-MgUserAuthenticationPhoneMethod -UserId $UserId -PhoneNumber $PhoneNumber -PhoneType mobile
Write-Output "MFA enabled for user with ID: $UserId"
} catch {
# Catch and display any errors that occur during the MFA enabling process
Write-Error "Failed to enable MFA for user with ID: $UserId. Error: $_"
}
}
# Path to the CSV file containing user principal names and phone numbers
$csvPath = "C:\Path\To\Users.csv"
# Import users from the CSV file
$users = Import-Csv -Path $csvPath
foreach ($user in $users) {
$userPrincipalName = $user.UserPrincipalName
$phoneNumber = $user.PhoneNumber
# Get user details from Microsoft Graph using their user principal name
$userObj = Get-MgUser -UserPrincipalName $userPrincipalName
$userId = $userObj.Id
# Check the MFA status of the user
$mfaStatus = Get-MFAStatus -UserId $userId
if (-not $mfaStatus) {
Write-Output "Enabling MFA for $userPrincipalName with phone number $phoneNumber"
Enable-MFA -UserId $userId -PhoneNumber $phoneNumber
} else {
Write-Output "MFA already enabled for $userPrincipalName"
}
}
# Disconnect from Microsoft Graph
Disconnect-MgGraph
You can download the script here: enable-MFA-script
How the Script Works?
- Import the Microsoft Graph Module: This line imports the Microsoft Graph PowerShell module, which is required to interact with Microsoft 365 services.
Import-Module Microsoft.Graph
- Connect to Microsoft Graph: This line connects to Microsoft Graph with the specified scopes, allowing the script to read user information, write directory information, and manage user authentication methods.
Connect-MgGraph -Scopes "User.Read.All", "Directory.ReadWrite.All", "UserAuthenticationMethod.ReadWrite.All"
- Get-MFAStatus Function: This function checks if MFA is enabled for a specific user.
- Parameters: $UserId: The unique identifier for the user.
- Process: i)Retrieves all authentication methods for the user. ii)Filters to check if any of these methods are phone or email (common MFA methods). iii) Returns true if any MFA methods are found, otherwise false.
# Function to get MFA status of a user
function Get-MFAStatus {
param (
[string]$UserId
)
# Retrieve all authentication methods for the specified user
$userMethods = Get-MgUserAuthenticationMethod -UserId $UserId
# Filter the authentication methods to check if any of them are phone or email (common MFA methods)
$mfaEnabled = $userMethods.AuthenticationMethod | Where-Object { $_.methodType -eq 'phone' -or $_.methodType -eq 'email' }
# Return true if any MFA methods are enabled, otherwise false
return $mfaEnabled.Count -gt 0
}
- Enable-MFA Function: This function enables MFA for a user by adding a phone method.
- Parameters: $UserId: The unique identifier for the user. $PhoneNumber: The phone number to be used for MFA.
- Process: i)Tries to add a new phone method for MFA using the provided phone number. ii)Outputs a success message if MFA is enabled successfully. iii) Catches and displays any errors if the process fails.
# Function to enable MFA for a user (
function Enable-MFA {
param (
[string]$UserId,
[string]$PhoneNumber
)
try {
# Add a new phone method for MFA using the provided phone number
New-MgUserAuthenticationPhoneMethod -UserId $UserId -PhoneNumber $PhoneNumber -PhoneType mobile
Write-Output "MFA enabled for user with ID: $UserId"
} catch {
# Catch and display any errors that occur during the MFA enabling process
Write-Error "Failed to enable MFA for user with ID: $UserId. Error: $_"
}
}
- Path to CSV File: This line specifies the path to the CSV file containing user information.
$csvPath = "C:\Path\To\Users.csv"
- Import Users from CSV File: This line imports user data from the CSV file into a variable..
$users = Import-Csv -Path $csvPath
- Loop Through Each User
- Loops through each user in the CSV file.
- Retrieves the user’s principal name and phone number from the CSV.
- Gets user details from Microsoft Graph using the principal name.
- Checks the MFA status of the user.
- If MFA is not enabled, enables MFA using the phone number.
- Outputs the result for each user.
foreach ($user in $users) {
$userPrincipalName = $user.UserPrincipalName
$phoneNumber = $user.PhoneNumber
# Get user details from Microsoft Graph using their user principal name
$userObj = Get-MgUser -UserPrincipalName $userPrincipalName
$userId = $userObj.Id
# Check the MFA status of the user
$mfaStatus = Get-MFAStatus -UserId $userId
if (-not $mfaStatus) {
Write-Output "Enabling MFA for $userPrincipalName with phone number $phoneNumber"
Enable-MFA -UserId $userId -PhoneNumber $phoneNumber
} else {
Write-Output "MFA already enabled for $userPrincipalName"
}
}
- Disconnect from Microsoft Graph: This line disconnects the session from Microsoft Graph.
Disconnect-MgGraph
Possible Issues You Might Face While Running The Script
Here are some of the issues you might face while trying to execute the script and how to solve them.
- Permission Issues: Error: Request Authorization failed Status: 403 (Forbidden)
Solution: Ensure the user running the script has the necessary permissions. You need the Directory.AccessAsUser.All, UserAuthenticationMethod.ReadWrite.All, and User.Read.All permissions.
- Not Allowed By Policy: Error: notAllowedByPolicy
Solution: Review Conditional Access policies, Authentication Methods policies, and Identity Protection policies in the Azure AD portal. Modify the policies or create exceptions to allow the required authentication methods.
- Script Execution Policy: Error: File C:\Path\To\Script.ps1 cannot be loaded because running scripts is disabled on this system
Solution: Change the execution policy to allow script execution.. Use the following command to change the execution policy: Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
- Invalid Phone Number Format: Error: Invalid phone number format
Solution: Ensure the phone number is in the correct format (e.g., +1234567890). Validate the phone number before attempting to add it
- User Not Found:: Error: Error: User not found
Solution: Ensure the user exists in your Azure AD. Double-check the user identifier. Use Get-MgUser -All to list all user ids and check for the correctness of user id.
Related Articles:
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