Thursday, March 8, 2012

sharepoint 2007 power shell script to delete old versions

Recently I had a requirement from customer to delete old versioned documents in the document library to get the free space.

Since share point saves each version as a new copy with occupying the memory in database server, we should keep the limit on major and minor versions to consume the memory space on the database server.

Its very cumbersome to manually go and delete each version of the document in the document library


Below power shell script allows to delete all the old version copies from document library.

 [System.Reflection.Assembly]::Load(”Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c”)
$siteurl="http://siteurl";
$spsite=new-object Microsoft.Sharepoint.SPSite("$siteurl");
$spweb=$spsite.OpenWeb("$weburl");
$splist=$spweb.GetList("/sites/mydocumentlibray");
foreach($splistitem in $splist.items){
$file=$splistitem.File;
$file.Versions.DeleteAll();
}
$spweb.dispose();
$spsite.Dispose();
write-host ">>>finished at "(get-date) `n;


If you want to keep the limited versions in a document library,
the below power shell script will help you.

 [System.Reflection.Assembly]::Load("Microsoft.Sharepoint,Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c”)
$siteurl="http://siteurl";
$listname="TempEmailDocument";
$spsite=new-object Microsoft.Sharepoint.SPSite("$siteurl");
$spweb=$spsite.OpenWeb();
$splist=$spweb.Lists["$listname"];
$listitems=$splist.items;
$VersionsToKeep=2;
foreach($item in $listitems)
{
$currentVersion=$item.Versions.Count;
if($currentVersion -gt $VersionsToKeep)
{
for($index=$currentVersion-1; $index -gt $VersionsToKeep-1;$index-- )
{
$file=$item.Versions[$index].ListItem.File;
$file.Versions[$index].Delete();
$splist.Update();
write-host "deleting ...." + $item.Name +$file.Versions[$index].VersionLabel+ "...";
}
}
}
$spweb.Dispose();
$spsite.Dispose();
write-host ">>>finished at "(get-date) `n;

In the above code, the number of limited versions are 2.


No comments: