3
votes

I got a custom sharepoint list, with a title column which contains Servernames and i got alot of .csv files that has the same name as the title

Is it somehow possible to upload em to the list item as an attachment with a script? Maybe Powershell? I got over 100 files so it would be a pain if i had to do it all manually.

The File and Title column looks like this:

Title
Server1.domain.com

.csv
Server1.domain.com.csv

Have been looking around for quite a while but havent been able to find anything i could use

1

1 Answers

4
votes

Approach:

  1. Iterate over the SharePoint list items.
  2. Load the corresponding CSV file by the SPListItem.Title
  3. Add the file as attachment to the SPListItem.

Script:

$w = Get-SPWeb http://List/Location/Url
$l = $w.Lists["TheList"]

foreach ($item in $l.Items)
{
     $file = Get-Item "$($item.Title).csv"
     $stream = $file.OpenRead()
     $buffer = New-Object byte[] $stream.length
     [void]$stream.Read($buffer, 0, $stream.Length)

     $item.Attachments.AddNow($file.Name, $buffer)
}

Considerations:

  1. Disposing of the file stream
  2. Disposing of the SPWeb object
  3. Handle missing files

Edit

Two mistakes in first attempt:

  1. SPAttachmentCollection.Add expects a byte array.
  2. SPAttachmentCollection.AddNow should be used to add the attachment directly (without update of the SPListItem)

Updated the code...