Is it possible to add a .txt file as an attachment to a SharePoint list via powershell which has some more columns

209 Views Asked by At

I have a sharepoint 2016 on Prem list. Which has a few columns. And iam populating values to this list using powershell. Is it possible to add a .txt file to this list as an attachment.. i have seen one field attachment, but what is it's internal name?

1

There are 1 best solutions below

0
On

Yes indeed, there is only one field attachement associated to each item in SharePoint list, in order to achieve your purpose by adding an attachement to an SP Item via PowerShell you need to consider the following things :

  • You need to add SharePoint PowerShell Module,
  • To add an attachement, you need to pass the file content (the byte version of the file) as an Input,
  • Without forgetting the File Path.

The script PowerShell :

#Call SP PS Module  
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
#Custom Function to Add attachment to SharePoint List Item
Function Add-Attachment($Item, $AttachmentPath)
{
  $FileContent = [System.IO.File]::ReadAllBytes($AttachmentPath)
  $Item.Attachments.Add([System.IO.Path]::GetFileName($AttachmentPath), $FileContent)
  $Item.Update()
  
  Write-host "Attachment Added to List Item Successfully!"
}
###########################################################################


#Variables
$SiteURL="<YOUR SHAREPOINT SITE>"
$ListName="<YOUR SHAREPOINT LIST>"
$ItemID=<YOUR SHAREPOINT ITEM ID>
$AttachmentPath="<YOUR LOCAL PATH OF THE FILE>"
 
$web = Get-SPWeb $SiteURL
$List = $web.Lists[$ListName]
$Item = $list.GetItemById($ItemID)
 
#Call the function to Add Attachment
Add-Attachment $Item $AttachmentPath

This Should answer your business requirement.