Pages

Search This Blog

Showing posts with label Versioning. Show all posts
Showing posts with label Versioning. Show all posts

Monday, December 12, 2011

Delete old versions of List Item via Poweshell SharePoint 2010


Most of the doucments were having lots of versions so the need was to remove all the existing versions except the latest version.


You can change this script to complete all the operation at one time means for all the libraries and lists under a web or all the site collections or all the web applications with in a farm.




The following script will remove all the existing versions of the documents except latest one.
PowerShell Command Prompt:


get-spWeb http://myweburl/
ForEach-Object {ForEach($_.list in $_.Lists){If($_.EnableVersioning -eq $True){if($_.Title -eq "ListName"){Write-host "List:"$_.Title "- List ID"$_.Id;$_.MajorVersionLimit = 1;$_.Update();ForEach($_.item in $_.items){$_.item.URL;$_.update()}}}}}




Note:
http://myweburl - Replace with your web URL
ListName - Replace with your list or library name
MajorVersionLimit = 1 - Change 1 to your specific limit

Monday, November 28, 2011

Get and Delete SharePoint List item version programmatically

When you upload a file for the very first time the version 1.0 is created, and from there you can start check in/out documents. Using versioning, you can see your document/item history and access to a particular version, and and restore it.

How to get all version associated with a document?

SPSite oSite = new SPSite("Site URL");
SPWeb oWeb = oSite.OpenWeb();
SPList oList = oWeb.Lists["Shared Documents"];
foreach (SPListItem doc in oList.Items)
{
SPListItemVersionCollection coll = doc.Versions;
foreach (SPListItemVersion version in coll)
{
Console.Writeline('VersionLabel: ' + version.VersionLabel + ' IsCurrentVersion: ' + version.IsCurrentVersion )
}
};

In the above way you can get all version of a document in sharepoint object Model. If you wanna programatically remove all the version , then better make use of SPFileVersionCollection, Since it is going to remove/delete all version except the Current version .

foreach (SPListItem doc in documentLibrary.Items)
{
SPFileVersionCollection coll = doc.File.Versions;
foreach (SPFileVersion version in coll)
{
//Either use Recycle() or Delete()
item.Recycle();  
 //or
 item.Delete();
}
}


But the best way for delete versions are usage of VersionCollection.