Skip to content

Instantly share code, notes, and snippets.

@braitom
Last active August 30, 2018 06:38
Show Gist options
  • Save braitom/808efe6be9540ccce45079e54c9d7715 to your computer and use it in GitHub Desktop.
Save braitom/808efe6be9540ccce45079e54c9d7715 to your computer and use it in GitHub Desktop.
Export O365 Auditlog
$UserCredential = Get-Credential
$ProxyOptions = New-PSSessionOption -ProxyAccessType "IEConfig"
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session
$scriptStart=(get-date)
$sessionName = "auditlog"
$results = @()
$i = 0 # Loop counter
Do {
$currentResults = Search-UnifiedAuditLog -StartDate 08/01/2018 -EndDate 08/30/2018 -UserIds "userA,userB,userC" -SessionId $sessionName -SessionCommand ReturnLargeSet -ResultSize 5000
if ($currentResults.Count -gt 0) {
Write-Host (" Finished {3} search #{1}, {2} records: {0} min" -f [math]::Round((New-TimeSpan -Start $scriptStart).TotalMinutes,4), $i, $currentResults.Count, $user.UserPrincipalName)
$results += $currentResults
if ($currentResults.Count -lt 5000) {
$currentResults = @()
} else {
$i++
}
}
} Until ($currentResults.Count -eq 0)
Foreach ($log in $results) {
$data = (ConvertFrom-Json $log.AuditData)
$output = $log.CreationDate.ToString() + "," + $log.UserIds + "," + $log.RecordType + "," + $log.Operations + "," + $data.ClientIP + "," + $data.ObjectId
Add-Content -path C:\Temp\auditlog.csv $output -Encoding String
}
Remove-PSSession $Session