How To Get Items Modified In The Last 24 Hours From A Site Collection
Hey guys! Ever needed to snag a report of all the items modified in your SharePoint site collection within the last 24 hours? It's a common task, and there are a couple of cool ways to tackle it. Let's dive into how you can do this using PowerShell, SSOM (Server Side Object Model), and PnP (Patterns and Practices) PowerShell. We'll explore the best approaches, whether through SPAudit or other methods. Buckle up; it’s going to be a fun ride!
Understanding the Challenge
Before we jump into the code, let’s chat a bit about the challenge. When you need to track changes in SharePoint, you're essentially looking at two main avenues: the SharePoint Audit Logs and querying the items directly for their modification timestamps. Each approach has its pros and cons, so choosing the right one depends on your specific needs and environment. Audit logs are great for compliance and historical tracking, providing a detailed record of who did what and when. However, they can be a bit cumbersome to work with and might require specific permissions. On the other hand, querying items directly is more straightforward for simple reports but might miss some actions that aren't reflected in item modifications, like permission changes or site-level activities. So, what’s the best way? Let’s break it down and see what works for you.
Why Track Modifications?
Tracking modifications is super important for several reasons. First off, security and compliance. Knowing who changed what and when can be crucial for maintaining a secure environment and meeting regulatory requirements. Think about it: if something goes wrong, you need to know who touched what last, right? Secondly, there's the content management aspect. Keeping an eye on changes helps ensure content stays up-to-date and accurate. Nobody wants outdated info floating around. And finally, it's about efficiency. Identifying frequently modified items can help you streamline workflows and improve collaboration. It’s all about making things smoother for everyone. So, armed with this info, let’s get into the nitty-gritty of how to actually pull this off.
Method 1: Leveraging PnP PowerShell
PnP PowerShell is like the Swiss Army knife for SharePoint admins. It’s packed with cmdlets that make complex tasks a breeze. Let’s use it to get those modified items. First, make sure you have the PnP PowerShell module installed. If not, just run Install-Module PnP.PowerShell -Scope CurrentUser
in your PowerShell console. Once that's done, you're ready to rock and roll. With PnP PowerShell, you can quickly connect to your SharePoint site, loop through the lists and libraries, and filter items modified within the last 24 hours. This method is fantastic because it’s clean, efficient, and relatively easy to understand, even if you're not a PowerShell guru. Plus, PnP PowerShell handles a lot of the heavy lifting, so you don’t have to write a ton of code. Let's check out the script.
The PnP PowerShell Script
# PnP PowerShell script to get items modified in the last 24 hours
# Site URL and credentials
$SiteURL = "https://yourtenant.sharepoint.com/sites/YourSite"
$Username = "[email protected]"
$Password = "YourPassword"
# Connect to SharePoint Online
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential -UserName $Username)
# Calculate the date 24 hours ago
$Last24Hours = (Get-Date).AddDays(-1)
# Array to store modified items
$ModifiedItems = @()
# Get all lists and libraries
$Lists = Get-PnPList -Includes Title
# Loop through each list
foreach ($List in $Lists) {
Write-Host "Checking list: $($List.Title)" -ForegroundColor Green
# Get items modified in the last 24 hours
$Items = Get-PnPListItem -List $List -Query "<View><Query><Where><Geq><FieldRef Name='Modified' /><Value Type='DateTime'>$($Last24Hours.ToString('yyyy-MM-ddTHH:mm:ssZ'))</Value></Geq></Where></Query></View>" -Fields "Title", "Modified", "Editor"
# Add modified items to the array
foreach ($Item in $Items) {
$ModifiedItems += [PSCustomObject]@{
ListTitle = $List.Title
ItemTitle = $Item.Title
Modified = $Item.Modified
Editor = $Item.Editor
}
}
}
# Export the results to a CSV file
$ModifiedItems | Export-Csv -Path "./ModifiedItems.csv" -NoTypeInformation
# Disconnect from SharePoint Online
Disconnect-PnPOnline
Write-Host "\nReport generated successfully! Check ModifiedItems.csv" -ForegroundColor Yellow
Walking Through the Script
Okay, let’s break this down piece by piece. First, we define the site URL, username, and password. Make sure to replace these with your actual credentials and site URL. You don't want to run this with the placeholder info, trust me! Next, we use Connect-PnPOnline
to establish a connection to your SharePoint site. This is where the magic starts. Then, we calculate the date and time 24 hours ago using (Get-Date).AddDays(-1)
. This gives us the starting point for our search. We initialize an empty array, $ModifiedItems
, to store the items we find. Think of it as our digital notepad for keeping track of changes. The script then gets all lists and libraries in the site using Get-PnPList
and loops through each one. Inside the loop, we use Get-PnPListItem
with a CAML query to filter items modified within the last 24 hours. CAML queries might sound intimidating, but they're just a way to tell SharePoint exactly what you’re looking for. We specify that we want items where the Modified
field is greater than or equal to our $Last24Hours
variable. For each modified item, we create a custom object with the list title, item title, modification date, and editor, then add it to our $ModifiedItems
array. Finally, we export the results to a CSV file using Export-Csv
, making it easy to open and review in Excel. And, of course, we disconnect from SharePoint using Disconnect-PnPOnline
. It’s like saying goodbye after a great visit. This approach is super efficient and gives you a clear, exportable report of all the changes.
Method 2: Using SharePoint Server Object Model (SSOM)
For those of you running on-premises SharePoint, SSOM is your best friend. SSOM allows you to interact directly with the SharePoint object model on the server. This approach is powerful but requires you to run the script on a SharePoint server or have the SharePoint client-side libraries installed. So, if you’re not familiar with SSOM, it might sound a bit technical, but don't worry, we'll walk through it step by step. Using SSOM, you can access the SharePoint object model directly, which gives you a ton of flexibility and control. You can dive deep into the SharePoint data structures and pull out exactly what you need. Let's see how we can use it to get those modified items.
The SSOM PowerShell Script
# SSOM PowerShell script to get items modified in the last 24 hours
# SharePoint site URL
$SiteURL = "http://yoursharepointsite"
# Calculate the date 24 hours ago
$Last24Hours = (Get-Date).AddDays(-1)
# Array to store modified items
$ModifiedItems = @()
# Load SharePoint assemblies
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
# Get the site
$Site = Get-SPSite $SiteURL
# Loop through each web in the site collection
foreach ($Web in $Site.AllWebs) {
Write-Host "Checking web: $($Web.Title)" -ForegroundColor Green
# Loop through each list in the web
foreach ($List in $Web.Lists) {
# Skip hidden lists
if ($List.Hidden -eq $false) {
# Construct CAML query
$CamlQuery = New-Object Microsoft.SharePoint.SPQuery
$CamlQuery.Query = "<Where><Geq><FieldRef Name='Modified' /><Value Type='DateTime'>$($Last24Hours.ToString('yyyy-MM-ddTHH:mm:ssZ'))</Value></Geq></Where>"
$CamlQuery.ViewFields = "<FieldRef Name='Title' /><FieldRef Name='Modified' /><FieldRef Name='Editor' />"
# Get list items
$ListItems = $List.GetItems($CamlQuery)
# Add modified items to the array
foreach ($Item in $ListItems) {
$ModifiedItems += [PSCustomObject]@{
WebTitle = $Web.Title
ListTitle = $List.Title
ItemTitle = $Item["Title"] # Access by property name
Modified = $Item["Modified"] # Access by property name
Editor = $Item["Editor"] # Access by property name
}
}
}
}
# Dispose the web object
$Web.Dispose()
}
# Dispose the site object
$Site.Dispose()
# Export the results to a CSV file
$ModifiedItems | Export-Csv -Path "./ModifiedItemsSSOM.csv" -NoTypeInformation
Write-Host "\nReport generated successfully! Check ModifiedItemsSSOM.csv" -ForegroundColor Yellow
Decoding the SSOM Script
Alright, let’s dissect this SSOM script. First up, we declare the site URL and calculate the date 24 hours ago, just like in the PnP version. We also set up our trusty $ModifiedItems
array to store the results. Then, we load the SharePoint PowerShell snap-in using Add-PSSnapin Microsoft.SharePoint.PowerShell
. This is crucial because it gives us access to the SharePoint cmdlets. Next, we get the site using Get-SPSite
. This is our entry point to the SharePoint world. The script then loops through each web in the site collection using $Site.AllWebs
. Inside this loop, we have another loop that goes through each list in the web. We skip hidden lists using a simple if
statement, because nobody cares about those, right? We construct a CAML query to filter items modified within the last 24 hours. Notice how we’re using the same CAML query structure as before? Consistency is key! We set the ViewFields
property to specify which fields we want to retrieve: Title
, Modified
, and Editor
. This helps us keep the data lean and mean. We get the list items using $List.GetItems($CamlQuery)
and then loop through each item. For each modified item, we create a custom object and add it to our $ModifiedItems
array. We access item properties by their names, like $Item["Title"]
. Finally, and this is super important, we dispose of the web and site objects using $Web.Dispose()
and $Site.Dispose()
. This releases the resources and prevents memory leaks. Trust me, you don't want memory leaks! We export the results to a CSV file using Export-Csv
, just like before. This approach might seem a bit more involved than PnP, but it gives you direct access to the SharePoint object model, which can be incredibly powerful for complex tasks.
Method 3: SharePoint Audit Logs
Now, let's talk about the SharePoint Audit Logs. This is like the black box recorder for your SharePoint site. It tracks all sorts of actions, including file modifications, access events, and more. Using audit logs is great for compliance and getting a comprehensive view of what’s happening in your site. However, it can be a bit more complex to work with compared to querying items directly. You'll need the right permissions to access the audit logs, and the data can be quite verbose, so filtering and parsing are key. But if you need a full picture of site activity, this is the way to go. Let's see how we can leverage audit logs to find those modified items.
Diving into Audit Logs
To access the SharePoint Audit Logs, you'll typically use the Search-UnifiedAuditLog
cmdlet in PowerShell. This cmdlet is part of the Exchange Online PowerShell module, so make sure you have that installed. The audit logs contain a ton of information, so you'll need to filter it down to the events you care about. In our case, we're looking for file modification events within the last 24 hours. This involves specifying the correct operation types and date ranges in your search query. Once you've pulled the audit log entries, you'll need to parse the results to extract the relevant details, such as the file name, user, and modification timestamp. This might involve some JSON parsing and data manipulation, but don't worry, we'll walk through it.
The Audit Log PowerShell Script
# PowerShell script to get items modified in the last 24 hours using Audit Logs
# Connect to Exchange Online
Connect-ExchangeOnline -UserPrincipalName "[email protected]" # Use the correct UPN for your admin account
# Calculate the date 24 hours ago
$Last24Hours = (Get-Date).AddDays(-1)
# Search the Unified Audit Log for FileModified events
$AuditLogs = Search-UnifiedAuditLog -StartDate $Last24Hours -EndDate (Get-Date) -Operations FileModified -ResultSize 5000
# Array to store modified items
$ModifiedItems = @()
# Check if audit logs were found
if ($AuditLogs) {
# Loop through each audit log entry
foreach ($Log in $AuditLogs) {
# Convert the AuditData property from JSON to a PowerShell object
$AuditData = ConvertFrom-Json $Log.AuditData
# Extract relevant information
$ItemTitle = $AuditData.SourceFileName # Get file name from AuditData
$SiteURL = $AuditData.SourceRelativeURL
$User = $Log.UserId # Get the user who modified the file
$ModifiedTime = $Log.CreationTime
# Add modified item to the array
$ModifiedItems += [PSCustomObject]@{
ItemTitle = $ItemTitle
SiteURL = $SiteURL
User = $User
ModifiedTime = $ModifiedTime
}
}
}
else {
Write-Warning "No audit logs found for FileModified events in the last 24 hours."
}
# Export the results to a CSV file
$ModifiedItems | Export-Csv -Path "./ModifiedItemsAuditLogs.csv" -NoTypeInformation
# Disconnect from Exchange Online
Disconnect-ExchangeOnline
Write-Host "\nReport generated successfully! Check ModifiedItemsAuditLogs.csv" -ForegroundColor Yellow
Unpacking the Audit Log Script
Okay, let’s break down this audit log script. First things first, we need to connect to Exchange Online using Connect-ExchangeOnline
. This is because the Search-UnifiedAuditLog
cmdlet lives there. You'll need to provide the UPN (User Principal Name) of your admin account. Make sure it’s the right one! We calculate the date 24 hours ago, just like in the previous scripts. Then, we use Search-UnifiedAuditLog
to search the audit logs. We specify the StartDate
, EndDate
, and Operations
parameters. We’re looking for FileModified
events, which cover file modifications. We also set the ResultSize
to 5000 to make sure we grab enough logs. We initialize our $ModifiedItems
array to store the results. We check if any audit logs were found using a simple if
statement. If we find logs, we loop through each entry. The key part here is the ConvertFrom-Json $Log.AuditData
. The AuditData
property is a JSON string, so we need to convert it into a PowerShell object to work with it. We extract the relevant information, like the ItemTitle
(file name), SiteURL
, User
, and ModifiedTime
, from the $AuditData
object and the log entry. We add the modified item to our $ModifiedItems
array. If no audit logs are found, we display a warning message. Finally, we export the results to a CSV file using Export-Csv
and disconnect from Exchange Online using Disconnect-ExchangeOnline
. This approach gives you a comprehensive view of file modifications, but it requires a bit more setup and parsing compared to the other methods.
Choosing the Right Approach
So, which method should you use? It really depends on your specific requirements and environment. If you're in SharePoint Online and want a quick and easy solution, PnP PowerShell is your best bet. It’s simple, efficient, and gets the job done. If you're on-premises and comfortable with SSOM, the SharePoint Server Object Model gives you more control and flexibility. And if you need a comprehensive view of all activity in your site, including modifications, access events, and more, the SharePoint Audit Logs are the way to go. Each method has its strengths and weaknesses, so choose the one that fits your needs the best.
Final Thoughts
Tracking item modifications in SharePoint is crucial for maintaining a secure and well-managed environment. Whether you choose PnP PowerShell, SSOM, or the Audit Logs, you now have the tools and knowledge to get the job done. Remember to tailor your approach to your specific needs and environment, and always test your scripts before running them in production. Happy scripting, guys, and keep those SharePoint sites in tip-top shape!
FAQ
Can I schedule these scripts to run automatically?
Absolutely! You can use the Windows Task Scheduler to schedule these PowerShell scripts to run at specific intervals. This way, you can automatically generate reports and stay on top of changes in your SharePoint environment. For example, you can set the task scheduler to run the script every day at a specific time, ensuring you always have the latest information.
How do I handle large lists with many items?
For large lists, consider using paging in your PowerShell scripts to avoid performance issues. Paging allows you to retrieve items in chunks, rather than trying to load everything at once. This can significantly improve the performance and reliability of your scripts. Look into the RowLimit
and Position
properties in your CAML queries or the -PageSize
parameter in PnP PowerShell cmdlets.
What permissions do I need to run these scripts?
You'll need appropriate permissions to access SharePoint and the audit logs. For PnP PowerShell and SSOM, you typically need site collection administrator permissions. For audit logs, you'll need permissions to access the Exchange Online Protection Center or the Security & Compliance Center. Make sure your account has the necessary privileges before running the scripts.
How can I customize the output of the reports?
You can easily customize the output of the reports by modifying the $ModifiedItems
array and the Export-Csv
command. For example, you can add additional properties to the custom objects in the array or specify different fields in the Select-Object
cmdlet before exporting to CSV. This allows you to tailor the reports to include exactly the information you need.
What if I encounter errors while running the scripts?
If you encounter errors, double-check your script for typos and ensure you have the correct site URLs and credentials. Also, make sure you have the necessary modules installed (e.g., PnP.PowerShell, Microsoft.Online.SharePoint.PowerShell). If you're using SSOM, ensure the script is running on a SharePoint server or has the SharePoint client-side libraries installed. If you're still stuck, try searching online forums or communities for similar issues. The SharePoint community is super helpful and there’s a good chance someone else has encountered the same problem! Remember, debugging is a part of coding, so don’t get discouraged!
Can I filter the audit logs for specific file types?
Yes, you can filter the audit logs for specific file types by adding additional criteria to your search query. The Search-UnifiedAuditLog
cmdlet has parameters that allow you to specify file extensions or other properties. You can modify the script to include these filters and narrow down the results to the file types you're interested in. This can be particularly useful if you want to track changes to specific types of documents, like PDFs or spreadsheets.
Is it possible to track modifications made by a specific user?
Yes, you can track modifications made by a specific user by filtering the results based on the UserId
property in the audit logs or the Editor
property in the item metadata. In the scripts, you can add a Where-Object
clause to filter the results based on the user's ID or username. This can help you monitor the activities of specific individuals within your SharePoint environment and ensure accountability.