Keeping track of your user’s MFA Status is important to keep your tenant protected. For now, we can still use the Msol module for this in PowerShell, but Microsoft is planning to retire this module. So I have recreated my successful MFA Status script with the Microsoft Graph module.
The Microsoft Graph module isn’t fully completed yet. It doesn’t only lack documentation, but we also can’t retrieve all information yet from it. For example, we can’t retrieve (or set) the default MFA method with Graph at the moment.
So this new MFA Status script can do pretty much the same things as the old script:
- List the MFA Status of all users
- List configured MFA types for each user
- Get all the users that don’t have MFA enabled
- Check the MFA status of a single user
- Checks if a user is admin or not
- Get only the licensed and enabled users
But with Graph, we are also able to retrieve a little bit more information than with the old module. So the following information is now also retrieved:
- Authenticator device name
- Check if Hello for business is registered
- Registered email address for Self Services Password Reset (SSPR)
What we currently can’t retrieve is the default MFA method, and if MFA is enforced for the users (as in that the user needs to configure MFA the next time after login).
As always, you will find the complete script at the end of the article.
Get MFA Status with Microsoft Graph and PowerShell
Microsoft Graph still has a lot of features only available in their beta release. So the first thing the script does is connect to Graph with the required scopes and switch over to the beta profile. We can then retrieve all users with the Get-MgUser cmdlet.
After we have collected all the users we can use the Get-MgUserAuthenticationMethod cmdlet to get all the MFA details.
Requirements
You will need to have the Microsoft Graph module installed. The script will check if the module is installed, if not you will be given the option to install it.
Getting all users and their MFA Status
The script comes with a couple of parameters that we can use to fine-tune the export results. But by default, it will get all licensed users, list the admins, and save the CSV Export at the same location as the script. The script will open the CSV file when completed.
So to get all users we can simply run the script:
# Get all licensed users: Get-MgMFAStatus.ps1
Get only users without MFA
When you have a large tenant you probably only want to see the users who don’t have MFA enabled. To do this you can add use the switch -withoutMFAOnly
:
Get-MgMFAStatus.ps1 -withOutMFAOnly
Check MFA Status of Admin only
The script will list all admins by default, but you can also check the MFA Status from admins only with the -adminsOnly
switch:
Get-MgMFAStatus.ps1 -adminsOnly
Check the status of a specific user or a selection of users
It’s also possible to check the MFA status of a specific user. We can specify the UserPrincipal name of the user using the -UserPrincipalName parameter:
Get-MgMFAStatus -UserPrincipalName '[email protected]'
The parameter accepts a string array, so you can comma separate the users that you want to retrieve:
Get-MgMFAStatus -UserPrincipalName '[email protected]','[email protected]'
Another option is to use the filter of the Get-MgUser cmdlet and then pipe the Get-MgMFAStatus script:
Get-MgUser -Filter "country eq 'Netherlands'" | ForEach-Object { Get-MgMFAStatus -UserPrincipalName $_.UserPrincipalName }
The Complete Script
The complete script can be downloaded from my Github repository, which I recommend using so you have always the latest version.
Tip
Quickly get the MFA Status of your users by adding a reference to the script in your PowerShell Profile. Read all about it in this article.
[CmdletBinding(DefaultParameterSetName="Default")] param( [Parameter( Mandatory = $false, ParameterSetName = "UserPrincipalName", HelpMessage = "Enter a single UserPrincipalName or a comma separted list of UserPrincipalNames", Position = 0 )] [string[]]$UserPrincipalName, [Parameter( Mandatory = $false, ValueFromPipeline = $false, ParameterSetName = "AdminsOnly" )] # Get only the users that are an admin [switch]$adminsOnly = $false, [Parameter( Mandatory = $false, ValueFromPipeline = $false, ParameterSetName = "Licensed" )] # Check only the MFA status of users that have license [switch]$IsLicensed = $true, [Parameter( Mandatory = $false, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, ParameterSetName = "withOutMFAOnly" )] # Get only the users that don't have MFA enabled [switch]$withOutMFAOnly = $false, [Parameter( Mandatory = $false, ValueFromPipeline = $false )] # Check if a user is an admin. Set to $false to skip the check [switch]$listAdmins = $true, [Parameter( Mandatory = $false, HelpMessage = "Enter path to save the CSV file" )] [string]$path = ".\MFAStatus-$((Get-Date -format "MMM-dd-yyyy").ToString()).csv" ) Function ConnectTo-MgGraph { # Check if MS Graph module is installed if (-not(Get-InstalledModule Microsoft.Graph)) { Write-Host "Microsoft Graph module not found" -ForegroundColor Black -BackgroundColor Yellow $install = Read-Host "Do you want to install the Microsoft Graph Module?" if ($install -match "[yY]") { Install-Module Microsoft.Graph -Repository PSGallery -Scope CurrentUser -AllowClobber -Force }else{ Write-Host "Microsoft Graph module is required." -ForegroundColor Black -BackgroundColor Yellow exit } } # Connect to Graph Write-Host "Connecting to Microsoft Graph" -ForegroundColor Cyan Connect-MgGraph -Scopes "User.Read.All, UserAuthenticationMethod.Read.All, Directory.Read.All" # Select the beta profile Select-MgProfile Beta } Function Get-Admins{ <# .SYNOPSIS Get all user with an Admin role #> process{ $admins = Get-MgDirectoryRole | Select-Object DisplayName, Id | %{$role = $_.displayName; Get-MgDirectoryRoleMember -DirectoryRoleId $_.id | where {$_.AdditionalProperties."@odata.type" -eq "#microsoft.graph.user"} | % {Get-MgUser -userid $_.id | Where-Object {($_.AssignedLicenses).count -gt 0}} } | Select @{Name="Role"; Expression = {$role}}, DisplayName, UserPrincipalName, Mail, ObjectId | Sort-Object -Property Mail -Unique return $admins } } Function Get-Users { <# .SYNOPSIS Get users from the requested DN #> process{ # Set the properties to retrieve $select = @( 'id', 'DisplayName', 'userprincipalname', 'mail' ) $properties = $select + "AssignedLicenses" # Get enabled, disabled or both users switch ($enabled) { "true" {$filter = "AccountEnabled eq true and UserType eq 'member'"} "false" {$filter = "AccountEnabled eq false and UserType eq 'member'"} "both" {$filter = "UserType eq 'member'"} } # Check if UserPrincipalName(s) are given if ($UserPrincipalName) { Write-host "Get users by name" -ForegroundColor Cyan $users = @() foreach ($user in $UserPrincipalName) { try { $users += Get-MgUser -UserId $user -Property $properties | select $select -ErrorAction Stop } catch { [PSCustomObject]@{ DisplayName = " - Not found" UserPrincipalName = $User isAdmin = $null MFAEnabled = $null } } } }elseif($adminsOnly) { Write-host "Get admins only" -ForegroundColor Cyan $users = @() foreach ($admin in $admins) { $users += Get-MgUser -UserId $admin.UserPrincipalName -Property $properties | select $select } }else { if ($IsLicensed) { # Get only licensed users $users = Get-MgUser -Filter $filter -Property $properties -all | Where-Object {($_.AssignedLicenses).count -gt 0} | select $select }else{ $users = Get-MgUser -Filter $filter -Property $properties -all | select $select } } return $users } } Function Get-MFAMethods { <# .SYNOPSIS Get the MFA status of the user #> param( [Parameter(Mandatory = $true)] $userId ) process{ # Get MFA details for each user [array]$mfaData = Get-MgUserAuthenticationMethod -UserId $userId # Create MFA details object $mfaMethods = [PSCustomObject][Ordered]@{ status = "-" authApp = "-" phoneAuth = "-" fido = "-" helloForBusiness = "-" emailAuth = "-" tempPass = "-" passwordLess = "-" softwareAuth = "-" authDevice = "-" authPhoneNr = "-" SSPREmail = "-" } ForEach ($method in $mfaData) { Switch ($method.AdditionalProperties["@odata.type"]) { "#microsoft.graph.microsoftAuthenticatorAuthenticationMethod" { # Microsoft Authenticator App $mfaMethods.authApp = $true $mfaMethods.authDevice = $method.AdditionalProperties["displayName"] $mfaMethods.status = "enabled" } "#microsoft.graph.phoneAuthenticationMethod" { # Phone authentication $mfaMethods.phoneAuth = $true $mfaMethods.authPhoneNr = $method.AdditionalProperties["phoneType", "phoneNumber"] -join ' ' $mfaMethods.status = "enabled" } "#microsoft.graph.fido2AuthenticationMethod" { # FIDO2 key $mfaMethods.fido = $true $fifoDetails = $method.AdditionalProperties["model"] $mfaMethods.status = "enabled" } "#microsoft.graph.passwordAuthenticationMethod" { # Password # When only the password is set, then MFA is disabled. if ($mfaMethods.status -ne "enabled") {$mfaMethods.status = "disabled"} } "#microsoft.graph.windowsHelloForBusinessAuthenticationMethod" { # Windows Hello $mfaMethods.helloForBusiness = $true $helloForBusinessDetails = $method.AdditionalProperties["displayName"] $mfaMethods.status = "enabled" } "#microsoft.graph.emailAuthenticationMethod" { # Email Authentication $mfaMethods.emailAuth = $true $mfaMethods.SSPREmail = $method.AdditionalProperties["emailAddress"] $mfaMethods.status = "enabled" } "microsoft.graph.temporaryAccessPassAuthenticationMethod" { # Temporary Access pass $mfaMethods.tempPass = $true $tempPassDetails = $method.AdditionalProperties["lifetimeInMinutes"] $mfaMethods.status = "enabled" } "#microsoft.graph.passwordlessMicrosoftAuthenticatorAuthenticationMethod" { # Passwordless $mfaMethods.passwordLess = $true $passwordLessDetails = $method.AdditionalProperties["displayName"] $mfaMethods.status = "enabled" } "#microsoft.graph.softwareOathAuthenticationMethod" { # ThirdPartyAuthenticator $mfaMethods.softwareAuth = $true $mfaMethods.status = "enabled" } } } Return $mfaMethods } } Function Get-MFAStatusUsers { <# .SYNOPSIS Get all AD users #> process { Write-Host "Collecting users" -ForegroundColor Cyan # Collect users $users = Get-Users Write-Host "Processing" $users.count "users" -ForegroundColor Cyan # Collect and loop through all users $users | ForEach { $mfaMethods = Get-MFAMethods -userId $_.id if ($withOutMFAOnly) { if ($mfaMethods.status -eq "disabled") { [PSCustomObject]@{ "Name" = $_.DisplayName Emailaddress = $_.mail UserPrincipalName = $_.UserPrincipalName isAdmin = if ($listAdmins -and ($admins.UserPrincipalName -match $_.UserPrincipalName)) {$true} else {"-"} MFAEnabled = $false "Phone number" = $mfaMethods.authPhoneNr "Email for SSPR" = $mfaMethods.SSPREmail } } }else{ [pscustomobject]@{ "Name" = $_.DisplayName Emailaddress = $_.mail UserPrincipalName = $_.UserPrincipalName isAdmin = if ($listAdmins -and ($admins.UserPrincipalName -match $_.UserPrincipalName)) {$true} else {"-"} "MFA Status" = $mfaMethods.status # "MFA Default type" = "" - Not yet supported by MgGraph "Phone Authentication" = $mfaMethods.phoneAuth "Authenticator App" = $mfaMethods.authApp "Passwordless" = $mfaMethods.passwordLess "Hello for Business" = $mfaMethods.helloForBusiness "FIDO2 Security Key" = $mfaMethods.fido "Temporary Access Pass" = $mfaMethods.tempPass "Authenticator device" = $mfaMethods.authDevice "Phone number" = $mfaMethods.authPhoneNr "Email for SSPR" = $mfaMethods.SSPREmail } } } } } # Connect to Graph ConnectTo-MgGraph # Get Admins # Get all users with admin role $admins = $null if (($listAdmins) -or ($adminsOnly)) { $admins = Get-Admins } # Get MFA Status Get-MFAStatusUsers | Sort-Object Name | Export-CSV -Path $path -NoTypeInformation if ((Get-Item $path).Length -gt 0) { Write-Host "Report finished and saved in $path" -ForegroundColor Green # Open the CSV file Invoke-Item $path }else{ Write-Host "Failed to create report" -ForegroundColor Red }
Wrapping Up
Having MFA enabled really helps with protecting your tenant. This PowerShell script allows you to easily check the MFA status of your users.
Make sure you also check this article with 20 other security tips for Office 365. You can find the Msol version of this script here.
If you found this script useful, then please share it. If you have any questions then just drop a comment below.
You may also like one of the following PowerShell report scripts:
Very nice script, thank you!
I used it to check if all admins have MFA enabled.
Unfortunately the script does only list admin users with active assignments, the ones with eligible assignments will not be listed.
Hi Rudy,
I found that users enrolled in Google Authenticator MFA TOTP codes showed the MFA Status column as enabled, but did not have a column indicating which method they were using.
It looks like a final method was added to the script for “#microsoft.graph.softwareOathAuthenticationMethod” on line 284 but a corresponding column was not added to the csv file for this.
Adding line 350 with the following line gave me results in the CSV that tell me that the user has a 3rd party OATH app.
“3rd Party Authenticator” = $mfaMethods.softwareAuth
This addition might be useful for others as well to help differentiate which type of MFA the user has setup or show that they have multiple enrolled.
Thanks, Josh
Amazing script, is there any way to get this to show the last login date of each user please? Thanks.
You could add the property’SignInActivity’, but that requires Azure AD Premium Plan 2
Great script!
But for me it only shows the first 100 users. We have approx 15K!
Any way to resolve this? Has Microsoft made a change/put up some sort of limit on their API maybe?
That is strange. Do you get all the results when you run the following command?:
Get-MgUser -all
Any chance you can update to filter users created in last X amount of days. I love this script but it would be great to be able to limit the scope to a timeline. I’ve tried to add to the script but Im just a noob.
You can use the following filter to get all users that are created the last year for example:
Get-MgUser -Filter "CreatedDateTime ge $((Get-Date).AddYears(-1).ToString("s"))Z"
Really super useful, thanks so much for this!
I’m sure I’m missing something obvious, but I can’t run this with parameters. If I open the script in Powershell ISE and hit run it runs correctly, spitting out a file at the end.
If I try to run Get-MgMFAStatus -withoutMFAonly
I get: et-mgmfastatus : The term ‘get-mgmfastatus’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and try again.
At line:1 char:1
+ get-mgmfastatus -withoutmfaonly
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (get-mgmfastatus:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
I tried running it with powershell in front of the command and explicity indicating the path, putting a ps1 at the end of the file name… nothing seems to work.
Like I said – I’m sure I’m missing something simple.
Make sure that you save the file first, naming it, for example, Get-mgmfastatus.ps1. Then you can run it with the parameters. If you want to know more about running PowerShell scripts, then read this article.
Got it – thanks. The problem was that I wasn’t running it in the Powershell as admin window.
HI!
Running the script with
Get-MgUser -Filter “country eq ‘Netherlands'” | ForEach-Object { Get-MgMFAStatus -UserPrincipalName $_.UserPrincipalName }
leads to an error that the script was not found, even if I am in the same folder.
Adding a ./ infront of Get-MgMFAStatus starts the process, but it exports one by one. So if there are 20 accounts to export, I get 20 excel files. And the whole process with “Welcome To MS Graph….” starts 20 time and that takes quite long.
Is there anything I can do so I get all suitable users in one excel file?
Kepp up the good work. Thank you. Cheers!
Axel
It is easier to add the country filter in line 144 or 146.
Hi Ruud,
I can get the default methodtype now in the Graph API
e.g. (not my work, just searching 🙂 )
$user.StrongAuthenticationMethods
gives
ExtensionData IsDefault MethodType
————- ——— ———-
System.Runtime.Serialization.ExtensionDataObject False PhoneAppOTP
System.Runtime.Serialization.ExtensionDataObject True PhoneAppNotification
and then
$DefaultMethod = ($User.StrongAuthenticationMethods | ? { $_.IsDefault -eq “True” }).MethodType
StrongAuthenticationMethods is part of the MsolUser cmdlet. The problem is that msoluser is going to be depreciated at some point. You can use this MFA script for that.
Hi everyone,
I just run this Script for different Customers. I did get some respond that the status is false.
Checked it in the azure Admin Center and the results from the script are not the same.
Did somebody notice that?
Hello
for a strange reason, both graph version and the msol version, show me users who are disabled as enabled (the same users)
what I notice about those users is that they have the MFA configured, they have authenticator setup and phone numbers etc, but they are disabled cause someone disabled them afterwards or they forgot to enable
but on the report in “MFA Status” show as enabled
any idea why this might happening?
I verified that I can catch those type of users checking “MFA Enabled” is True and “MFA Enforced” is blank, on the MSOL report
but on the Graph one I cannot get this easy, I have to filter if they have any method enabled
Thanx a lot for you work
Thanks for sharing. It is asking for sign-in prompt for reporting each user’s MFA status. What parameter i can use to only provide creds in the beginning?
It should only show the prompt ones. Do you have the correct permissions?
I tried with GA creds. Also, gave consent to the required scopes to run.
Checkout this issue on Github, seems similar to your situation. Seems like running a Disconnect-Graph might solve it. And check your PowerShell versions.
I have been playing with your script since I found it and I have been trying to add the manager for each user without success.
I created a switch, a function, pasted the full query when looping trough users but all I acheived is increase the script running time. Managers remain blank. I know that it’s because the Manager field has to be resolved by expanding the properties. Could you provide some insight to get it in there?
Standalone, this is the query I use to report the managers for each employee:
Get-MgUser -All -Filter “UserType eq ‘Member'” -ExpandProperty manager | Select UserPrincipalName,DisplayName,@{Name = ‘Manager’; Expression = {$_.Manager.AdditionalProperties.displayName}}
You can use this function:
Function Get-Manager {
<# .SYNOPSIS Get the manager users #>
param(
[Parameter(Mandatory = $true)] $userId
)
process {
$manager = Get-MgUser -UserId $userId -ExpandProperty manager | Select @{Name = 'name'; Expression = {$_.Manager.AdditionalProperties.displayName}}
return $manager.name
}
}
And then add it to the Get-MFAStatusUsers foreach loop : $manager = Get-Manager -userId $_.id
Late update but this works perfectly. Thank you very much
If it helps anyone, I had the same issue as Flávio: Get-MgDirectoryRole : Insufficient privileges to complete the operation.
adding the scope Directory.Read.All resolved my issue
Connect-MgGraph -Scopes “User.Read.All, UserAuthenticationMethod.Read.All, Directory.Read.All”
Thanks, it’s strange that it works here without the directory.read.all scope, but I have added it to script.
Yes, it seems that was the one that sorted me out as well (I tried a number of things, but I can boil it down to that)
Also, my (based on another script I found) script, my come in handy for someone. it outputs users to a csv list based on State (as united states, I am based in the UK, so its free real estate for tagging):
param($defaultpath=”$env:USERPROFILE\downloads”,$pwdnochangedindays = 480)
cd $defaultpath
Start-transcript
$cohort = read-host “Enter cohort to audited”
Connect-MgGraph -Scopes “Directory.ReadWrite.All”, “Directory.AccessAsUser.All”,”User.Read.All”,”AuditLog.Read.All”
Select-MgProfile -Name beta
Get-MgUser -Filter “userType eq ‘Member’ and AccountEnabled eq true and startsWith(State, ‘$cohort’)” -all -Property id,displayName,State,signInActivity,userPrincipalName, `
userType,onPremisesSyncEnabled,createdDateTime,accountEnabled,passwordPolicies,mail,lastPasswordChangeDateTime | `
select id,displayName,State,userPrincipalName,userType,onPremisesSyncEnabled,createdDateTime,accountEnabled,mail,lastPasswordChangeDateTime,passwordPolicies, `
@{N=’LastSignInDateTime’;E={$_.signInActivity.LastSignInDateTime}}, @{N=’LastNonInteractiveSignInDateTime’;E={$_.signInActivity.LastNonInteractiveSignInDateTime}} | `
export-csv .\aad_user_report_$cohort.csv -notypeinformation
write-host “Report can be found here cd $defaultpath”
Stop-transcript
# Based on chadmcox create-AADMGUserReport.ps1
#
Hi!
I am getting the following error while running this script:
Get-MgDirectoryRole : Insufficient privileges to complete the operation.
At C:\Users\SharedFolder\User-Management\Get-MgMFAStatus.ps1:132 char:5
+ $admins = Get-MgDirectoryRole | Select-Object DisplayName, Id |
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: ({ Skip = , Sear…ndProperty = }:f__AnonymousType58`7) [Get-MgDirectoryRole_List], RestException`1
+ FullyQualifiedErrorId : Authorization_RequestDenied,Microsoft.Graph.PowerShell.Cmdlets.GetMgDirectoryRole_List
Any idea why is happening?
I can run Get-MgUsers.ps1 and I am a global admin.
The error would indicate that Graph isn’t connected with the required scopes:
Connect-MgGraph -Scopes "User.Read.All, UserAuthenticationMethod.Read.All"
What happens if you try the following code:
Connect-MgGraph -Scopes "User.Read.All, UserAuthenticationMethod.Read.All"
Get-MgDirectoryRole
I think I solved (The permissions hadn’t been set correctly, for some reason) even got a better script sorted out for my specific needs. But lot of the inspiration and help came from here.
Keep up the good work, I am refering to this blog on a weekly basis.