Using PNP to Copy files between SharePoint Sites with metadata

Brass Contributor

I'm trying to copy files between SharePoint sites.  I can not find an example of using the powershell PNP commands in sequence to perform the actions.  


I'm not certain if I should be using Get-PNPListItems first then trying to use Get-PNPFile then using copy-pnpfile.  


I see examples of these commands working individually but I don't see examples of using them in a real script to migrate files.



2 Replies

Hi @David Jenkins 

did you get anywhere with this...i have the same issue

I did actually get it to work. It's been a while so hopefully what I post makes sense.

I was copying list items from one sharepoint site to another.

First I got all items in the list.
#Define CAML Query
$qaDatabaseAll = Get-PnPListItem -List "QA Database" -Connection $sourceSite

Then do a foreach. like foreach($qaDBentry in $qaDatabaseAll){$qaDBentry}

Then the basic steps are to get the attachments. Sometimes theres more than one so foreach...
#Get Attachments for Entry
$attachments = ForEach-Object{Get-PnPProperty -ClientObject $qaDBentry -Property "AttachmentFiles" -Connection $sourceSite}

#Create new item
$newListItem = Add-PnPListItem -List "QA Database" -Values $qualityAlertValues -Connection $destinationSite -ContentType $qaDBentryContentType.Name

#Append Attachments
foreach($attachment in $attachments){
#Download the Attachment to Temp
# Fails because of versions?
#$File = Get-PnPFile -Url $attachment.ServerRelativeUrl -FileName $attachment.FileName -Path "D:\TEMP" -AsFile -force -Connection $sourceSite

$fileInfo = [Microsoft.SharePoint.Client.File]::OpenBinaryDirect($sourceCtx, $Attachment.ServerRelativeUrl) #
$toPath = "D:\temp\" #
$fileName = $toPath + $attachment.FileName #
$fileStream = [System.IO.File]::Create($fileName) #
$fileInfo.Stream.CopyTo($fileStream); #

#Add Attachment to Target List Item
$FileStream = New-Object IO.FileStream(("D:\TEMP"+"\"+$attachment.FileName),[System.IO.FileMode]::Open)
$AttachmentInfo = New-Object -TypeName Microsoft.SharePoint.Client.AttachmentCreationInformation
$AttachmentInfo.FileName = $attachment.FileName
$AttachmentInfo.ContentStream = $FileStream
$AttachFile = $newListItem.AttachmentFiles.add($AttachmentInfo)

#Delete the Temporary File
Remove-Item -Path "D:\TEMP\$($attachment.FileName)" -Force