Just a few days I wrote that ” it’s been MONTHS since I last ran a PowerShell script!” – and yesterday I not only had to run a script, but create it first. Luckily I still remembered how to use some of the PnP PowerShell cmdlets (though I have to confess, I forgot some syntax), and got the script working within a very short time. Not a surprise, really, as its purpose is quite simple.

What I wanted to do is to track some changes that were made to a list item in SharePoint Online – basically, who updated the item, made which changes to which fields, and when. Sounds exactly like the OOTB version history, but I needed to export it to CSV. As this is a “get the job done quickly” kind of script, it’s kept extremely simple – but as said, it gets the job done. Fields that I wanted to track a hardcoded, and exporting the columns to the CSV is not done in any specific order. Could be improved, but doesn’t have to.

Not much else needs to be explained, here’s the very simple script:

$ListName = "My List Name"
$siteUrl = "https://example.sharepoint.com/sites/demosite"
$ItemId = 1234

Connect-PnPOnline -Url $siteUrl
$list = get-pnplist -Identity $ListName
$item = Get-PnPListItem -List $list -Id $ItemId
$versions = = Get-PnPProperty -ClientObject $item -Property Versions

$VersionHistory = @()
Foreach($version in $versions)
	$CreatedBy =  Get-PnPProperty -ClientObject $version -Property createdby
	$VersionHistory += New-Object PSObject -Property @{
		'VersionId' = $version.VersionId
		'Created by' = $CreatedBy.Title
		'Created' = $version.Created
    #Update here as required with your own columns
		'My First Column' =  $version.FieldValues["MyFirstColumn"]
		'Another Column' = $version.FieldValues["AnotherColumn"]
		'One More Column' = $version.FieldValues["OneMoreColumn"]   
$VersionHistory | Export-Csv "VersionHistory $($ListName) $($ItemId).csv"

Link to the source code on GitHub: https://github.com/modery/PnP-Samples/blob/master/Items/GetItemVersionHistory

Photo by Fatos Bytyqi on Unsplash

Leave a Reply

Your email address will not be published. Required fields are marked *

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