Powershell Tips Series : Download all attachments from a SharePoint list

Sriram Varadarajan
 
Solution Architect
December 19, 2015
 
Rate this article
 
Views
16991

Use the below Poweshell script to download all the attachments from a SharePoint list / library and save those files to local folder

Code Snippet

 $webUrl = "URL"
 $library = "Documents"  
 #Local Folder to dump files
 $tempLocation = "D:attachments"     
 $s = new-object Microsoft.SharePoint.SPSite($webUrl)    
 $w = $s.OpenWeb()         
 $l = $w.Lists[$library]    
 foreach ($listItem in $l.Items)
 {
     Write-Host "    Content: " $listItem.ID 
     $destinationfolder = $tempLocation + "" + $listItem.ID          
     if (!(Test-Path -path $destinationfolder))        
     {            
         $dest = New-Item $destinationfolder -type directory          
     }
     foreach ($attachment in $listItem.Attachments)    
     {        
         $file = $w.GetFile($listItem.Attachments.UrlPrefix + $attachment)        
         $bytes = $file.OpenBinary()                
         $path = $destinationfolder + "" + $attachment 
         Write "Saving $path" 
         $fs = new-object System.IO.FileStream($path, "OpenOrCreate") 
         $fs.Write($bytes, 0 , $bytes.Length)    
         $fs.Close()    
     }
 }
 

Author Info

Sriram Varadarajan
 
Solution Architect
 
Rate this article
 
Sriram is a Technology Evangelist with 15+ years experience in Microsoft Technologies. He is an enterprise architect working for large pharmaceutical organization which has presence globally with largest Microsoft implementation ...read more
 

Leave a comment