Búsqueda de sitios web

Microsoft 365: busque la fecha del último inicio de sesión de los usuarios


Requisito: busque la fecha y hora del último inicio de sesión de todos los usuarios en el inquilino de Microsoft 365.

PowerShell para generar el informe de la fecha del último inicio de sesión en Office 365

Administrar cuentas de usuario de manera efectiva es crucial para las organizaciones que usan Office 365. Uno de los aspectos esenciales de la administración de usuarios es monitorear la actividad de los usuarios, incluidas sus últimas fechas de inicio de sesión. En esta publicación de blog, lo guiaremos a través del proceso de encontrar la fecha del último inicio de sesión de los usuarios en Office 365 usando PowerShell.

Centro de administración de Microsoft 365, registros de inicio de sesión de Azure AD y el cmdlet de PowerShell Get-AzureADAuditSignInLogs: ¡los tres tienen una limitación de registros de 30 días en Office 365!

Si desea buscar la fecha del último inicio de sesión dentro de los últimos 30 días de todos los usuarios que utilizan PowerShell, este es el script para usted:


#Config Parameters
$CSVPath = "C:\Temp\SigninLogs.csv"
$SigninLogs = @()

#Connect to Azure AD
Connect-AzureAD | Out-Null

#Get All users from Azure AD
$AllUsers = Get-AzureADUser -All $true
$TotalUsers = $AllUsers.Count

#Function to get the last login time stamp of the user
Function Get-UserLastLogin([string] $UserObjectID)
{
    Try {
        Write-host -f Yellow "Collecting Last Login date of the User Object:"$UserObjectID

        #Get the Successful Signin Logs of the user
        $SigninLog = Get-AzureADAuditSignInLogs -All:$true -Filter "userID eq '$UserObjectID' and status/errorCode eq 0" | Select -First 1

        #Return Last Login Date
        $LoginDetails = New-Object psobject -Property @{
            LoginTime = $SigninLog.CreatedDateTime
            App = $SigninLog.AppDisplayName
        }
        Return $LoginDetails
    }
    Catch {
        $message = $_
        If ($message -like "*Too Many Requests*")
        {
            Write-host "`tSleeping for 10 seconds due to throttling limitations..." -ForegroundColor Cyan
            Sleep 10
            #Recursive function call to retry the entry that was throttled
            Get-UserLastLogin $UserObjectID
        }
        Else
        {
            Write-host $Message -ForegroundColor Red           
        }
    }
}

#Loop through all users
$Counter = 1
$AllUsers | ForEach-Object {
    Write-Progress -Activity "Checking Signin Logs:" -Status "Processing $($_.UserPrincipalName) ($Counter of $TotalUsers)" -PercentComplete (($Counter / $TotalUsers) * 100) 
    #Call the function to get the sign-in log
    $SignInLog = Get-UserLastLogin $_.ObjectID
    
    #Get the Last Login Date
    If ($SignInLog.LoginTime -eq $Null)
    {
        $LastLoginDate = "No Log-in Events Found!"
    }
    Else
    {
        $LastLoginDate = Get-Date $SignInLog.LoginTime
    }

    #Collect data
    $SigninLogs += [PSCustomObject][ordered]@{
        UserLoginName   = $_.UserPrincipalName
        UserDisplayName   = $_.DisplayName
        LastLogin  = $LastLoginDate
        Application = $SignInLog.App
    }
    $Counter++
}

$SigninLogs
#Export Data to CSV
$SigninLogs | Export-Csv -Path $CSVPath -NoTypeInformation

Sin embargo, el script anterior puede obtener datos solo durante 30 días.

Genere el informe del último inicio de sesión para Office 365 usando Graph API PowerShell

¡La API de Microsoft Graph puede obtener la fecha del último inicio de sesión sin un límite de 30 días!

Requisitos previos

Antes de acceder a la última información de inicio de sesión del usuario de Office 365, debe instalar el módulo Microsoft Graph PowerShell. Consulte aquí para saber cómo instalar el módulo Microsoft Graph PowerShell.


#Connect to Microsoft Graph
Connect-MgGraph -Scopes "AuditLog.Read.All","User.Read.All"

#Set the Graph Profile
Select-MgProfile beta

#Properties to Retrieve
$Properties = @(
    'Id','DisplayName','Mail','UserPrincipalName','UserType', 'AccountEnabled', 'SignInActivity'    
)

#Get All users along with the properties
$AllUsers = Get-MgUser -All -Property $Properties #| Select-Object $Properties

$SigninLogs = @()
ForEach ($User in $AllUsers)
{
    $SigninLogs += [PSCustomObject][ordered]@{
            LoginName       = $User.UserPrincipalName
            Email           = $User.Mail
            DisplayName     = $User.DisplayName
            UserType        = $User.UserType
            AccountEnabled  = $User.AccountEnabled
            LastSignIn      = $User.SignInActivity.LastSignInDateTime
    }
}

$SigninLogs

#Export Data to CSV
$SigninLogs | Export-Csv -Path "C:\Temp\SigninLogs.csv" -NoTypeInformation

Este script recupera todos los usuarios de su inquilino de Office 365, recopila su última información de inicio de sesión y genera los resultados en un informe CSV.

Artículos relacionados