Búsqueda de sitios web

Exporte los usuarios de MFA Status Office 365 con PowerShell


Uno de los informes que realmente extraño en el Centro de administración de Microsoft 365 es una descripción general clara del estado de MFA de cada usuario. MFA es una medida de seguridad realmente importante para proteger a su inquilino. Para asegurarnos de que nuestros usuarios hayan configurado MFA, usaremos PowerShell para obtener y exportar el estado de MFA.

También puede utilizar la descripción general integrada en el Centro de administración, pero eso llevaría mucho tiempo. Por otro lado, con PowerShell podemos obtener fácilmente el estado MFA de todos los usuarios y crear una lista de Excel con todos los detalles que necesitamos.

He creado un script que puede hacer un par de cosas para verificar e informar el estado de MFA de sus usuarios:

  • Enumere el estado de MFA de todos los usuarios
  • Listar los tipos de MFA configurados para cada usuario
  • Obtenga todos los usuarios que no tienen MFA habilitado
  • Verifique el estado de MFA de un solo usuario
  • Compruebe si se aplica la MFA
  • Comprueba si un usuario es administrador o no
  • Obtenga solo los usuarios habilitados y con licencia

Al final del artículo encontrarás el guión completo.

Nota

También creé este script basado en Microsoft Graph. Obtendrá un poco más de información que este script. ¡Asegúrate de comprobarlo!

Obtenga el estado de MFA con PowerShell

Con PowerShell, podemos obtener fácilmente el estado MFA de todos nuestros usuarios de Office 365. La base del script es el cmdlet Get-MsolUser, que obtiene los usuarios de Azure Active Directory.

Get-MsolUser devuelve todos los detalles del usuario, incluido el parámetro StrongAuthenticationMethods. Este parámetro enumerará todos los métodos de autenticación segura que utiliza un usuario. Si se establece este parámetro, entonces sabemos que el usuario está utilizando MFA.

Consejo

Agregue este script a su perfil de PowerShell para que pueda verificar fácilmente el estado de MFA de sus usuarios. Lea más sobre esto en este artículo.

Requisitos

Debe tener instalado el módulo MsolService para utilizar este script. Asegúrese de estar conectado antes de ejecutar el script.

Connect-MsolService

Obtener una lista de todos los usuarios y su estado MFA

Puede simplemente ejecutar el script sin ningún parámetro para obtener una lista de todos los usuarios y su estado de MFA. La secuencia de comandos verificará si el usuario es administrador y enumerará el tipo de MFA predeterminado que el usuario ha configurado.

Puede exportar el resultado en la pantalla o a un archivo CSV si lo desea.

# Make sure you are connected to MsolService
Get-MFAStatus.ps1 | FT

# Or if you want an excel file
Get-MFAStatus.ps1 | Export-CSV c:\temp\mfastatus.csv -noTypeInformation

Obtenga solo los usuarios sin MFA

Si tiene un inquilino grande, probablemente solo desee obtener usuarios sin MFA. Puede utilizar el modificador withOutMFAOly para esto.

Get-MFAStatus.ps1 -withOutMFAOnly

Verifique el estado de MFA de los administradores

Los administradores deberían tener habilitado MFA sin lugar a dudas. Para verificar rápidamente el estado de todas sus cuentas de administrador, puede usar el interruptor adminsOnly

Get-MFAStatus.ps1 -adminsOnly

Verifique el estado de MFA en una selección de usuarios

El script también le permite verificar el estado de MFA de uno o varios usuarios.

Get-MFAStatus.ps1 -UserPrincipalName 'johndoe@contoso.com'

Si desea verificar el estado de un solo departamento, por ejemplo, puede hacer lo siguiente:

Get-MsolUser.ps1 -Department 'Finance' | ForEach-Object { Get-MFAStatus $_.UserPrincipalName }

El guión completo

Puede encontrar el script completo aquí debajo o puede obtenerlo aquí desde mi Github. (Recomiendo usar Github para asegurarse de tener la última versión).

Consejo

Obtenga rápidamente el estado de MFA de sus usuarios agregando una referencia al script en su perfil de PowerShell. Lea todo sobre esto en este artículo.
<#
  Name: Get-MFAStatus
  Author: R. Mens - LazyAdmin.nl
  Version: 1.3
  DateCreated: jan 2021
  Purpose/Change: List all Configured MFA Types
	Thanks to: Anthony Bartolo
