Getting Microsoft 365 User Sign-In Logs with Microsoft Graph - Part 3

IMPORTANT:
Cloud Modernization Notice (2026):
The original script acquired tokens using ADAL from the retired AzureAD module with a hard-coded username and password. This post now uses Microsoft Graph PowerShell (Get-MgAuditLogSignIn), which supports MFA, token refresh, and app-only authentication. The original script is kept at the bottom for reference.

This is part 3 of my Microsoft Graph series:

In this post we use OData query parameters ($filter) to fetch sign-in logs for a specific user. This is the first thing you need when investigating account lockouts, impossible-travel alerts, or Conditional Access failures.


Requirements

  • Permission: AuditLog.Read.All (delegated or application) plus Directory.Read.All.
  • Role (delegated): Reports Reader, Security Reader, or Global Reader.
  • License: Sign-in logs through Graph require Microsoft Entra ID P1 or P2.
  • Retention: Entra ID keeps sign-in logs for 30 days (P1/P2). Stream them to Log Analytics if you need more.
POWERSHELL
Install-Module Microsoft.Graph.Reports -Scope CurrentUser -Repository PSGallery
Connect-MgGraph -Scopes "AuditLog.Read.All", "Directory.Read.All"

Building $filter Queries

The sign-in log endpoint (/auditLogs/signIns) supports $filter on many properties. Common examples:

TEXT
# All sign-ins for one user
userPrincipalName eq '[email protected]'

# One user, on or after a date (use full ISO 8601 UTC timestamps)
userPrincipalName eq '[email protected]' and createdDateTime ge 2026-11-01T00:00:00Z

# Only failed sign-ins (errorCode 0 = success)
userPrincipalName eq '[email protected]' and status/errorCode ne 0

# Sign-ins to a specific application
appDisplayName eq 'Office 365 Exchange Online'

With the SDK you pass the filter string as-is. There's no URL building and no escaping of $filter:

POWERSHELL
$filter = "userPrincipalName eq '[email protected]' and createdDateTime ge 2026-11-01T00:00:00Z"
Get-MgAuditLogSignIn -Filter $filter -Top 50 |
    Select-Object CreatedDateTime, AppDisplayName, ClientAppUsed, IpAddress, @{n='ErrorCode';e={$_.Status.ErrorCode}}

Reusable Function: Get-UserSignInLog

This modern replacement for the original GetSignInLogs function keeps the same parameters (-Upn, -DateGTE, -GetFailed) but has no credentials in the script.

POWERSHELL
<#
.SYNOPSIS
    Fetches Entra ID sign-in logs for a user via Microsoft Graph PowerShell.
.EXAMPLE
    Get-UserSignInLog -Upn sc@lab365.in -DateGTE 2026-11-01 -GetFailed
.NOTES
    Author: Sunil Chauhan (https://www.lab365.in)
    Requires: Microsoft.Graph.Reports; scope AuditLog.Read.All
#>
function Get-UserSignInLog {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$Upn,

        # Date greater than or equal to, format YYYY-MM-DD
        [ValidatePattern('^\d{4}\d{2}\d{2}')]
        [string]$DateGTE,

        # Return only failed sign-ins
        [switch]$GetFailed,

        [string]$ExportPath
    )

    if (-not (Get-MgContext)) {
        Connect-MgGraph -Scopes "AuditLog.Read.All", "Directory.Read.All" -NoWelcome
    }

    $filter = "userPrincipalName eq '$Upn'"
    if ($DateGTE)   { $filter += " and createdDateTime ge $($DateGTE)T00:00:00Z" }
    if ($GetFailed) { $filter += " and status/errorCode ne 0" }

    Write-Verbose "Graph filter: $filter"
    $logs = Get-MgAuditLogSignIn -Filter $filter -All

    $report = $logs | Select-Object `
        CreatedDateTime,
        UserPrincipalName,
        AppDisplayName,
        ClientAppUsed,
        IpAddress,
        @{ n = 'Location';      e = { "$($_.Location.City), $($_.Location.CountryOrRegion)" } },
        @{ n = 'ErrorCode';     e = { $_.Status.ErrorCode } },
        @{ n = 'FailureReason'; e = { $_.Status.FailureReason } },
        ConditionalAccessStatus,
        @{ n = 'OS';            e = { $_.DeviceDetail.OperatingSystem } },
        @{ n = 'Browser';       e = { $_.DeviceDetail.Browser } }

    if ($ExportPath) {
        $report | Export-Csv -Path $ExportPath -NoTypeInformation -Encoding utf8
        Write-Host "[+] $($report.Count) sign-in record(s) exported to $ExportPath" -ForegroundColor Green
    }

    return $report
}

Parameters

  • -Upn: UPN of the user whose sign-in logs you want.
  • -DateGTE: Only return sign-ins on or after this date (YYYY-MM-DD). Leave it out to return everything in the retention window.
  • -GetFailed: Return only failed sign-ins. The filter runs server-side, which is much faster than filtering in PowerShell.
  • -ExportPath: Optional CSV export.

Example runs

POWERSHELL
# Failed sign-ins for one user since 1 November, shown as a table
Get-UserSignInLog -Upn sc@lab365.in -DateGTE 2026-11-01 -GetFailed | Format-Table -AutoSize

# Everything in the retention window, exported to CSV
Get-UserSignInLog -Upn sc@lab365.in -ExportPath .\sc-signins.csv
TIP:
Common error codes when triaging: 50126 invalid username or password, 50053 account locked (smart lockout), 50074/50076 MFA required, 53003 blocked by Conditional Access, 50158 external security challenge not satisfied.


Archival Reference: Original 2019 Script (Do Not Use)

Click to view the original ADAL-based script

Original download: GitHub - Get-User-sign-in-Logs.ps1

POWERSHELL
function GetSignInLogs {
param ($upn, [switch]$getfailed,$DateGTE)
#///////////////////MODIFY THE DETAILS BELOW/////////////////////////////////////
$Office365Username='adminuserid'
$Office365Password='Password'
$clientId = "c14a2820-b922-4139-901b-36024950fc95"
#////////////////////////////////////////////////////////////////////////////////
$resourceURI = "https://graph.microsoft.com"
$authority = "https://login.microsoftonline.com/common"
$AadModule = Import-Module -Name AzureAD -ErrorAction Stop -PassThru
$adal = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
[System.Reflection.Assembly]::LoadFrom($adal) | Out-Null
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
$SecurePassword = ConvertTo-SecureString -AsPlainText $Office365Password -Force
$AADCredential = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserPasswordCredential" -ArgumentList $Office365Username,$SecurePassword
$authResult = [Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContextIntegratedAuthExtensions]::AcquireTokenAsync($authContext, $resourceURI, $clientid, $AADCredential);
$accessToken = $authResult.result.AccessToken
$apiUrl = 'https://graph.microsoft.com/beta/auditLogs/signIns?' + "`$filter=userPrincipalName eq " + "'" + $upn + "'"
if ($DateGTE) { $apiUrl += " and createdDateTime ge " + $DateGTE }
$Data = Invoke-RestMethod -Headers @{Authorization = "Bearer $accessToken"} -Uri $apiUrl -Method Get
$PR = $Data.value
if ($getfailed) { $PR | ? {$_.status.errorCode -ne 0} }
else { $PR }
}