none
Extracting attachments from a list in SharePoint Online using PowerShell RRS feed

  • Question

  • Hi,

    Not sure if i put this in the right place but I am trying to create a powershell script to extract attachments from a list on SharePoint online. I found this code below:

    $webUrl = "https://mottmac.sharepoint.com/teams/pj-b0000"
    $library = "Photos" 
    #Local Folder to dump files
    $tempLocation = "C:\Users\CHI\Documents\temp"    
    $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()    
        }
    }
     

    but i get errors that read as follows:

    new-object : Cannot find type [Microsoft.SharePoint.SPSite]: verify that the assembly containing this type is loaded.
    At line:7 char:6
    + $s = new-object Microsoft.SharePoint.SPSite($webUrl)
    +      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidType: (:) [New-Object], PSArgumentException
        + FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand
     
    You cannot call a method on a null-valued expression.
    At line:8 char:1
    + $w = $s.OpenWeb()
    + ~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
        + FullyQualifiedErrorId : InvokeMethodOnNull
     
    Cannot index into a null array.
    At line:9 char:1
    + $l = $w.Lists[$library]
    + ~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
        + FullyQualifiedErrorId : NullArray
    

    so i modified it to read like this:

    Connect-PnPOnline -Url 'https://mottmac.sharepoint.com/teams/pj-b0000' -UseWebLogin
    $tempLocation = "C:\Users\CHI\Documents\temp"
    $list = Get-PnPListItem -List 'Photos'
    
    foreach ($listItem in $list)
    {
        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()    
        }
    }

    but all i get in my local temp folder is the amount of folder as in SharePoint but no attachments are in the folder. Can someone tell me what I am doing wrong?

    Thank you in advance.

    Thursday, January 17, 2019 2:54 PM

All replies

  • Where did you source this from? Is there any user posted threads or commentary to check?

    I'll try and test this when I'm at home to see what I can work out too.


    Steven Andrews
    SharePoint Business Analyst: LiveNation Entertainment
    Blog: baron72.wordpress.com
    Twitter: Follow @backpackerd00d
    My Wiki Articles: CodePlex Corner Series
    Please remember to mark your question as "answered" if this solves (or helps) your problem.

    Thursday, January 17, 2019 4:02 PM
    Answerer
  • the original code i found here 

     http://www.sharepointpals.com/post/Powershell-Tips-Series-Download-all-attachments-from-a-SharePoint-list

    I think my problem is in the second foreach loop. Where it supposed to get the attachments. I am able to get the item and they save as a folder in my destination just no attachments in the folders are being pulled.

    Thursday, January 17, 2019 4:46 PM
  • Hi codingChamp23,

    For downloading list all attachments to local folder, here is a working CSOM PowerShell script for your reference:

    Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
    Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
     
    Function Download-ListAttachments()
    {
        param
        (
            [Parameter(Mandatory=$true)] [string] $SiteURL,
            [Parameter(Mandatory=$true)] [string] $ListName,
            [Parameter(Mandatory=$true)] [string] $DownloadDirectory
        )   
       Try {
            #Setup Credentials to connect
            $Cred = Get-Credential
            $Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)
         
            #Setup the context
            $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
            $Ctx.Credentials = $Cred
     
            #Get All Items from the List
            $List = $Ctx.Web.Lists.GetByTitle($ListName)
            $ListItems = $List.GetItems([Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery())
            $Ctx.Load($ListItems)
            $Ctx.ExecuteQuery()
             
            #Create download directory if it doesn't exist
            If (!(Test-Path -path $DownloadDirectory))       
            {           
                New-Item $DownloadDirectory -type directory         
            }
             
            #Iterate through each list item
            Foreach($Item in $ListItems)
            {
                #Get All attachments from the List Item
                $AttachmentsColl = $Item.AttachmentFiles
                $Ctx.Load($AttachmentsColl)
                $Ctx.ExecuteQuery()
     
                #Get attachment for each list item
                ForEach($Attachment in $AttachmentsColl)
                {
                    #Download attachment
                    $FileContent = [Microsoft.SharePoint.Client.File]::OpenBinaryDirect($Ctx, $Attachment.ServerRelativeUrl)
                    $FileName= $DownloadDirectory+$Item.id.ToString()+"_"+$Attachment.FileName
                    $FileStream = [System.IO.File]::Create($FileName)
                    $FileContent.Stream.CopyTo($FileStream)
                    $FileStream.Close()
               }
            }
     
            write-host  -f Green "List Attachments Downloaded Successfully!"
        }
        Catch {
            write-host -f Red "Error Downloading List Attachments!" $_.Exception.Message
        }
    }
     
    #Set Parameters
    $SiteURL= "https://tenant.sharepoint.com/sites/sitename/"
    $ListName="your list name"
    $DownloadDirectory="D:\Temp\"
     
    #Call the function to copy list items
    Download-ListAttachments -SiteURL $SiteURL -ListName $ListName -DownloadDirectory $DownloadDirectory

    Also, please install SharePoint Online CSOM assembly firstly, you could download and install here:

    SharePoint Online Client Components SDK

    Reference:

    SharePoint Online: Download Attachments from List using PowerShell

    Thanks

    Best Regards


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.

    SharePoint Server 2019 has been released, you can click here to download it.
    Click here to learn new features. Visit the dedicated forum to share, explore and talk to experts about SharePoint Server 2019.


    Friday, January 18, 2019 5:48 AM
  • Hi,

     

    I am checking to see how things are going there on this issue. Please let us know if you would like further assistance.

     

    You can mark the helpful post as answer to help other community members find the helpful information quickly.

     

    Thanks

     

    Best Regards


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.

    SharePoint Server 2019 has been released, you can click here to download it.
    Click here to learn new features. Visit the dedicated forum to share, explore and talk to experts about SharePoint Server 2019.

    Tuesday, January 22, 2019 1:51 AM
  • Sorry for the necro-reply, but I am getting the following, mid-download:

    Error Downloading List Attachments! Exception calling "OpenBinaryDirect" with "2" argument(s): "The remote server returned an error: (404) Not Found."

    Any ideas as to why?  I'm assuming a broken document link somewhere, I'm just uncertain how to adjust (so it skips any dead document links) or determine how to find the one in question so I can fix it.

    Wednesday, October 16, 2019 6:49 PM