kwizcom banner advertisement

SharePoint Online: Delete Attachments from List Item using Powershell

Requirement: Delete Attachment from SharePoint Online List Item.

PowerShell to Remove Attachment from SharePoint Online 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 Remove-AttachmentFromListItem()
{
    param
    (
        [Parameter(Mandatory=$true)] [string] $SiteURL,
        [Parameter(Mandatory=$true)] [string] $ListName,
        [Parameter(Mandatory=$true)] [string] $ItemID,
        [Parameter(Mandatory=$false)] [string] $AttachmentFileName
    )    
    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)
        $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
        $AttachmentFile = $AttachmentFiles | where { ($_.FileName -eq $AttachmentFileName) }
        If($AttachmentFile -ne $Null)
        {
            $AttachmentFile.DeleteObject()
            $Ctx.ExecuteQuery()

            write-host  -f Green "Attachment File '$AttachmentFileName' Removed from List Item!" 
        }
        else
        {
            write-host -f Yellow "Attachment File '$AttachmentFileName' Doesn't Exist!"
        }
    }
    Catch {
        write-host -f Red "Error Removing Attachment From List!" $_.Exception.Message
    }
}

#Set Parameters
$SiteURL= "https://crescent.sharepoint.com/"
$ListName="Projects"
$ItemID="64"
$AttachmentFileName="ProjectProposal.docx"

#Call the function to copy list items
Remove-AttachmentFromListItem -SiteURL $SiteURL -ListName $ListName -ItemID $ItemID -AttachmentFileName $AttachmentFileName
SharePoint Online: Delete Attachments from List Item using Powershell SharePoint Online: Delete Attachments from List Item using Powershell Reviewed by Salaudeen Rajack on February 01, 2017 Rating: 5

No comments:

Please Login and comment to get your questions answered!

Powered by Blogger.