Get MFA Status of Office 365 users with Microsoft Graph

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.

So this new MFA Status script can do pretty much the same things as the old script:

  • List the configured MFA types of all users
  • Get all the users that don’t have MFA enabled
  • Check the MFA configuration 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
  • Get the preferred MFA method of the user
  • Check if Hello for Business is registered
  • Registered email address for Self Services Password Reset (SSPR)

What we currently can’t check is if MFA is actually enabled or disabled for the users, or if MFA is enforced (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 has continuously updated, and with the latest versions, we don’t have to use the beta endpoints anymore. This means that we can connect to Graph in the normal way with the required scopes to retrieve all the data using the Get-MgUser cmdlet.

mfa status microsoft graph
Get MFA Status with Microsoft Graph

After we have collected all the users we can use the Get-MgUserAuthenticationMethod cmdlet to get all the MFA details.

Note

With Graph we can’t actually check if MFA is enabled or disabled for user. We can only check which Authentication methods are configured.

Microsoft is moving away from per-user MFA configuration, we will need to move to Conditional Access policies for MFA. So currently, MFA can be disabled for a particular user in the Admin center and we can’t detect that with Graph.

However, if you have Azure P1 or P2, then checkout this script. Or you can still use the old MSOL module for this, so make sure you check this script as well if you are still using per-user MFA.

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 'johndoe@contoso.com'

The parameter accepts a string array, so you can comma separate the users that you want to retrieve:

Get-MgMFAStatus -UserPrincipalName 'johndoe@contoso.com','janedoe@contoso.com'

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.
<#
.Synopsis
  Get the MFA status for all users or a single user with Microsoft Graph

.DESCRIPTION
  This script will get the Azure MFA Status for your users. You can query all the users, admins only or a single user.
   
	It will return the MFA Status, MFA type and registered devices.

  Note: Default MFA device is currently not supported https://docs.microsoft.com/en-us/graph/api/resources/authenticationmethods-overview?view=graph-rest-beta
        Hardwaretoken is not yet supported

.NOTES
  Name: Get-MgMFAStatus
  Author: R. Mens - LazyAdmin.nl
  Version: 1.2
  DateCreated: Jun 2022
  Purpose/Change: Added MFA preferred method

.LINK
  https://lazyadmin.nl

.EXAMPLE
  Get-MgMFAStatus

  Get the MFA Status of all enabled and licensed users and check if there are an admin or not

.EXAMPLE
  Get-MgMFAStatus -UserPrincipalName 'johndoe@contoso.com','janedoe@contoso.com'

  Get the MFA Status for the users John Doe and Jane Doe

.EXAMPLE
  Get-MgMFAStatus -withOutMFAOnly

  Get only the licensed and enabled users that don't have MFA enabled

.EXAMPLE
  Get-MgMFAStatus -adminsOnly

  Get the MFA Status of the admins only

.EXAMPLE
  Get-MgUser -Filter "country eq 'Netherlands'" | ForEach-Object { Get-MgMFAStatus -UserPrincipalName $_.UserPrincipalName }

  Get the MFA status for all users in the Country The Netherlands. You can use a similar approach to run this
  for a department only.

.EXAMPLE
  Get-MgMFAStatus -withOutMFAOnly| Export-CSV c:\temp\userwithoutmfa.csv -noTypeInformation

  Get all users without MFA and export them to a CSV file
#>

[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" -NoWelcome
}

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 }
                } | 
                Select @{Name="Role"; Expression = {$role}}, DisplayName, UserPrincipalName, Mail, Id | 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  = "-"
      helloForBusinessCount = 0
      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"
            $mfaMethods.helloForBusinessCount++
          } 
          "#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-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
  }
}

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
      $manager = Get-Manager -userId $_.id

       $uri = "https://graph.microsoft.com/beta/users/$($_.id)/authentication/signInPreferences"
       $mfaPreferredMethod = Invoke-MgGraphRequest -uri $uri -Method GET

       if ($null -eq ($mfaPreferredMethod.userPreferredMethodForSecondaryAuthentication)) {
        # When an MFA is configured by the user, then there is alway a preferred method
        # So if the preferred method is empty, then we can assume that MFA isn't configured
        # by the user
        $mfaMethods.status = "disabled"
       }

      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 Preferred method" = $mfaPreferredMethod.userPreferredMethodForSecondaryAuthentication
          "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
          "Manager" = $manager
        }
      }
    }
  }
}

