Uploading attachments to tasks in SharePoint

Uploading attachments to tasks in SharePoint programmatically

Uploading attachments to tasks in SharePoint programmatically can be done if the documents are stored in a structured way. The script described below assumes the documents are stored in folders that are named using the ID of the task in SharePoint.

For how to download attachments from a task list, please see: Downloading attachments from Task list

First, we get all files and folders, then we use the folder name to do a CAML Query lookup to get the Task by ID, then we binary upload the attachments.

$Web = Get-SPWeb "http: location" #SPWeb site location as URL
$fileDirectory = "D:\PROD";    # location holding the attachments
$spList = $web.lists["Tasks"]  #replace with the name of your task list
foreach($folder in Get-ChildItem $fileDirectory)
{
$folderID = $folder.Name
$spQuery = New-Object Microsoft.SharePoint.SPQuery;
$camlQuery = "<Where><Eq><FieldRef Name='TaskID'/><Value Type='Number'>$folderID</Value></Eq></Where>"
$spQuery.Query = $camlQuery
$processListItems = $spList.GetItems($spQuery)                                                                                                                             
$item = $processListItems[0];
$folderPath = $fileDirectory+"\"+$folder
foreach($file in Get-ChildItem $folderPath )
{
#$fileStream = ([System.IO.FileInfo] (Get-Item $File.FullName)).OpenRead()
$bytes = [System.IO.File]::ReadAllBytes($File.FullName)
$item.Attachments.Add([System.IO.Path]::GetFileName($File.FullName), $bytes)
$item.Update()
write-host File Uploaded.. $File.FullName -> $item.ID
}
}
$web.Dispose()
3 replies
    • admin
      admin says:

      The PowerShell capabilities in SharePoint online have always lagged SharePoint on-premises. The need for Microsoft to prevent one tenant from incurring an undue performance laod on other tenants is one factor. Other options include CSOM based solutions to achieve your goal.

      Reply

Trackbacks & Pingbacks

  1. […] For how to upload attachments from a task list, please see: Uploading attachments to tasks […]

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *