Contents

Copy or Move files (not folders) to another library or Site using PowerShell

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.

/images/powershell-screenshots/copy-or-move-files-img1.png

/images/powershell-screenshots/copy-or-move-files-img2.png

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

Info
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
Both cmdlets are using the same parameters so choose one or the other depending on what you wish to do (copy or move).

Script

And with only a few lines, here we go…

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
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.

Results

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

/images/powershell-screenshots/copy-or-move-files-img3.png