Purview UAL & Parsing · T1530 / Collection

Search-UnifiedAuditLog PowerShell Export Guide for Incident Response

Direct Answer (Key Forensic Takeaway)

To export complete Microsoft 365 audit logs without silent truncation, invoke Search-UnifiedAuditLog with -SessionCommand ReturnLargeSet, a unique -SessionId GUID per time slice, and -ResultSize 5000 inside a loop until zero rows return. Always subdivide StartDate and EndDate intervals if ResultCount approaches 50,000—the hard per-session limit.

Why This Artifact Matters in M365 Incident Response

During an active Business Email Compromise or SharePoint data exfiltration incident, calling Search-UnifiedAuditLog with default parameters is one of the fastest ways to miss critical attacker evidence. Without explicit pagination flags, Exchange Online returns at most 100 records and silently drops every earlier or later event in that window.

Even worse, Exchange Online enforces strict throttling and a hard 50,000-record cap per ReturnLargeSet session. Understanding how SessionId cursors, UTC date boundaries, and adaptive interval slicing work guarantees your incident response team captures a forensically complete timeline.

Search-UnifiedAuditLog supports two session commands: ReturnNextPreviewPage and ReturnLargeSet. While ReturnNextPreviewPage sorts sequentially, it caps at 5,000 total records and can skip rows under concurrent cloud writes. ReturnLargeSet unlocks up to 50,000 records per SessionId by paging unordered shards from Exchange Online search indexes—meaning you must sort the final CSV chronologically by AuditData.CreationTime.

In medium to large tenants (1,000+ users), running a blanket 30-day tenant query easily exceeds 50,000 SharePoint FileAccessed or Exchange MailItemsAccessed events within hours. Always scope incident exports first by suspected -UserIds or high-signal -RecordType filters, and check the ResultCount property on the very first batch returned.

1. RAW TELEMETRY Purview UAL & Parsing T1530 / Collection 2. CLIENT-SIDE PARSE AuditVane Engine Search-UnifiedAuditLog export 0 Bytes Uploaded 3. SOC OUTCOME Scoped Containment IOCs · CSV · KQL
Local browser DFIR workflow for Search-UnifiedAuditLog export (T1530 / Collection)
AdSense-Ready In-Article Placement

Real-World Incident Walkthrough

An IR team responds to a suspected compromised HR account at a 3,500-employee firm. A junior admin runs a quick Search-UnifiedAuditLog query covering 14 days across the entire tenant without pagination, sees 100 rows, and concludes no InboxRule was created.

A senior responder re-runs the collection scoped directly to -UserIds hr.lead@company.com with ReturnLargeSet and -ResultSize 5000, recovering 3,840 events—followed by a tenant-wide RecordType 1 (ExchangeAdmin) and RecordType 8 (AzureActiveDirectory) sweep split into 12-hour slices. Dropping all resulting CSVs into AuditVane instantly orders every slice chronologically and flags an UpdateInboxRules event hidden in the previously truncated batch.

Forensic Telemetry Fields & High-Signal Indicators

Telemetry Field / Pattern Meaning in M365 / Entra High-Signal Threat Indicator
-SessionCommand ReturnLargeSetEnables full paged retrieval up to 50,000 eventsOmitting it caps output to 100–5,000 rows
-ResultSize 5000Maximum page size per PowerShell round-tripReduces API calls and throttling risk vs. default 100
-SessionId <GUID>Tracks server-side search cursor across loop iterationsMust be fresh GUID per time window/query
ResultIndex / ResultCountCurrent page offset and estimated total matching eventsIf ResultCount == 50000, slice time range smaller
-FormattedApplies human formatting (do NOT use for exports)Can alter AuditData JSON—omit for raw exports
-RecordType / -OperationsServer-side filter shrinking massive tenant pullsIdeal for targeted ExchangeAdmin or OAuth sweeps

Purview Extraction Methods Compared

MethodMax Rows per JobBest Use Case in DFIR
Purview Audit Web UI50,000 rows per search jobAd-hoc single-user review when UI export suffices
Search-UnifiedAuditLog (No Session)100 rows default (5,000 max)Quick smoke check only—never use for evidence
Search-UnifiedAuditLog (ReturnLargeSet)50,000 per SessionId (loopable by time slice)Fastest scriptable PowerShell export per user/window
Microsoft Graph auditLogQuery APIMillions of rows (async paged job)Large multi-week full-tenant forensic acquisitions

