Export M365 Sign-in Logs (30 Days)

View Categories

Export M365 Sign-in Logs (30 Days)

< 1 min read

Easiest method is to open Powershell ISE and copy the script below

🔷
Export30DaySignIns.ps1
# Check and install Microsoft Graph module if not present
Write-Host "Checking Microsoft Graph module..." -ForegroundColor Yellow
if (-not (Get-Module -ListAvailable -Name Microsoft.Graph)) {
    Write-Host "Installing Microsoft Graph module..." -ForegroundColor Cyan
    Install-Module Microsoft.Graph -Scope CurrentUser -Force
    Write-Host "Microsoft Graph module installed successfully." -ForegroundColor Green
} else {
    Write-Host "Microsoft Graph module already installed." -ForegroundColor Green
}

# Import the module
Write-Host "Importing Microsoft Graph module..." -ForegroundColor Yellow
Import-Module Microsoft.Graph
Write-Host "Module imported successfully." -ForegroundColor Green

# Connect to Microsoft Graph (requires admin consent)
Write-Host "Connecting to Microsoft Graph..." -ForegroundColor Yellow
Connect-MgGraph -Scopes "AuditLog.Read.All" -NoWelcome
Write-Host "Connected to Microsoft Graph." -ForegroundColor Green

# Verify connection
$context = Get-MgContext
if (-not $context) {
    Write-Host "Failed to connect to Microsoft Graph. Please check credentials." -ForegroundColor Red
    exit
}

# Define date range (last 30 days)
$startDate = (Get-Date).AddDays(-30).ToString("yyyy-MM-ddTHH:mm:ssZ")
$endDate = (Get-Date).ToString("yyyy-MM-ddTHH:mm:ssZ")

Write-Host "Exporting sign-in logs from $startDate to $endDate..." -ForegroundColor Cyan

# Initialize array for logs
$signInLogs = @()

# Get logs in pages
Write-Host "Retrieving sign-in logs. This may take a few minutes..." -ForegroundColor Yellow
$logs = Get-MgAuditLogSignIn -Filter "createdDateTime ge $startDate and createdDateTime le $endDate" -All

# Add logs to array
$signInLogs += $logs
Write-Host "Retrieved $($signInLogs.Count) sign-in records." -ForegroundColor Green

# Export to CSV
$outputFile = "$env:USERPROFILE\Desktop\M365_SignInLogs_Last30Days.csv"
Write-Host "Exporting logs to $outputFile..." -ForegroundColor Cyan

$signInLogs | Select-Object `
    userDisplayName,
    userPrincipalName,
    appDisplayName,
    ipAddress,
    @{Name='City';Expression={$_.Location.City}},
    @{Name='State';Expression={$_.Location.State}},
    @{Name='Country';Expression={$_.Location.CountryOrRegion}},
    @{Name='Status';Expression={$_.Status.ErrorCode}},
    @{Name='FailureReason';Expression={$_.Status.FailureReason}},
    @{Name='AdditionalDetails';Expression={$_.Status.AdditionalDetails}},
    createdDateTime |
Export-Csv -Path $outputFile -NoTypeInformation



Write-Host "Export completed successfully! File saved to $outputFile" -ForegroundColor Green
Read-Host $view = "Open interative view of logs? Enter Y for Yes, N for No (Default No)"
if ($view -eq "Y" -or "y")
{$signInLogs | Out-GridView}
else {exit}