PowerShell

When doing test migrations or otherwise coordinating multiple environments, it’s sometimes useful to create a list of files modified since a cutoff date.

PowerShell makes it easy:

Add-PSSnapin Microsoft.SharePoint.PowerShell

$dateCutoff = "2015-01-01"
$spQuery = New-Object Microsoft.SharePoint.SPQuery 
$spQuery.Query = "<Where> 
 <Gt> 
 <FieldRef Name='Modified' /> 
 <Value IncludeTimeValue='TRUE' Type='DateTime'>" + $dateCutoff + "</Value>
 </Gt> 
 </Where>"
$spQuery.ViewFields = "<FieldRef Name='EncodedAbsUrl' /><FieldRef Name='Modified' />" 
$spQuery.ViewFieldsOnly = $true

Get-SPWebApplication | Get-SPSite | Get-SPWeb | ForEach-Object { ForEach ($list in $_.Lists) { $listItems = $list.GetItems($spQuery); $listItems | ForEach-Object { $_['EncodedAbsUrl'] + " (" + $_['Modified'] + ")" } } }

How many versions of a typical document do you need to keep? 5? 10? 100?

SharePoint content databases often get cluttered with redundant versions of the same documents. In some cases, I’ve seen presentation libraries with less than 10 GB of active content, but hundreds of GBs of content due to gradual changes.

If you’re ready to clear out old versions, SharePoint’s Management Shell makes it easy. The script below will iterate through all lists and update them to keep only the last 2 copies. It will also loop through and delete unneeded versions.

Get–SPWebApplication | Get–SPSite –Limit All | Get–SPWeb –Limit All | ForEach–Object { ForEach ($list in $_.Lists) { If ($list.EnableVersioning –eq $true){ $list.MajorVersionLimit=2; $list.Update(); ForEach ($item in $list.Items){ $item.URL; $item.SystemUpdate() } } } }

You can see that it…

  1. Loops through all web applications
  2. Loops through their site collections
  3. Loops through their webs
  4. Loops through their lists
  5. If versioning’s enabled, it sets the major version limit to 2
  6. In order to remove old versions, it needs to loop through each item and perform a system update

The script can be easily amended to deal with only specific site collections / libraries. To keep a different number of versions, modify the MajorVersionLimit variable above.