How to Efficiently Copy or Move Files in SharePoint

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 document 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”.

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 😉

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
    }
}

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

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

Discover more from Veronique's Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading