Skip to content

Instantly share code, notes, and snippets.

@princeppy
Created April 5, 2019 13:57
Show Gist options
  • Save princeppy/8c30088082c77dd42ab0e021c8dff1e7 to your computer and use it in GitHub Desktop.
Save princeppy/8c30088082c77dd42ab0e021c8dff1e7 to your computer and use it in GitHub Desktop.

Add Attachments to Sharepoint Online List Item

CLS

#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"

Add-Type -Path "C:\Program Files\SharePoint Online Management Shell\Microsoft.Online.SharePoint.PowerShell\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\SharePoint Online Management Shell\Microsoft.Online.SharePoint.PowerShell\Microsoft.SharePoint.Client.Runtime.dll"
 
Function Add-AttachmentToListItem {
    param
    (
        [Parameter(Mandatory=$true)] [string] $SiteURL,
        [Parameter(Mandatory=$true)] [string] $ListName,
        [Parameter(Mandatory=$true)] [string] $ItemID,
        [Parameter(Mandatory=$false)] [string] $AttachmentPath,
        [Parameter(Mandatory=$false)] $Credential = $null
    )
    # http://www.sharepointdiary.com/2017/02/sharepoint-online-add-attachment-to-list-item-using-powershell.html

    Try {
        if($Credential -eq $null){
            #Setup Credentials to connect
            $Cred = Get-Credential
            $Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)
        } else { $Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Credential.UserName,$Credential.Password)}

        #Setup the context
        $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
        $Ctx.Credentials = $Cred
 
        #Get the List & List Item
        $List = $Ctx.Web.Lists.GetByTitle($ListName)
        $Ctx.Load($List)
        $ListItem = $List.GetItemByID($ItemID)
        $Ctx.Load($ListItem)
        $Ctx.ExecuteQuery()
 
        #Get All existing attachments
        $AttachmentFiles = $ListItem.AttachmentFiles
        $Ctx.Load($AttachmentFiles)
        $Ctx.ExecuteQuery()
 
        #Check if attachment file name exists already
        $FileName = Split-Path $AttachmentPath -Leaf
        $AttachmentFile = $AttachmentFiles | where { ($_.FileName -eq $FileName) }
        If($AttachmentFile -eq $Null)
        {
            #Get the Attachment file from local disk
            [Byte[]]$Bytes = [System.IO.File]::ReadAllBytes($AttachmentPath)
            $ContentStream = New-Object -TypeName System.IO.MemoryStream -ArgumentList @(,$Bytes)
     
            #Create Attachment object
            $AttachmentCreation = New-Object Microsoft.SharePoint.Client.AttachmentCreationInformation
            $AttachmentCreation.ContentStream = $ContentStream
            $AttachmentCreation.FileName = $FileName
            [Void]$ListItem.AttachmentFiles.Add($AttachmentCreation)
            $Ctx.ExecuteQuery()
 
            write-host  -f Green "Attachment Added to List Item!"
        }
        else
        {
            write-host -f Yellow "Attachment File Name Exists already!"
        }
    }
    Catch {
        write-host -f Red "Error Adding Attachment to List!" $_.Exception.Message
    }
}

$query = "<View><Query><Where><Eq><FieldRef Name='__dID' /><Value Type='Number'>{0}</Value></Eq></Where></Query></View>"

$files = Get-Content "C:\Users\xxx\\filemetadata.json" | ConvertFrom-Json | Get-ObjectMembers

#Set Parameters
$SiteURL        = "https://xxxxx.sharepoint.com/it"
if($Credential -eq $null) { $Credential = Get-Credential }
Connect-PnPOnline -Url $SiteURL -Credentials $Credential

$list = Get-PnPList -Web (Get-PnPWeb) -Identity "BudgetAY"
$files | %{
    $id = $_.key
    $attachments = $_.value
    $item = Get-PnPListItem -List $list -Query ($query -f $id)
    $item
    $attachments | %{
        $attachment  = $_
        $fileWithPath = "C:\Users\prince\Downloads\backup sps\BudgetAY Attachments\$($attachment)"
        if(Test-Path -Path $fileWithPath) {
            #Call the function to copy list items
            Add-AttachmentToListItem -SiteURL $SiteURL -ListName $ListName -ItemID ($item.Id) -AttachmentPath $fileWithPath -Credential $Credential
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment