Copy Attachment from SharePoint List to Document Library using SharePoint Designer – PowerShell

Requirement: Copy Attachments from SharePoint List to Document Library

How to copy attachment from list to document library in SharePoint?

SharePoint keeps attachments under “List >> Attachments >> ‘List Item ID'” folder path. So, if you want to copy an attachment from list to document library, follow these steps:

  1. Open your SharePoint site from SharePoint Designer
  2. Navigate to “All Files” view >> Lists >> Your Source List >> Attachments folder. Here, folders are created based on the list item’s ID. 
    sharepoint copy attachment from list to document library
  3. Just copy attachment files from these folders and navigate to the target document library and paste there.sharepoint designer copy attachment from list to document library

Well, it would be tedious to copy list attachment to document library, if you have large number of list items/attachments. So, lets use PowerShell in SharePoint to copy list attachment to document library.

PowerShell script to copy attachment from list to document library:

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$WebURL = "http://sharepoint.crescent.com/pmo/GIS/"

$SourceListName = "External Projects"   
$TargetLibraryName = "Design Documents"

#Get the Web List and Library objects
$web = Get-SPWeb $WebURL
$SourceList = $web.Lists[$SourceListName]    
$TargetLibrary = $web.Lists[$TargetLibraryName]    

#Loop through each list item
foreach ($ListItem in $SourceList.Items)
{
   if($ListItem.Attachments.Count -gt 0)
   {
        #Loop through each attachment in the list item
        foreach ($Attachment in $ListItem.Attachments)    
        {   
              #Get the attachment
              $file = $web.GetFile($ListItem.Attachments.UrlPrefix+$Attachment)        
              $bytes = $file.OpenBinary()               
    
              $TargetFileName = $TargetLibrary.RootFolder.Url+"/"+$Attachment
              $TargetFile = $TargetLibrary.RootFolder.Files.Add($TargetFileName, $bytes, $true)
              Write-Host "Copied to: $($TargetFilename)"
        }
   }
}

This script copies all attachments from all list items to the given library’s root folder. You can tweak the script a little to create sub-folders in the target library too.

Salaudeen Rajack

Information Technology Professional with Two decades of SharePoint Experience.

2 thoughts on “Copy Attachment from SharePoint List to Document Library using SharePoint Designer – PowerShell

  • January 21, 2021 at 9:26 PM

    Just what I needed! Thanks so much.

    Reply

Leave a Reply