#>
[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  = "AllUsers"
  )]
  # Set the Max results to return
  [int]$MaxResults = 10000,

  [Parameter(
    Mandatory         = $false,
    ValueFromPipeline = $false,
    ParameterSetName  = "Licenend"
  )]
  # 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
)



# Connect to Msol
if ((Get-Module -ListAvailable -Name MSOnline) -eq $null)
{
  Write-Host "MSOnline Module is required, do you want to install it?" -ForegroundColor Yellow
      
  $install = Read-Host Do you want to install module? [Y] Yes [N] No 
  if($install -match "[yY]") 
  { 
    Write-Host "Installing MSOnline module" -ForegroundColor Cyan
    Install-Module MSOnline -Repository PSGallery -AllowClobber -Force
  } 
  else
  {
	  Write-Error "Please install MSOnline module."
  }
}

if ((Get-Module -ListAvailable -Name MSOnline) -ne $null) 
{
  if(-not (Get-MsolDomain -ErrorAction SilentlyContinue))
  {
	  Connect-MsolService
  }
}
else{
  Write-Error "Please install Msol module."
}
  
# Get all licensed admins
$admins = $null

if (($listAdmins) -or ($adminsOnly)) {
  $admins = Get-MsolRole | %{$role = $_.name; Get-MsolRoleMember -RoleObjectId $_.objectid} | Where-Object {$_.isLicensed -eq $true} | select @{Name="Role"; Expression = {$role}}, DisplayName, EmailAddress, ObjectId | Sort-Object -Property EmailAddress -Unique
}

