This script can retrieve document versions, along with metadata such as the version number, last modified date, and the user who made the changes.
This PowerShell script will,
- Connect to a SharePoint site.
- Access a specified document library.
- Retrieve version information for each document, including version number, modified date, and modified by.
- Export the data to a CSV file for easy reference.
Step 1. Install PnP.PowerShell module.
Install-Module -Name "PnP.PowerShell" -Scope CurrentUser.
Step 2. Script to get all the versions of Documents.
# Import the PnP.PowerShell module
Import-Module PnP.PowerShell
# Define parameters
$SiteUrl = ""
$LibraryName = "Documents" # Replace with your document library name
$OutputFile = "DocumentVersionHistory.csv"
$Username = "[email protected]" # Replace with your SharePoint username
$Password = "yourpassword" # Replace with your SharePoint password
# Create a secure password
$SecurePassword = ConvertTo-SecureString $Password -AsPlainText -Force
# Create a credential object
$Credential = New-Object System.Management.Automation.PSCredential($Username, $SecurePassword)
# Connect to SharePoint Online using credentials
Connect-PnPOnline -Url $SiteUrl -Credentials $Credential
# Initialize an array to store version data
$VersionData = @()
# Get all files in the specified document library
$Files = Get-PnPListItem -List $LibraryName -PageSize 100 -Fields "FileLeafRef", "FileDirRef"
# Loop through each file in the library
foreach ($File in $Files) {
# Build the full URL for the file
$FileUrl = ($File["FileDirRef"] + "/" + $File["FileLeafRef"])
# Retrieve version history for the current file
$Versions = Get-PnPFileVersion -Url $FileUrl
# Loop through each version and capture version details
foreach ($Version in $Versions) {
$VersionData += New-Object PSObject -Property @{
"FileName" = $File["FileLeafRef"]
"VersionNumber" = $Version.VersionLabel
"ModifiedDate" = $Version.Created
"ModifiedBy" = $Version.CreatedBy
}
}
}
# Export the version data to a CSV file
$VersionData | Export-Csv -Path $OutputFile -NoTypeInformation -Encoding UTF8
# Disconnect from SharePoint
Disconnect-PnPOnline
Write-Host "Document version history exported to $OutputFile"
Notes
- This script leverages PnP.PowerShell, the modern module that replaces the legacy SharePointPnPPowerShellOnline.
- The password is securely handled by converting it to a SecureString and using it within the PSCredential object.
Conclusion
This approach provides a simple and modern way to retrieve document version histories using PnP.PowerShell, with added security and cross-platform compatibility.