Sample Metadata Columns Returned by Search-UnifiedAuditLog

{
  "RecordType": 2,
  "CreationDate": "2026-12-01T08:16:40Z",
  "UserIds": "finance.director@contoso-demo.invalid",
  "Operations": "MailItemsAccessed",
  "ResultIndex": 4995,
  "ResultCount": 14820,
  "AuditData": "{...escaped JSON string...}"
}

Pay close attention to ResultIndex and ResultCount on every returned batch object. When ResultCount is 14,820 (safely under 50,000), looping ReturnLargeSet with the same SessionId retrieves all 14,820 records cleanly across three pages of 5,000.

If ResultCount ever reads 50,000, Exchange Online hit its ceiling and discarded everything beyond 50,000—making narrower time slices mandatory.

Production-Ready Paginated Search-UnifiedAuditLog Export Script

Connect-ExchangeOnline -ShowBanner:$false
$start = (Get-Date).ToUniversalTime().AddDays(-14)
$end   = (Get-Date).ToUniversalTime()
$sid   = [guid]::NewGuid().ToString()
$all   = [System.Collections.Generic.List[object]]::new()
do {
  $batch = Search-UnifiedAuditLog -StartDate $start -EndDate $end -UserIds "victim@domain.com" -SessionId $sid -SessionCommand ReturnLargeSet -ResultSize 5000
  if ($batch) {
    if ($all.Count -eq 0 -and $batch[0].ResultCount -ge 50000) { Write-Warning "Hit 50,000 ceiling! Narrow time slice." }
    $all.AddRange($batch)
  }
} while ($batch.Count -gt 0)
$all | Export-Csv .\Victim_UAL_14d.csv -NoTypeInformation -Encoding utf8

Sample Console Progress & Verification Check

WARNING: (only shown if ResultCount >= 50000)
Total rows exported: 14,820 | Unique RecordIds: 14,820
Ready to drop Victim_UAL_14d.csv into AuditVane.

Step-by-Step Triage, Containment & Verification

  1. Install and connect with ExchangeOnlineManagement v3+ using an account assigned View-Only Audit Logs or Audit Logs.
  2. Always convert StartDate and EndDate explicitly to UTC (.ToUniversalTime()) so local workstation timezones never skew boundaries.
  3. Use a fresh [guid]::NewGuid().ToString() for every distinct query or time chunk.
  4. Check $batch[0].ResultCount immediately; if it equals 50,000, halve your time window and re-run.
  5. Export with -NoTypeInformation -Encoding utf8 and deduplicate on Identity/RecordId if overlapping slices were used.
  6. Drop the exported CSV files into AuditVane to sort chronologically, flatten AuditData, and evaluate all 12 BEC/AiTM rules.

How to Verify Containment Completed Cleanly

  • Verify exported CSV contains a RecordId/Identity count matching ResultCount from the first batch.
  • Check earliest and latest AuditData.CreationTime values in AuditVane to confirm full date coverage without mid-day drops.
  • Store raw unmodified CSVs in read-only forensic evidence storage before any analyst filtering.

Analyst Blind Spots, Licensing Quirks & False Positives

Reusing the same -SessionId GUID after changing -StartDate or -UserIds causes Exchange Online to silently return stale cached results from the previous query. Always generate a brand-new GUID for every query iteration.

Do not omit -NoTypeInformation in Windows PowerShell 5.1; otherwise Export-Csv writes a #TYPE header on line 1 that breaks standard CSV parsers.

Frequently Asked Questions

Why did my Search-UnifiedAuditLog loop stop at 50,000 rows?

Exchange Online enforces a hard 50,000-record ceiling per SessionId. Reduce StartDate/EndDate into 2-hour or 6-hour increments or filter specifically by UserIds or Operations.

Should I use Microsoft Graph auditLogQuery instead of PowerShell?

Yes, for huge enterprise-wide pulls exceeding 50,000 rows per hour, the Microsoft Graph security/auditLog/queries async API avoids the 50k session ceiling—while Search-UnifiedAuditLog remains fastest for targeted user investigations.

Why are ReturnLargeSet rows out of chronological order?

ReturnLargeSet streams pages directly from multiple backend search partitions for speed. AuditVane automatically re-sorts all rows ascending by UTC CreationTime on import.

Can AuditVane handle multiple time-sliced CSV exports at once?

Yes—drag all hourly or daily CSV files onto AuditVane together to build one unified timeline.

Related Forensics Guides