# 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 and the new Microsoft Entra-based version 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:

46 thoughts on “Get MFA Status of Office 365 users with Microsoft Graph”

  1. Hey Rudy, I am running into an issue with lines 327 and 328. I believe this section may have been added later on as I wasn’t having issues before December 2023. It appears this code was added after Zack’s comment on November 17. The error I receive is the same as Scerazy’s comment.

    Invoke-MgGraphRequest : Specified argument was out of the range of valid values.
    Parameter name: value
    At C:\temp\PowerShellScripts\Get-MgMFAStatus.ps1:328 char:30
    + … $mfaPreferredMethod = Invoke-MgGraphRequest -uri $uri -Method GET
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: (:) [Invoke-MgGraphRequest], ArgumentOutOfRangeException
    + FullyQualifiedErrorId : NotSpecified,Microsoft.Graph.PowerShell.Authentication.Cmdlets.InvokeMgGraphRequest

    • I have indeed added that part. But I have done some tests with differents tenants and I am unable to replicate the issue. Which version of the Microsoft Graph module do you have installed? (Get-InstalledModule Microsoft.Graph). And are you using PowerShell 5.1 or 7?

      I have updated the script with a try-catch block, so it won’t throw an error now. But it isn’t really solved either this way…

  2. Hey Rudy! I’m trying to figure out if is there any possibility of making a sample regarding mfa status for members per specific security group. Could you please advise what exact parameter should I a script with? Thanks a lot for a hint, your blog is awesome!

  3. Invoke-MgGraphRequest : Specified argument was out of the range of valid values.
    Parameter name: value
    At C:\PSScripts\Get-MgMFAStatus.ps1:331 char:30
    + … $mfaPreferredMethod = Invoke-MgGraphRequest -uri $uri -Method GET
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: (:) [Invoke-MgGraphRequest], ArgumentOutOfRangeException
    + FullyQualifiedErrorId : NotSpecified,Microsoft.Graph.PowerShell.Authentication.Cmdlets.InvokeMgGraphRequest

  4. FYI You can get a user’s default MFA method via Graph using the following:

    $User = Get-MgUser -UserId $Username
    $uri = “https://graph.microsoft.com/beta/users/$($User.id)/authentication/signInPreferences”
    $DefaultMFAMethod = Invoke-MgGraphRequest -uri $uri -Method GET
    $DefaultMFAMethod

  5. Hi Rudy,

    Is there a way to show all devices registered with authentication methods? I currently have 2 phones connected with the authenticator app but the script is only showing my iphone and not my android. However, when I run (Get-MgUserAuthenticationMethod -UserId “email address”).AdditionalProperties I see both listed.

    I’m wondering if there is a way to configure the script to look at all registered devices and list them out. I’m trying to track down users with multiple authenticator apps registered.

    Thanks!

  6. Hello,

    I used your script with the MSOL module and it works fine. I now use your script with the MS Graph and also works fine.

    In my test lab security defaults is disabled and no CA policies are active. I activated MFA per user basis. I activated MFA on an account, run the script and the result is that MFA is enabled. But if I disable MFA for the individual user and run the script again the result is that MFA is still enabled but it’s not. It’s temporarely disabled. I can login at the account without MFA. Is it possible to check if MFA is really active and not disabled at the user leve?

    • At the moment, no. I understand that the script in the current form might be misleading (I will add a note to this article about it). The problem is that we can only check which MFA methods a user has configured with Graph. If, for what ever reason, an admin overrides the MFA status per user to disabled, then it indeed won’t reflect in this script.

      Microsoft is moving away from the per-user MFA configuration. They want us to move to conditional access policies for it (with security defaults as a basis). At the moment, the only option is to use the old MSOL based script, which is now supported to mid-2024.

      The old MSOL module would first be deprecated in 2022, so that is why I created the Graph based script. Maybe the feature to check it per user might come to Graph but time will tell.

  7. 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.

  8. 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

  9. 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?

  10. 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"

  11. 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.

  12. 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

  13. 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

  14. 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?

  15. 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

  16. 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?

  17. 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

  18. 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”

    • 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
      #

  19. 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.

Leave a Comment

0 Shares
Tweet
Pin
Share
Share