Every now and then a problem pops up in that a user is unable to delete an attachment on a list item. The system goes through the motions of deleting the item, but when you get back to the list item the attachment is still there. No errors are received and no reason is given for the item not deleting. I haven’t seen this happen very often but it happened recently in one of our team site lists. There was nothing special about the list item or the attachment, but for whatever reason, it wouldn’t delete the attachment. Like so many things I come across I figure if it happened to me, it could happen to someone else. So that brought about this blog post. I want to show you how to delete a list item’s attachment with PowerShell.
How to Delete a SharePoint List Item Attachment with PowerShell
So to start off I have a simple list with an item that has two attachments. I want to delete the one called “AutoSPInstallerFolderStructure.txt”. The process for deleting it is pretty straightforward. You simply access the list, get the item we are looking for in the list and then loop through the attachments until we find the one we want to delete and remove it.
Building the script:
#############################################################################################
#Date Who Comment #
#------------- ------------------ ------------------------------------------------------ #
#01May2017 David Drever Deletes an attachment from a list item #
#############################################################################################
$webURL = "http://teams.drevsp2016.com";
$listName = "AttachmentList";
$attachmentName = "AutoSPInstallerFolderStructure.txt";
$spWeb = Get-SPWeb $webURL;
$spList = $spWeb.Lists[$listName];
$spListItems = $spList.Items;
foreach($spListItem in $spListItems)
{
#Need to do a reverse loop as we are deleting from the collection and a forward loop will fail
for($i=$spListItem.Attachments.count-1; $i -ge 0; $i--)
{
if($spListItem.Attachments[$i].Contains($attachmentName))
{
write-host "Deleting file:" $spListItem.Attachments[$i]
$spListItem.Attachments.Delete($spListItem.Attachments[$i])
$spListItem.SystemUpdate()
}
}
}
Before the Script:
![How to Delete a SharePoint List Item Attachment with PowerShell - BeforeScript]()
Running the Script:
![How to Delete a SharePoint List Item Attachment with PowerShell - Running The Script]()
After the Script:
![How to Delete a SharePoint List Item Attachment with PowerShell - After the Script]()
And that’s it. You can also modify the script to delete attachments in bulk if the need is there.
Thanks for reading!