# Export-AuditLogs.ps1 # Export M365 Unified Audit Logs via Graph API # Usage: .\Export-AuditLogs.ps1 -StartDate "2024-01-01" -EndDate "2024-01-31" # Requires: Microsoft.Graph module (Install-Module Microsoft.Graph) param( [Parameter(Mandatory=$true)] [datetime]$StartDate, [Parameter(Mandatory=$true)] [datetime]$EndDate, [string]$OutputPath = ".\AuditLogs.csv", [string[]]$Operations, [switch]$AuditSharePoint, [switch]$AuditExchange, [switch]$AuditAzureAD, [switch]$AuditGeneral ) # Check for Microsoft.Graph module if (-not (Get-Module -ListAvailable -Name Microsoft.Graph)) { Write-Host "Microsoft.Graph module not found. Installing..." -ForegroundColor Yellow Install-Module Microsoft.Graph -Scope CurrentUser -Force } Write-Host "Connecting to Microsoft Graph..." -ForegroundColor Cyan Write-Host "Date range: $StartDate to $EndDate" -ForegroundColor Cyan Write-Host "" # Connect with appropriate scopes $Scopes = @("AuditLog.Read.All") if ($AuditSharePoint -or $AuditExchange) { $Scopes += "Sites.Read.All" } try { Connect-MgGraph -Scopes $Scopes Write-Host "Connected successfully!" -ForegroundColor Green } catch { Write-Host "Failed to connect: $_" -ForegroundColor Red exit 1 } # Build search parameters $SearchParams = @{ StartDateTime = $StartDate EndDateTime = $EndDate } # Filter by operations if specified if ($Operations) { $SearchParams.Operations = $Operations } # Audit log activities $Activities = @() if ($AuditGeneral -or -not ($AuditSharePoint -or $AuditExchange -or $AuditAzureAD)) { $Activities += "General" } if ($AuditAzureAD) { $Activities += "AzureAD" } if ($AuditSharePoint) { $Activities += "SharePoint" } if ($AuditExchange) { $Activities += "Exchange" } Write-Host "Searching audit logs..." -ForegroundColor Cyan $AllResults = @() $Page = 0 do { $Page++ Write-Host "Fetching page $Page..." -ForegroundColor Gray try { $Results = Search-MgAuditLogDirectoryActivity @SearchParams -All if ($Results) { foreach ($Result in $Results) { $AllResults += [PSCustomObject]@{ CreationTime = $Result.CreationTime Id = $Result.Id Operation = $Result.Operation Workload = $Result.Workload UserId = $Result.UserId ClientIP = $Result.ClientIP Result = $Result.Result } } } $Results = $null } catch { Write-Host "Error on page $Page : $_" -ForegroundColor Red break } } while ($Results) Write-Host "" Write-Host "Found $($AllResults.Count) audit log entries" -ForegroundColor Green if ($AllResults.Count -gt 0) { $AllResults | Export-Csv -Path $OutputPath -NoTypeInformation Write-Host "Exported to: $OutputPath" -ForegroundColor Green } Disconnect-MgGraph