Compare SharePoint List Item Version History using PowerShell
Requirement: Compare version history data of SharePoint List items and update a metadata column based on a particular field’s value change.
A bit of background: We have a project tracking list with the “Status” column. We wanted to have an insight into when a particular item’s status was set to “Rejected”.
PowerShell to Compare Version History Data and update a column value:
As far solution to the above requirement, let’s compare list item versions to capture when a particular item’s “status” column was changed to “rejected”, and get the created date of the specific version to update the “Rejected Date” column of the list item. Let’s compare version history in SharePoint using PowerShell:
Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue
#Parameters
$SiteURL="https://intranet.crescent.com"
$ListName = "Projects"
#Get web and List
$Web = Get-SPWeb $SiteURL
$List = $web.Lists.TryGetList($ListName)
#Get all list items
$ListItems = $List.Items
#Iterate through each list item
Foreach($Item in $ListItems)
{
#Iterate through each version
ForEach($Version in $Item.Versions)
{
#Check if the status column is "Rejected"
If($($version['Status']) -eq "Rejected")
{
#Update Rejected Date value of the item from version
$Item["RejectedDate"] = $($version.Created)
$Item.SystemUpdate()
Write-host "ID:$($item.id), Version:$($version.VersionLabel), CreatedBy:-$($version.CreatedBy.User.DisplayName), Status:-$($version['Status'])"
Break
}
}
}
This script compares each list item version and updates the “RejectedDate” column value. If you want to export list item version history, use: How to Export SharePoint List Item Version History using PowerShell?
Doesnt this script give you the newest version where the status=rejected? So it doesnt get the version where the changes was actualy made.
Example: You want the version 2 to be returned but the script will return version 3 since that is the newest version where the status is Rejected.
Version
3 Some other field is changed. No changes to the Status field.
2 Status is set to Rejected.
1 Item is created