How to Report Per-User SharePoint Online Activity

What Did Users Do with SharePoint Documents?

A question popped up in an online group: How can I create a report for each user detailing the interaction with documents stored in SharePoint Online libraries? The answer seems straightforward: search the Office 365 audit log for SharePoint document operations and create a report from the events found, outputting it in CSV or HTML format. Chapter 21 of the Office 365 for IT Pros eBook includes many examples of how to extract information from the audit log that could be used as the basis for a solution. The post covering how to answer the question of who updated a document is also helpful.

Often the reports generated from the audit log cover actions taken by multiple users. In this case, the request is to generate a report on a per-user basis. Possibly the desire is to email the report to the user, or maybe the feeling is that it is easier to review access to sites and documents on a personal level.

Generating a List of Users

The first thing to resolve is what’s intended by “user”? We need to know this to generate the reports. A user could mean:

  • Someone with an account in a tenant.
  • Both tenant and guest users.
  • Just guest users.

From a PowerShell perspective, you can generate a list of mailbox owners with Get-ExoMailbox (people with mailboxes are likely to have SharePoint Online licenses).

$Users = Get-ExoMailbox -RecipientTypeDetails UserMailbox -ResultSize Unlimited | Select UserPrincipalName,DisplayName

Alternatively, if you want to include guest accounts, you can create a list with Get-AzureADUser and include accounts of type Member (tenant account) and Guest.

$Users = Get-AzureADUser -All $True -Filter ("UserType eq 'Guest' or UserType eq 'Member'") | Select UserPrincipalName, DisplayName

You could filter the list further by removing tenant accounts who aren’t licensed for SharePoint Online. This is easy to do, but it’s probably not necessary because the report is generated from audit events that won’t exist unless an account is licensed.

Searching the Office 365 Audit Log

We’re going to search the Office 365 audit log for events generated by all users. The other search parameters needed are:

The events to look for: Depending on the applications used in a tenant, the audit log could include up to 1,500 different events. In this case, we want to know about events which manipulate documents stored in SharePoint or OneDrive for Business. Five events should suffice:

  • FileAccessed. A user opens a file but does not modify the content.
  • FileDownloaded. A user downloads a file to their workstation.
  • FileModified. A user updates the content of a file.
  • FileDeleted. A user deletes a file.
  • FileUploaded. A user uploads (creates) a new file.

Although you can input the events directly into the search command, it’s easier to declare the set of events in an array:

$Operations = @('FileAccessed', 'FileDownloaded', 'FileModified', 'FileDeleted', 'FileUploaded')

The start and end date for the search. SharePoint Online is a verbose application when it comes to the generation of audit log records. To make processing easier, restrict the date range as much as possible. You can go back 90 days for Office 365 E3 accounts and 365 days for Office 365 E5 accounts.

Handling Large Quantities of Audit Records

In large tenants, consider splitting the processing up over several batches as otherwise the script will likely take a long time to complete. The easiest way to do this is to amend the script to create a filtered set of users and use the filtered list as input to the audit log search. This example uses the Get-ExoMailbox cmdlet with a filter applied to the CustomAttribute1 property to find a set of users:

$Users = Get-ExoMailbox -Filter {CustomAttribute1 -eq "Sales"} | Select -ExpandProperty UserPrincipalName 
Search-UnifiedAuditLog -Operations $Operations -UserIds $Users -StartDate $StartDate -EndDate $EndDate -ResultSize 5000

The Search-UnifiedAuditLog cmdlet is restricted to returning a maximum of 5,000 audit records at one time. More records might exist, and in this case, you must run the cmdlet until all available data is retrieved. Search-UnifiedAuditLog supports the retrieval of large amounts of data (up to 50,000 records) by allowing you to declare a session identifier (a value to link calls together) together with the ReturnLargeSet parameter. The data is unsorted when fetched, so it must be sorted for reporting purposes. If more than 50,000 audit records are available, you’ll have to divide processing up across multiple runs.

Processing Audit Data

It’s possible to take the raw data from audit records and output the records to a CSV file. However, I like to process Office 365 audit records to make more sense of what they contain. In this case, the script does the following:

  • Format the timestamp so that it’s something like 4-May-2020 18:56.
  • Drop a bunch of unneeded audit records generated by SharePoint Online for access to different graphic elements used by pages, records for background processing (app@sharepoint), and records with blank user agent information.
  • Extract a human-friendly client identifier from the UserAgent property. For example, take a string like “Microsoft Office Word/16.0.12730.20144 (Windows/10.0; Desktop WOW64; en-IE; Desktop app; Microsoft Corporation/Surface Book 2)” and make it “Microsoft Word (desktop)” or “Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4121.0 Safari/537.36 Edg/84.0.495.2” and make it “Microsoft Edge” (yes, there is a misspelling in the information written into the audit log. The version information is also extracted.

The processed audit records go into a PowerShell list object. This is much more efficient than adding records to an array. And we can do some rudimentary processing to generate some insight into what’s happening. For example, what kind of file operations are performed:

$Report | Group Operation | Format-Table Name, Count   

Name           Count
----           -----
FileAccessed    3594
FileUploaded     341
FileModified    3186
FileDownloaded    86
FileDeleted      327

Or the people who are creating documents:

$Report | Group UPN | Sort Count -Descending | Format-Table Name, Count                     

Name                                                                           Count
----                                                                           -----                                                5669     690          374

Generating the Per-User Reports

To create a report for each active user, we can loop through the set of users we created beforehand and extract the records for the selected user and write them out to a CSV file:

$UserRecords = $Report | ? {$_.UPN -eq $U.UserPrincipalName} 
    If ($UserRecords) {  
       Write-Host "Writing out data for" $U.DisplayName
       $FileName = "c:\Temp\AuditHistory" + $U.UserPrincipalName + ".csv"
       $UserRecords | Export-CSV -NoTypeInformation $FileName }

Figure 1 shows what the contents of a CSV file looks like:

Example of a per-user report of SharePoint activity
Figure 1: Example of a per-user report of SharePoint activity

The per-user CSV files are created in the c:\temp\ directory (Figure 2), so it would be easy to find them and email them to the users… But that’s another day’s work.

Audit reports are available for access
Figure 2: Audit reports are available for access

In the meantime, the complete script containing everything described above is available for download from GitHub. Happy PowerShell!

6 Replies to “How to Report Per-User SharePoint Online Activity”

  1. Hi Tony, i am not able to run the script. First fails Can’t find Search-UnifiedAuditLog command. What are pre-reqs? If i import module ExchangeOnlineManagement -verbose i can view command import…

    1. Search-UnifiedAuditLog is part of the Exchange Online module. Once you have loaded that module into a session, you should be able to run the script.

  2. Hi Tony, Can reports automatically generate periodically(weekly or monthly) within SharePoint Online with sitecollection Admin access(tenant level is not provided).

  3. Forgive me first!
    I am new to PowerShell, and I wondering why there are no error logs in your sample scripts.
    How easy can I be able to modify your sample script to capture errors, in case a section fails to execute.

    1. Simple. We write scripts to illustrate how to solve problems. Given that organizations have their own way to create PowerShell scripts, including error handling, it’s up to you to take our sample code and adapt it for use in your environment.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.