Auditing OneDrive file access is essential for security, compliance, and tracking user activities in an organization. Using PnP PowerShell, you can retrieve details on who accessed, modified, or shared files in OneDrive for Business.
This guide explains step-by-step how to audit OneDrive file access using PnP PowerShell.
Step 1: Install and Update PnP PowerShell
Ensure PnP PowerShell is installed. Open PowerShell as Administrator and run:
Install-Module -Name PnP.PowerShell -Force -AllowClobber
To update the module:
Update-Module -Name PnP.PowerShell
Verify the installation:
Get-Module -Name PnP.PowerShell -ListAvailable
Step 2: Connect to SharePoint Online Admin Center
To access OneDrive data, connect to SharePoint Online:
$adminUrl = "https://yourtenant-admin.sharepoint.com"
Connect-PnPOnline -Url $adminUrl -Scopes "Sites.FullControl.All" -Interactive
For App-based authentication, use:
$clientId = "your-client-id"
$tenantId = "your-tenant-id"
$clientSecret = "your-client-secret"
Connect-PnPOnline -Url $adminUrl -ClientId $clientId -ClientSecret $clientSecret -Tenant $tenantId
Step 3: Retrieve OneDrive Sites
To list all OneDrive sites in the organization:
$oneDriveSites = Get-PnPTenantSite -IncludeOneDriveSites | Where-Object { $_.Url -like "*-my.sharepoint.com/personal/*" }
$oneDriveSites | Select-Object Url, Owner, StorageUsageCurrent, StorageQuota | Format-Table -AutoSize
This command lists all OneDrive sites with their URL, owner, and storage details.
Step 4: Retrieve File Access Logs from OneDrive
To track file access events, use the Audit Log Search feature in Microsoft 365:
$startDate = (Get-Date).AddDays(-7).ToString("yyyy-MM-dd")
$endDate = (Get-Date).ToString("yyyy-MM-dd")
Search-UnifiedAuditLog -StartDate $startDate -EndDate $endDate -RecordType SharePointFileOperation -Operations "FileAccessed", "FileDownloaded" -ResultSize 5000
This script retrieves file access and download events from OneDrive.
Step 5: Export File Access Logs to CSV
To save the audit log as a CSV file:
$logPath = "C:\Reports\OneDrive_Audit_Report.csv"
Search-UnifiedAuditLog -StartDate $startDate -EndDate $endDate -RecordType SharePointFileOperation -Operations "FileAccessed", "FileDownloaded" -ResultSize 5000 | Export-Csv -Path $logPath -NoTypeInformation
Write-Host "OneDrive File Access Report saved to $logPath"
Step 6: Automate the Audit Process
1. Open Task Scheduler
- Click Start, search for Task Scheduler, and open it.
- Click Create Basic Task.
- Name it “OneDrive Audit Report”.
2. Set Trigger
- Choose Daily or any required frequency.
- Set the execution time.
3. Set Action
- Select Start a Program.
- In Program/Script, enter:
powershell.exe
- In Arguments, enter:
-File "C:\Scripts\OneDriveAuditReport.ps1"
- Click Finish.
This will automate the OneDrive audit process.
Step 7: Review the Report
To check the generated report:
Import-Csv -Path "C:\Reports\OneDrive_Audit_Report.csv" | Format-Table -AutoSize