Friday, March 7, 2014

Download All Attachments from SharePoint List Items using PowerShell

Requirement is to Download all attachments from a SharePoint list to local folder. Lets use PowerShell to download attachments in SharePoint list items using PowerShell.

PowerShell script to download all attachments from a SharePoint list:

[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
#For MOSS 2007 compatibility
Function global:Get-SPWeb($url)
{
  $site= New-Object Microsoft.SharePoint.SPSite($url)
        if($site -ne $null)
            {
               $web=$site.OpenWeb()        
            }
    return $web
}

#Site URL and List Name variables
$WebURL = "http://intranet.crescent.com/sites/purchase"    
$LibraryName = "Invoinces"   

#Local folder to which attachments to be downloaded
$DownloadPath = "C:\Docs"     

#Get the web
$Web = Get-SPWeb $WebURL
#Get the Library
$List = $Web.Lists[$LibraryName]    

    #Loop through each List item
    foreach ($ListItem in $List.Items)
     {   
       #Set path to save attachment
       $DestinationFolder = $DownloadPath + "\" + $ListItem.ID          

       #Check if folder exists already. If not, create the folder
         if (!(Test-Path -path $DestinationFolder))        
            {            
                New-Item $DestinationFolder -type directory          
            }
      
          #Get all attachments
          $AttachmentsColl = $ListItem.Attachments
          
          #Loop through each attachment
          foreach ($Attachment in $AttachmentsColl)    
               { 
                 #Get the attachment File       
                 $file = $web.GetFile($listItem.Attachments.UrlPrefix + $Attachment)        
                 $bytes = $file.OpenBinary()                
                
                 #Save the attachment as a file  
                 $FilePath = $DestinationFolder + " \" + $Attachment
                 $fs = new-object System.IO.FileStream($FilePath, "OpenOrCreate")
                 $fs.Write($bytes, 0 , $bytes.Length)    
                 $fs.Close()    
                }
    }
For C# version of the above code, Go to: Download Attachments from SharePoint List Programmatically



You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Check out these SharePoint products:

1 comment :

Please Login and comment to get your questions answered!

You might also like:

Related Posts Plugin for WordPress, Blogger...