#region Functions function get-oAuthAccessToken() { # Retrieve Oauth 2 access token $body = @{grant_type="client_credentials";resource=$resource;client_id=$clientID;client_secret=$clientSecret} $oauthToken = Invoke-RestMethod -Method Post -Uri $loginURL/$tenantdomain/oauth2/token?api-version=1.0 -Body $body return $oauthToken } #endregion $runtime = Get-Date $ClientID = "<<>>" $ClientSecret = "<<>>" $loginURL = "https://login.windows.net" $tenantdomain = "<<>>" $TenantGUID = "<<>>" $resource = "https://manage.office.com" $offSetDays = 1 $AuditSearchString = "https://wharfconsulting.sharepoint.com/_catalogs/masterpage/display templates*" $extractDate = $runtime.AddDays(-$offSetDays) $processDate = $extractDate.toString("yyyy-MM-dd") $auditSuffix = "?contentType=Audit.SharePoint&startTime=" + $processDate + "T00:00:00Z&endTime=" + $processDate + "T23:59:59Z" #Setup containers $blobs = @() $unstructuredAuditData = @() $totalRecordCount = 0 $filteredCount = 0 #Get an oAuth token $oAuth = get-oAuthAccessToken #Create the header params for this token. $headerParams = @{'Authorization'="$($oauth.token_type) $($oauth.access_token)"} do { $rawBlob = Invoke-WebRequest -Headers $headerParams -Uri "https://manage.office.com/api/v1.0/$tenantGUID/activity/feed/subscriptions/content$auditSuffix" write-host "Package length:" $rawBlob.Content.Length foreach ($blobPackage in $rawBlob) { $blobs += $blobPackage.Content | ConvertFrom-Json } } while ( $rawBlob.Headers.NextPageUri) $blobTotal = $blobs.Count write-host "$blobTotal packages for processing." #Now process the blob data to retrieve the actual audit data. foreach ($blobDataSource in $blobs) { #Note, you may need to keep an eye on your oAuth token expiry here! #You can do this by comparing the UnixDate in $oAuth.expires_on #And refreshing the token if there's less than 5 minutes to go. $thisBlobdata = Invoke-WebRequest -Headers $headerParams -Uri $blobDataSource.contentUri $blobDataJSON = $thisBlobdata | convertfrom-json $totalRecordCount += $blobDataJSON.Count $filteredBlobData = $null $filteredBlobData = $blobDataJSON | ?{$_.ObjectId.tolower() -like $AuditSearchString} foreach ($filteredBlob in $filteredBlobData) { $unstructuredAuditData += $filteredBlobData $filteredCount++ } } write-host "$totalRecordCount audit records processed" write-host "$filteredCount audit records collated" $sortedData = $unstructuredAuditData | Sort-Object -Property CreationTime $sortedData | export-csv -Path $"ExtractedAuditData.csv" -NoTypeInformation