If you have list of files in csv and all from same site , we can use below script to delete versions.
# Replace with your own Connect-PnPOnline statement
$SiteUrl = "
https://contoso.sharepoint.com/sites/site"
Connect-PnPOnline -Url $SiteUrl -UseWebLogin
# Replace with the path to your own CSV file
$FileList = Import-Csv .\VersionDelete.csv
# Replace with the number of versions you want to keep
$VersionsToKeep = 2
Write-Verbose "Keeping $VersionsToKeep of each file"
foreach($File in $FileList) {
# Remove site from Filename if it's there
$Filename = $File.FileName.Replace($SiteUrl,"")
Write-Verbose "Getting version for file $Filename"
# Get the versions of each file
$FileVersions = Get-PnPFileVersion -Url $Filename
Write-Verbose "Found $($FileVersions.Count) versions"
if ($FileVersions.Count -gt $VersionsToKeep) {
# Pick the ones we want to remove
$DeleteVersionList = ($FileVersions[0..$($FileVersions.Count - $VersionsToKeep)])
Write-Verbose "More than $VersionsToKeep versions. Deleting $($DeleteVersionList.count)"
foreach($VersionToDelete in $DeleteVersionList) {
Write-Verbose "Removing $($VersionToDelete.VersionLabel)"
# Remove the versions
#Remove-PnPFileVersion -Url $Filename -Identity $VersionToDelete.Id -Force
$Output = [PSCustomObject]@{
PSTypeName = 'TKDeletedFileVersion'
Filename = $Filename
DeletedVersion = $($VersionToDelete.VersionLabel)
}
# Output the output
$Output
}
} else {
Write-Verbose "$Filename only had $($FileVersions.Count). Skipping..."
}
}