Skip to content

Instantly share code, notes, and snippets.

@bachoang
Last active May 8, 2019 04:56
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
# This script will require the Web Application and permissions setup in Azure Active Directory
$ClientID = "client id" # Should be a ~35 character string insert your info here
$ClientSecret = "secret” # Should be a ~44 character string insert your info here
$loginURL = "https://login.microsoftonline.com"
$tenantdomain = "<tenantname>.onmicrosoft.com" # For example, contoso.onmicrosoft.com
$resource = "https://graph.microsoft.com"
# Get an Oauth 2 access token based on client id, secret and tenant domain
$body = @{grant_type="client_credentials";resource=$resource;client_id=$ClientID;client_secret=$ClientSecret}
$oauth = Invoke-RestMethod -Method Post -Uri $loginURL/$tenantdomain/oauth2/token -Body $body
$2daysago = "{0:s}" -f (get-date).AddDays(-2) + "Z"
# or, AddMinutes(-5)
Write-Output $2daysago
if ($oauth.access_token -ne $null) {
$headerParams = @{'Authorization'="$($oauth.token_type) $($oauth.access_token)"}
$url = "https://graph.microsoft.com/beta/auditLogs/directoryAudits?\`$filter=eventTime gt $2daysago"
$myReport = (Invoke-WebRequest -UseBasicParsing -Headers $headerParams -Uri $url)
foreach ($event in ($myReport.Content | ConvertFrom-Json).value) {
Write-Output ($event | ConvertTo-Json)
}
$myReport.Content | Out-File -FilePath "C:\Path to file\auditEvents.json" -Force
} else {
Write-Host "ERROR: No Access Token"
}
@bachoang
Copy link
Author

bachoang commented May 8, 2019

This PS script uses MS Graph endpoint to get the Azure AD Audit Events.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment