Forum Discussion

ComputerHabit's avatar
ComputerHabit
Brass Contributor
Sep 15, 2020

Using PNP to Copy files between SharePoint Sites with metadata

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

    • ComputerHabit's avatar
      ComputerHabit
      Brass Contributor
      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
      #$env:TEMP

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

      #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)
      $destinationCtx.ExecuteQuery()

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

      }

Resources