Answered by:
powershell to add attachments to an item

Question
-
I can attach a document to an Item using the code below. But, how can I reference a document stored in a SharePoint Library?
Like this:
AddAttachment $item "c:\test.docx"
AddAttachment $item "http://sharepointed.com/docs/test.docx"
--------code------
$web = Get-SPWeb "http://sharepointed.com/"
$list = $web.GetList("http://sharepointed.com/Lists/Taco/")
$item = $list.GetItemById(2)
AddAttachment $item "c:\test.docx"
function AddAttachment($item, $filePath)
{
$bytes = [System.IO.File]::ReadAllBytes($filePath)
$item.Attachments.Add([System.IO.Path]::GetFileName($filePath), $bytes)
$item.Update()
}
http://www.sharepointed.comWednesday, December 7, 2011 7:33 PM
Answers
-
got it!
$file = $web.GetFile($filePath).OpenBinary()
$item.Attachments.Add($filepath, $file)
http://www.sharepointed.com/2011/12/07/powershell-add-attachment-to-item/
http://www.sharepointed.com- Proposed as answer by Kemp Brown Wednesday, December 7, 2011 9:44 PM
- Marked as answer by Qiao Wei Tuesday, December 13, 2011 1:32 AM
Wednesday, December 7, 2011 9:33 PM
All replies
-
Wednesday, December 7, 2011 7:39 PM
-
nope, they are using the same code that i have.
I can get the file using:
$file = $web.GetFile($filePath)
The .Add function wants the file input to be in bytes.
$item.Attachments.Add($filepath, $file)
Error:
Cannot convert argument "1", with value: "docs/test.docx", for "Add" to type "System.Byte[]": "Cannot convert the "docs/test.docx" value of
type "Microsoft.SharePoint.SPFile" to type "System.Byte[]"."
http://www.sharepointed.comWednesday, December 7, 2011 8:35 PM -
got it!
$file = $web.GetFile($filePath).OpenBinary()
$item.Attachments.Add($filepath, $file)
http://www.sharepointed.com/2011/12/07/powershell-add-attachment-to-item/
http://www.sharepointed.com- Proposed as answer by Kemp Brown Wednesday, December 7, 2011 9:44 PM
- Marked as answer by Qiao Wei Tuesday, December 13, 2011 1:32 AM
Wednesday, December 7, 2011 9:33 PM