Wednesday, February 1, 2017

SharePoint Online: Add Attachment to List Item using PowerShell

Requirement: Add Attachment to SharePoint Online List Item

PowerShell to Add an Attachment to List Item:

#Load SharePoint CSOM Assemblies
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 Add-AttachmentToListItem()
        [Parameter(Mandatory=$true)] [string] $SiteURL,
        [Parameter(Mandatory=$true)] [string] $ListName,
        [Parameter(Mandatory=$true)] [string] $ItemID,
        [Parameter(Mandatory=$false)] [string] $AttachmentPath
    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 the List & List Item
        $List = $Ctx.Web.Lists.GetByTitle($ListName)
        $ListItem = $List.GetItemByID($ItemID)

        #Get All existing attachments
        $AttachmentFiles = $ListItem.AttachmentFiles

        #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

            write-host  -f Green "Attachment Added to List Item!" 
            write-host -f Yellow "Attachment File Name Exists already!"
    Catch {
        write-host -f Red "Error Adding Attachment to List!" $_.Exception.Message

#Set Parameters
$SiteURL= ""

#Call the function to copy list items
Add-AttachmentToListItem -SiteURL $SiteURL -ListName $ListName -ItemID $ItemID -AttachmentPath $AttachmentPath

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

Check out these SharePoint products:

No comments :

Post a Comment

Please Login and comment to get your questions answered!

You might also like:

Related Posts Plugin for WordPress, Blogger...