Script to Batch enable Per-user multifactor authentication in Entra via Graph in Powershell

Install-Module -Name Microsoft.Graph -Scope CurrentUser

# Connect to Microsoft Graph with required scopes
Connect-MgGraph -Scopes "User.Read.All", "Policy.ReadWrite.AuthenticationMethod"

# Get all users with UPN ending in @domain.onmicrosoft.com, with ConsistencyLevel and $count=true
$users = Get-MgUser -Filter "endsWith(userPrincipalName, '@domain.onmicrosoft.com')" -All -ConsistencyLevel eventual -CountVariable userCount | Select-Object Id, UserPrincipalName

# Check if users were found
if ($users.Count -eq 0) {
    Write-Host "No users found with UPN ending in @doylo.onmicrosoft.com." -ForegroundColor Yellow
} else {
    Write-Host "Found $($users.Count) users with UPN ending in @doylo.onmicrosoft.com." -ForegroundColor Cyan

    # Loop through each user and enable MFA
    foreach ($user in $users) {
        $userId = $user.Id
        $userUPN = $user.UserPrincipalName

        Write-Host "Enabling MFA for user: $userUPN" -ForegroundColor Green

        # Define the MFA state
        $body = @{
#Can be Enforced as well
            "perUserMfaState" = "enabled"
        }

        # Update the user's MFA state
        Invoke-MgGraphRequest -Method PATCH -Uri "/beta/users/$userId/authentication/requirements" -Body $body
    }

    Write-Host "MFA has been enabled for all matching users." -ForegroundColor Cyan
}
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...