The SharePoint Coffee House
I'd like some SharePoint with my coffee please...

PowerShell Script to Delete All Versions in a Document Library

Sunday, 10 April 2011 21:41 by Michael Mukalian

The question was asked of how to delete all versions of a document in libraries in a site collection.  So, I wound up whipping up this script kinda quick.  It's nothing too crazy, but what I've been trying to do of late is to see how often I can write the script so that it'd work in both SharePoint 2007 and 2010.  Granted I do this cause I've been worknig on both versions of late, but I can see more and more leaning more towards the SharePoint 2010 cmdlets as 2010 is adopted more.  So, that being said...

What we have below is a script that instantiates a site collection, loops through all its webs, identifies the document libraries only, goes through each item, and deletes all of the versions of the item, leaving only the current version.  It's good to note here that since this is a document library we're dealing with you need to work with the SPFile object.  That's pretty much it, nothing crazy and it's not rocket science, right?  Again, as before, keep in mind that the disposal of the web and site objects are a necessity.

[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
# get site
$site = new-object Microsoft.SharePoint.SPSite("http://mossdev:8000")
# loop through webs
foreach ($web in $site.AllWebs)
{
  # loop through all lists in web
  foreach ($list in $web.Lists)
  {
    # examine if BaseType of list is NOT a Document Library
    if ($list.BaseType -ne "DocumentLibrary") 
    {
      # forget the rest and return to top
      continue
    }
    # loop through each item
    foreach ($item in $list.Items)
    {
      # work with the file object as we're in a document library
      $file = $item.File
      # delete all versions
      $file.Versions.DeleteAll()
    }
  }
}
$web.Dispose();
$site.Dispose();

Note: Take a look at Gary Lapointe's blog for all things (and I mean all) PowerShell.  Awesome reference out there.

Enjoy! - M

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Categories:   2010 | PowerShell | 2007
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed