Thursday, August 2, 2012

Powershell Script to download attachments on a SharePoint List into a file share

Problem Description: Download all attachments on a SharePoint List to a File Share. Each set of attachments for a List Item need to be in its own folder, with ItemId as the name of the folder.

Solution: Powershell script shown below was run. The script took about 5 minutes to run on a list with 3000 items, each containing between 1 and 5 attachments. Average size of an attachment is between 1 and 5 MB.



   1:  $webUrl = "Url"    
   2:  $library = "ListName"   
   3:  #Local Folder to dump files
   4:  $tempLocation = "FolderPath"     
   5:  $s = new-object Microsoft.SharePoint.SPSite($webUrl)    
   6:  $w = $s.OpenWeb()         
   7:  $l = $w.Lists[$library]    
   8:  foreach ($listItem in $l.Items)
   9:  {
  10:      Write-Host "    Content: " $listItem.ID 
  11:       $destinationfolder = $tempLocation + "\" + $listItem.ID          
  12:        if (!(Test-Path -path $destinationfolder))        
  13:         {            
  14:          $dest = New-Item $destinationfolder -type directory          
  15:         }
  16:      foreach ($attachment in $listItem.Attachments)    
  17:          {        
  18:              $file = $w.GetFile($listItem.Attachments.UrlPrefix + $attachment)        
  19:              $bytes = $file.OpenBinary()                
  20:              $path = $destinationfolder + "
\" + $attachment
  21:              Write "
Saving $path"
  22:              $fs = new-object System.IO.FileStream($path, "
OpenOrCreate")
  23:              $fs.Write($bytes, 0 , $bytes.Length)    
  24:              $fs.Close()    
  25:          }
  26:  }

Reference: Thanks to this blogpost. I tweaked the script mentioned on this blog post for the above purpose.