# Check if a UserPrincipalName is given
# Get the MFA status for the given user(s) if they exist
if ($PSBoundParameters.ContainsKey('UserPrincipalName')) {
  foreach ($user in $UserPrincipalName) {
		try {
      $MsolUser = Get-MsolUser -UserPrincipalName $user -ErrorAction Stop

      $Method = ""
      $MFAMethod = $MsolUser.StrongAuthenticationMethods | Where-Object {$_.IsDefault -eq $true} | Select-Object -ExpandProperty MethodType

      If (($MsolUser.StrongAuthenticationRequirements) -or ($MsolUser.StrongAuthenticationMethods)) {
        Switch ($MFAMethod) {
            "OneWaySMS" { $Method = "SMS token" }
            "TwoWayVoiceMobile" { $Method = "Phone call verification" }
            "PhoneAppOTP" { $Method = "Hardware token or authenticator app" }
            "PhoneAppNotification" { $Method = "Authenticator app" }
        }
      }

      [PSCustomObject]@{
        DisplayName       = $MsolUser.DisplayName
        UserPrincipalName = $MsolUser.UserPrincipalName
        isAdmin           = if ($listAdmins -and $admins.EmailAddress -match $MsolUser.UserPrincipalName) {$true} else {"-"}
        MFAEnabled        = if ($MsolUser.StrongAuthenticationMethods) {$true} else {$false}
        MFAType           = $Method
				MFAEnforced       = if ($MsolUser.StrongAuthenticationRequirements) {$true} else {"-"}
      }
    }
		catch {
			[PSCustomObject]@{
				DisplayName       = " - Not found"
				UserPrincipalName = $User
				isAdmin           = $null
				MFAEnabled        = $null
			}
		}
  }
}
# Get only the admins and check their MFA Status
elseif ($adminsOnly) {
  foreach ($admin in $admins) {
    $MsolUser = Get-MsolUser -ObjectId $admin.ObjectId | Sort-Object UserPrincipalName -ErrorAction Stop

    $MFAMethod = $MsolUser.StrongAuthenticationMethods | Where-Object {$_.IsDefault -eq $true} | Select-Object -ExpandProperty MethodType
    $Method = ""

    If (($MsolUser.StrongAuthenticationRequirements) -or ($MsolUser.StrongAuthenticationMethods)) {
        Switch ($MFAMethod) {
            "OneWaySMS" { $Method = "SMS token" }
            "TwoWayVoiceMobile" { $Method = "Phone call verification" }
            "PhoneAppOTP" { $Method = "Hardware token or authenticator app" }
            "PhoneAppNotification" { $Method = "Authenticator app" }
        }
      }
    
    [PSCustomObject]@{
      DisplayName       = $MsolUser.DisplayName
      UserPrincipalName = $MsolUser.UserPrincipalName
      isAdmin           = $true
      "MFA Enabled"     = if ($MsolUser.StrongAuthenticationMethods) {$true} else {$false}
      "MFA Default Type"= $Method
      "SMS token"       = if ($MsolUser.StrongAuthenticationMethods.MethodType -contains "OneWaySMS") {$true} else {"-"}
      "Phone call verification" = if ($MsolUser.StrongAuthenticationMethods.MethodType -contains "TwoWayVoiceMobile") {$true} else {"-"}
      "Hardware token or authenticator app" = if ($MsolUser.StrongAuthenticationMethods.MethodType -contains "PhoneAppOTP") {$true} else {"-"}
      "Authenticator app" = if ($MsolUser.StrongAuthenticationMethods.MethodType -contains "PhoneAppNotification") {$true} else {"-"}
			MFAEnforced = if ($MsolUser.StrongAuthenticationRequirements) {$true} else {"-"}
    }
  }
}
# Get the MFA status from all the users
else {
  $MsolUsers = Get-MsolUser -EnabledFilter EnabledOnly -MaxResults $MaxResults | Where-Object {$_.IsLicensed -eq $isLicensed} | Sort-Object UserPrincipalName
    foreach ($MsolUser in $MsolUsers) {

      $MFAMethod = $MsolUser.StrongAuthenticationMethods | Where-Object {$_.IsDefault -eq $true} | Select-Object -ExpandProperty MethodType
      $Method = ""

      If (($MsolUser.StrongAuthenticationRequirements) -or ($MsolUser.StrongAuthenticationMethods)) {
        Switch ($MFAMethod) {
            "OneWaySMS" { $Method = "SMS token" }
            "TwoWayVoiceMobile" { $Method = "Phone call verification" }
            "PhoneAppOTP" { $Method = "Hardware token or authenticator app" }
            "PhoneAppNotification" { $Method = "Authenticator app" }
        }
      }

      if ($withOutMFAOnly) {
        # List only the user that don't have MFA enabled
        if (-not($MsolUser.StrongAuthenticationMethods)) {

          [PSCustomObject]@{
            DisplayName       = $MsolUser.DisplayName
            UserPrincipalName = $MsolUser.UserPrincipalName
            isAdmin           = if ($listAdmins -and ($admins.EmailAddress -match $MsolUser.UserPrincipalName)) {$true} else {"-"}
            MFAEnabled        = $false
            MFAType           = "-"
						MFAEnforced       = if ($MsolUser.StrongAuthenticationRequirements) {$true} else {"-"}
          }
        }
      }else{
        [PSCustomObject]@{
          DisplayName       = $MsolUser.DisplayName
          UserPrincipalName = $MsolUser.UserPrincipalName
          isAdmin           = if ($listAdmins -and ($admins.EmailAddress -match $MsolUser.UserPrincipalName)) {$true} else {"-"}
          "MFA Enabled"     = if ($MsolUser.StrongAuthenticationMethods) {$true} else {$false}
          "MFA Default Type"= $Method
          "SMS token"       = if ($MsolUser.StrongAuthenticationMethods.MethodType -contains "OneWaySMS") {$true} else {"-"}
          "Phone call verification" = if ($MsolUser.StrongAuthenticationMethods.MethodType -contains "TwoWayVoiceMobile") {$true} else {"-"}
          "Hardware token or authenticator app" = if ($MsolUser.StrongAuthenticationMethods.MethodType -contains "PhoneAppOTP") {$true} else {"-"}
          "Authenticator app" = if ($MsolUser.StrongAuthenticationMethods.MethodType -contains "PhoneAppNotification") {$true} else {"-"}
					MFAEnforced       = if ($MsolUser.StrongAuthenticationRequirements) {$true} else {"-"}
        }
      }
    }
  }

Concluyendo

Habilitar MFA es uno de los pasos importantes para proteger a su inquilino. Con este script de PowerShell, puede comprobar fácilmente el estado de MFA de sus usuarios.

Asegúrese de consultar también este artículo con otros 20 consejos de seguridad para Office 365.

Si este script le resultó útil, compártalo. Si tiene alguna pregunta, simplemente deje un comentario a continuación.

Es posible que también le guste uno de los siguientes scripts de informes de PowerShell:

  • Informe de permisos de buzón
  • Informe de tamaño del buzón
  • Informe de tamaño de OneDrive

Artículos relacionados