1
votes

I'm trying to use powershell and Sharepoint 2013 CSOM to copy attachments of one item to a new item in another list. I've been able to successfully generate an attachments folder for the new item, so in theory all I need to do is move the files from the old attachments folder to the new one. CopyTo and MoveTo only seem to work for moving files within a list, so I thought to use OpenBinaryDirect and SaveBinaryDirect with the site context. However, in powershell, calling either of these methods results in the following error: Method invocation failed because [System.RuntimeType] doesn't contain a method named 'OpenBinaryDirect'.

$attachments = $item.AttachmentFiles
if($attachments.Count -gt 0)
{
    #Creates a temporary attachment for the new item to genereate a folder, will be deleted later.
    $attCI = New-Object Microsoft.SharePoint.Client.AttachmentCreationInformation
    $attCI.FileName = "TempAttach"
    $enc = New-Object System.Text.ASCIIEncoding
    $buffer = [byte[]] $enc.GetBytes("Temp attachment contents")
    $memStream = New-Object System.IO.MemoryStream (,$buffer)
    $attCI.contentStream = $memStream
    $newItem.AttachmentFiles.Add($attCI)

    $ctx.load($newItem)
    $sourceIN = $sourceList.Title
    $archIN = $archList.Title
    $sourcePath = "/" + "Lists/$sourceIN/Attachments/" + $item.Id
    $archPath = "/" + "Lists/$archIN/Attachments/" + $newItem.Id
    $sFolder = $web.GetFolderByServerRelativeUrl($sourcePath)
    $aFolder = $web.GetFolderByServerRelativeURL($archPath)
    $ctx.load($sFolder)
    $ctx.load($aFolder)
    $ctx.ExecuteQuery()
    $sFiles = $sFolder.Files
    $aFiles = $aFolder.Files
    $ctx.load($sFiles)
    $ctx.load($aFiles)
    $ctx.ExecuteQuery()
    foreach($file in $sFiles)
    {
        $fileInfo = [Microsoft.SharePoint.Client.File].OpenBinaryDirect($ctx, $file.ServerRelativeUrl)
        [Microsoft.Sharepoint.Client.File].SaveBinaryDirect($ctx, $archPath, $fileInfo.Stream, $true)
    }
}
$ctx.ExecuteQuery()

Any help on either getting the BinaryDirect methods to work or just a generalized strategy for copying attachments across lists using powershell + CSOM would be greatly appreciated.

1
please consider marking latkin's answer as the answerTroy Palacino

1 Answers

2
votes

You have the wrong syntax for invoking a static method. You want [Microsoft.SharePoint.Client.File]::OpenBinaryDirect( ... )

Note the double colons syntax :: between the type name and the method name. Same for SaveBinaryDirect invocation.