Entra / Microsoft 365 · Compliance & audit
Get audit records for tagged SPO files
Report audit records generated when SharePoint Online files are tagged with a retention label.
Connect & set up
Run these once per session. All scopes are read-only unless the script makes changes.
# Review required modules and connection steps before running.# Connect to Microsoft Graph or Exchange Online as needed for this script.
Run it
The main script. Copy it, or download the .ps1 and run it from your console.
param([string] $AppId = "",[int] $LookbackDays = 3,[string] $StartDate = (Get-Date).AddDays(-$LookbackDays); $EndDate = (Get-Date).AddDays(1),[string] $EndDate = (Get-Date))[array]$Modules = Get-Module | Select-Object -ExpandProperty NameIf ("ExchangeOnlineManagement" -notin $Modules) {Write-Host "Please connect to the Exchange Online Management module and then restart the script"break}# Start and end date for the audit scan. By default, we look for 3 days, but you can choose any value you like up to 365 (assuming Office 365 E5)# AppId for the Microsoft Graph PowerShell SDK# Find the audit records[array]$Records = Search-UnifiedAuditLog -Operations TagApplied -StartDate $StartDate -EndDate $EndDate -Formatted -ResultSize 5000 -SessionCommand ReturnLargeSetIf (!$Records) {Write-Host "No audit records found - exiting!"; break}# Sort to remove duplicate audit records$Records = $Records | Sort-Object Identity -Unique$TaggedFilesReport = [System.Collections.Generic.List[Object]]::new()ForEach ($Rec in $Records) {$AuditData = $Rec.AuditData | ConvertFrom-JsonIf ($AuditData.AppAccessContext.ClientAppId -eq $AppId) {# Audit record is for a SharePoint Online file tagged with a retention label by the Microsoft Graph PowerShell$AuditReportLine = [PSCustomObject] @{Workload = $AuditData.WorkloadFile = $AuditData.DestinationFileName"Retention Label" = $AuditData.DestinationLabel"Tagging Date" = Get-Date($AuditData.CreationTime) -format 'dd-MMM-yyyy HH:mm:ss'Site = $AuditData.SiteURLFullURL = $AuditData.ObjectId}$TaggedFilesReport.Add($AuditReportLine)}}Write-Host ("{0} audit records found for files tagged with a retention label by the Microsoft Graph PowerShell SDK" -f $TaggedFilesReport.Count)$TaggedFilesReport = $TaggedFilesReport | Sort-Object {$_."Tagging Date" -as [datetime]} -Descending$TaggedFilesReport | Out-GridView -Title 'SharePoint Files tagged by Graph SDK script'
Parameters
ParameterDefaultNotes
-AppId""Application (client) ID for the app registration used to connect.-LookbackDays3Number of days to search the audit log for retention label tagging events.-StartDate(Get-Date).AddDays(-3); $EndDate = (Get-Date).AddDays(1)Start of the reporting window.-EndDate(Get-Date)End of the reporting window.Attribution
Author
Office365itpros