How do i construct a script that can check the Azure Tentant and enable MFA for Admins?

376 Views Asked by At

Hello Stack Overflow,

I'm encountering the following issue. I'm trying to create a script that will check what administrator accounts are present on the O365 tenant and enable automatically for them MFA so that, the next time they will log in the will be prompted to setup MFA.

The code bellow is as following:

$mfa1 = Get-MsolUser | Select-Object UserPrincipalName,StrongAuthenticationMethods,StrongAuthenticationRequirements | Where-object {$_.UserPrincipalName -notin $exclude }

foreach ($item in $mfa1) {
if ($null -ne $item.StrongAuthenticationMethods){
    $st = New-Object -TypeName Microsoft.Online.Administration.StrongAuthenticationRequirement
    $st.RelyingParty = "*"
    $st.State = "Enable"
    $sta = @($st)
    Set-MsolUser -UserPrincipalName $item.UserPrincipalName -StrongAuthenticationRequirements $sta
    Write-Host "test1"
}
else {
    Write-Host "test2"
}

}

Let me know where the i'm wrong, i have searched almost all the internet for a solution without having to upload the users from the CSV

Thanks in advance !

1

There are 1 best solutions below

2
On

Seems you got some issue, but the code below that based on your code works perfectly for me.

For a quick test, I specify a user to go through this process:

$mfa1 = Get-MsolUser | Select-Object UserPrincipalName,StrongAuthenticationMethods,StrongAuthenticationRequirements | Where-object {$_.UserPrincipalName -eq  '<User Principal Name>' }
foreach ($item in $mfa1) {
#if there is no StrongAuthenticationMethods, enable MFA
if ($item.StrongAuthenticationMethods.Count -eq 0){
    $st = New-Object -TypeName Microsoft.Online.Administration.StrongAuthenticationRequirement
    $st.RelyingParty = "*"
    #here is the issue that you can't set MFA successfully, the value should be "Enabled"
    $st.State = "Enabled"
    $sta = @($st)
    Set-MsolUser -UserPrincipalName $item.UserPrincipalName -StrongAuthenticationRequirements $sta
    Write-Host "test1"
}
else {
    Write-Host "test2"
    }
}

When a user has enabled MFA and set MFA method:

enter image description here

When a user has no MFA method:

enter image description here

Let me know if you have any further questions.