Copy or Move Files (not folders) to another SharePoint Library or Site using PowerShell PnP

In today’s post, we’ll have a look at something that could potentially be your mini “re-organisation / migration” project.
We’ll see how to copy or move files to another location, either on the same site but different library, or a completely different site 🙂

 

Starting Point

Let’s have a look first at our current (dummy) structure.

We have SitePnP1 where we’ll use the default Documents library. Inside this library, we have a folder called Folder1 with files inside (nested files). And we also have a files on its own (SPO Roadmap.pptx) at the same level as the Folder1.

    

So the goal here would be to copy or move those files into a new location. We do not want to have a folder structure, so we’ll leave the folder(s) “behind”.
👉🏻  For this example, we’ll copy them into a different site (SitePnP2), therefore a different library!

 

Description in the cmdlets

If we look at the description of the Copy-PnPFile cmdlet (or the Move-PnPFile for that matter), we can read: “Copies a file or folder to a different location“.
Here we have it. Folders are also in scope if we don’t do something! Because we’ll use the Get-PnPListItem cmdlet to grab all the items, it’ll also grab the folders. And we don’t want that…

So what do we do? Well… We have a property called FileSystemObjectType that can be either File or Folder. So let’s use it 😉

ℹ️.  Note that both cmdlets are using the same parameters so choose one or the other depending on what you wish to do (copy or move)

 

The Script

And with only a few lines, here we go…

Connect-PnPOnline -Url "https://<TENANT-NAME>.sharepoint.com/sites/SitePnP1" -Credentials <YOUR-CREDS>

$allItems = Get-PnPListItem -List "Shared Documents" -FolderServerRelativeUrl "/sites/SitePnP1/Shared Documents"

foreach ($item in $allItems) {
    if ($item.FileSystemObjectType -eq "File") {
        Write-Host "Copying file: $($item.FieldValues.FileLeafRef)" -ForegroundColor green
        Copy-PnPFile -SourceUrl "$($item.FieldValues.FileRef)" -TargetUrl "/sites/SitePnP2/TargetLibrary" -Force
    }
}
    

See on line 6? We have a condition stating that if the $item.FileSystemObjectType -eq "File", then copy the files.

 

The results

Files copied, even the nested ones. And…. No folders! 🔥

If you wish to:

  • Move files (not copy) –> Use the Move-PnPFile cmdlet
  • Copy to a different library on the same site –> change the TargetUrl

 

Thanks for reading!

 

 

 

One Response to “Copy or Move Files (not folders) to another SharePoint Library or Site using PowerShell PnP

  • Great Veronica, how to handle copy the folder and structure? thanks in advance.

Leave a Reply to Eduardo Cancel reply

%d bloggers like this: