I have a SharePoint document library with a large number of documents and versions. My task is to create a PowerShell script to delete all versions but the current for each document.
When I tried to delete the versions within my iteration, I got an error saying that the "collection was modified". Fair enough, I can't change the collection I'm looping through.
So instead I added the versions to be deleted in an array to be processed later outside the loop. But that didn't work eighter, I get "Exception calling Delete with 0 argument(s): Object reference not set to an instance of an object."
I have reviewed all similar Q&As for this issue on this site, but no answer is spot on. Can anyone give a hint on what is going on here? Thanks so much for any help.
asnp *sh*
$site = new-object Microsoft.SharePoint.SPSite("http://somesite")
$web = $site.RootWeb
$list = $web.Lists["Dokument"]
cls
$versionsToDelete = @()
foreach ($listItem in $list.Items)
{
foreach ($ver in $listItem.Versions)
{
if (!$ver.IsCurrentVersion)
{
$versionsToDelete += $listItem.Versions.GetVersionFromLabel($ver.VersionLabel)
}
}
}
for($i=0;$i -lt $versionsToDelete.Count;$i++)
{
write-host "Trying to delete" $versionsToDelete.VersionLabel[$i]
$versionsToDelete[$i].Delete()
}
$web.Dispose()
$site.Dispose()