SharePoint Online: Copy File Between Document Libraries using PowerShell
Requirement: SharePoint Online PowerShell to copy files from one library to another
How to Copy a File in SharePoint Online Document Library?
Are you looking for a way to copy files in SharePoint Online? This guide will show you how to use the “Copy to” feature to quickly and easily copy files between your sites, document libraries, or folders. We’ll also show you how to use PowerShell to copy files between locations in your SharePoint Online environment.
Here is how to copy file in SharePoint Online Document Library:
- Navigate to your SharePoint Online document library. Right-click on the file to copy >> Select “Copy To” menu item. You can also use “Copy To” button in the toolbar.
- This opens the information panel in the right. Select the target library to which your file needs to be copied. You can select the current library, any other library in the current site, or even a library in any different site collection.
- Pick the library and click on “Copy Here” button to start copying the file.
- You’ll see the “Copying” message in the toolbar and your file will be copied momentarily.
The same procedure applies to move operations as well.
When you copy files, Metadata like created by, modified are not preserved. Also, the Version history is not maintained when the file is copied. Whereas Move preserves the metadata and versions.
Do you often find yourself needing to copy files from your SharePoint Online environment into other locations? PowerShell can help make this process quick and easy!
SharePoint Online: PowerShell to Copy Documents
PowerShell is a powerful tool that you can use to automate tasks in SharePoint Online. Let’s see how to use PowerShell to copy files in SharePoint Online. Here is the PowerShell to copy a file in the SharePoint Online document library:
Function Copy-File
{
param
(
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [string] $SourceFileURL,
[Parameter(Mandatory=$true)] [string] $TargetFileURL
)
Try {
$Cred= Get-Credential
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = $Credentials
#Get the source file
$SourceFile =$Ctx.Web.GetFileByServerRelativeUrl($SourceFileURL)
$Ctx.Load($SourceFile)
$Ctx.ExecuteQuery()
#Copy File to destination
$SourceFile.CopyTo($TargetFileURL, $True)
$Ctx.ExecuteQuery()
Write-Host "File Copied from '$SourceFileURL' to '$TargetFileURL'" -F Green
}
Catch {
write-host -f Red "Error Copying File!" $_.Exception.Message
}
}
#Set Parameter values
$SiteURL="https://crescent.sharepoint.com/"
$SourceFileURL="/Project Documents/Active Users.xlsx"
$TargetFileURL="/Project Documents/Active UsersV2.xlsx"
#Call the function
Copy-File -SiteURL $SiteURL -SourceFileURL $SourceFileURL -TargetFileURL $TargetFileURL
This method copies the given document either to the same document library or a different document library within the same site along with its metadata fields (Except: Created by and Modified by fields – and obviously, the columns should exist in both libraries)!
SharePoint Online: Copy files between site collections using PowerShell
Here is the PowerShell to copy files from one library to another in SharePoint Online:
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
#Function to Copy a File
Function Copy-SPOFile([String]$SiteURL, [String]$SourceFileURL, [String]$TargetFileURL)
{
Try{
#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
#Copy the File
$MoveCopyOpt = New-Object Microsoft.SharePoint.Client.MoveCopyOptions
$Overwrite = $True
[Microsoft.SharePoint.Client.MoveCopyUtil]::CopyFile($Ctx, $SourceFileURL, $TargetFileURL, $Overwrite, $MoveCopyOpt)
$Ctx.ExecuteQuery()
Write-host -f Green "File Copied Successfully!"
}
Catch {
write-host -f Red "Error Copying the File!" $_.Exception.Message
}
}
#Set Config Parameters
$SiteURL="https://Crescent.sharepoint.com/sites/Marketing"
$SourceFileURL="https://Crescent.sharepoint.com/sites/Marketing/Shared Documents/Discloser Asia.doc"
$TargetFileURL="https://Crescent.sharepoint.com/Shared Documents/Discloser Asia.doc"
#Get Credentials to connect
$Cred= Get-Credential
#Call the function to Copy the File
Copy-SPOFile $SiteURL $SourceFileURL $TargetFileURL
Copy All Files from One Document Library to Another using PowerShell:
This time, let’s copy all files along with their folder-subfolder structure.
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
Function Copy-AllFiles
{
param
(
[Parameter(Mandatory=$true)] [string] $SiteURL,
[Parameter(Mandatory=$true)] [Microsoft.SharePoint.Client.Folder] $SourceFolder,
[Parameter(Mandatory=$true)] [Microsoft.SharePoint.Client.Folder] $TargetFolder
)
Try {
#Get all Files from the source folder
$SourceFilesColl = $SourceFolder.Files
$Ctx.Load($SourceFilesColl)
$Ctx.ExecuteQuery()
#Iterate through each file and copy
Foreach($SourceFile in $SourceFilesColl)
{
#Get the source file
$SourceFile =$Ctx.Web.GetFileByServerRelativeUrl($SourceFile.ServerRelativeUrl)
$Ctx.Load($SourceFile)
$Ctx.ExecuteQuery()
#Copy File to destination
$TargetFileURL = $TargetFolder.ServerRelativeUrl+"/"+$SourceFile.Name
$SourceFile.CopyTo($TargetFileURL, $True)
$Ctx.ExecuteQuery()
Write-host -f Green "Copied File '$($SourceFile.ServerRelativeUrl)' to '$TargetFileURL'"
}
#Process Sub Folders
$SubFolders = $SourceFolder.Folders
$Ctx.Load($SubFolders)
$Ctx.ExecuteQuery()
Foreach($SubFolder in $SubFolders)
{
If($SubFolder.Name -ne "Forms")
{
#Prepare Target Folder
$TargetFolderURL = $SubFolder.ServerRelativeUrl -replace $SourceLibrary.RootFolder.ServerRelativeUrl, $TargetLibrary.RootFolder.ServerRelativeUrl
Try {
$Folder=$Ctx.web.GetFolderByServerRelativeUrl($TargetFolderURL)
$Ctx.load($Folder)
$Ctx.ExecuteQuery()
}
catch {
#Create Folder
if(!$Folder.Exists)
{
$Folder=$Ctx.Web.Folders.Add($TargetFolderURL)
$Ctx.Load($Folder)
$Ctx.ExecuteQuery()
Write-host "Folder Added:"$SubFolder.Name -f Yellow
}
}
#Call the function recursively
Copy-AllFiles -SiteURL $SiteURL -SourceFolder $SubFolder -TargetFolder $Folder
}
}
}
Catch {
write-host -f Red "Error Copying File!" $_.Exception.Message
}
}
#Set Parameter values
$SiteURL="https://crescent.sharepoint.com"
$SourceLibraryName="Project Documents"
$TargetLibraryName="Documents"
#Setup Credentials to connect
$Cred= Get-Credential
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = $Credentials
#Get the source library and Target Libraries
$SourceLibrary = $Ctx.Web.Lists.GetByTitle($SourceLibraryName)
$Ctx.Load($SourceLibrary)
$Ctx.Load($SourceLibrary.RootFolder)
$TargetLibrary = $Ctx.Web.Lists.GetByTitle($TargetLibraryName)
$Ctx.Load($TargetLibrary)
$Ctx.Load($TargetLibrary.RootFolder)
$Ctx.ExecuteQuery()
#Call the function
Copy-AllFiles -SiteURL $SiteURL -SourceFolder $SourceLibrary.RootFolder -TargetFolder $TargetLibrary.RootFolder
PnP PowerShell to Copy a File in SharePoint Online:
Copying a file in the SharePoint Online document library each time can be tedious! Here is how to automate the process of copying files in SharePoint Online using PowerShell.
#Config Variables
$SiteURL = "https://Crescent.sharepoint.com/sites/marketing"
$SourceURL= "Shared Documents/Discloser Asia.doc"
$TargetURL = "Shared Documents/Discloser Asia-v2.doc"
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)
#Copy File to same document library
Copy-PnPFile -SourceUrl $SourceURL -TargetUrl $TargetURL -Force
PowerShell to Copy a File Between Folders in SharePoint Online
Here is a PowerShell example for copying a file from one folder to another folder:
#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$SourceURL = "/sites/marketing/Shared Documents/Active/SRS.docx"
$TargetURL = "/sites/marketing/Shared Documents/Categorized/SRS.docx"
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive
#Copy All Files and Folders from one folder to another
Copy-PnPFile -SourceUrl $SourceURL -TargetUrl $TargetURL -Force
The Copy-PnPFile cmdlet can be used to copy a file to the same library, between different libraries in different site collections!
#Config Variables
$SiteURL = "https://Crescent.sharepoint.com/sites/marketing"
$SourceURL= "Shared Documents/Discloser Asia.doc" #Site Relative path
$TargetURL = "/Sites/Sales/Shared Documents/Discloser Asia-v2.doc"
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)
#Copy File to another site collection
Copy-PnPFile -SourceUrl $SourceURL -TargetUrl $TargetURL -Force
If you need to copy files between different site collections, use: SharePoint Online: Copy Files Between Site Collections using PowerShell
Copy All Files and Folders Between Document Libraries using PnP PowerShell
What if you want to copy all files and sub-folders between two folders (or document libraries)?
#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$SourceFolderURL = "/sites/marketing/Shared Documents"
$TargetFolderURL = "/sites/marketing/Project Document"
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential) #-Interactive
#Copy All Files and Folders from one folder to another
Copy-PnPFile -SourceUrl $SourceFolderURL -TargetUrl $TargetFolderURL -SkipSourceFolderName -Force
PnP PowerShell to Copy All Files and Folders Between Document Libraries with Metadata
Want to preserve the metadata while copying all items between libraries? No problem! Let me show you how to create a simple PowerShell script that you can use to copy files in SharePoint Online.
#Function to copy all Items from one library to another
Function Copy-AllDocuments($SourceLibraryName, $TargetLibraryName)
{
#Get Source and Target Libraries
$SourceLibrary = Get-PnPList -Identity $SourceLibraryName -Includes RootFolder
$TargetLibrary = Get-PnPList -Identity $TargetLibraryName -Includes RootFolder
#Copy All Files and Folders from Source to Target Library
Copy-PnPFile -SourceUrl $SourceLibrary.RootFolder.ServerRelativeUrl -TargetUrl $TargetLibrary.RootFolder.ServerRelativeUrl -OverwriteIfAlreadyExists -Force -SkipSourceFolderName
#Get All Items from Source Library
$SourceItems = Get-PnPListItem -List $SourceLibraryName
$TargetItems = Get-PnPListItem -List $TargetLibraryName
#Get All Items in the Source Library
ForEach($SourceItem in $SourceItems)
{
#Get Metadata from Source Items
$Metadata = @{
'Title' = $SourceItem.FieldValues.Title
'Created'= $SourceItem.FieldValues.Created.DateTime
'Modified' = $SourceItem.FieldValues.Modified.DateTime
'Author' = $SourceItem.FieldValues.Author.Email
'Editor' = $SourceItem.FieldValues.Editor.Email
}
#Update Metadata in Target Items
ForEach($TargetItem in $TargetItems)
{
If($SourceItem.FieldValues.FileLeafRef -eq $TargetItem.FieldValues.FileLeafRef)
{
Set-PnPListItem -List $TargetLibrary -Identity $TargetItem.Id -Values $Metadata | Out-Null
}
}
}
}
#Connect to PnP Online
$SiteURL = "https://crescent.sharepoint.com/sites/marketing/"
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)
#Call the function to copy all files between document libraries
Copy-AllDocuments "Project Documents" "Temp"
To copy an entire document library to another site in SharePoint Online, use: SharePoint Online Copy Document library to another site PowerShell
I need to retain unique permissions set on all files and folders. Can your code accomplish that?
You can copy permissions between any SharePoint Objects such as Sites, Lists and Libraries, Files-Folders, etc. Here is the reference: How to Copy Permission between Folders in SharePoint Online using PowerShell?
So for my need – i am trying to copy(word docs) a specific combinations of files only from one site collection to another folder in different site collection along with metadata in online environment.Also the word doc has huge metadata list that need to copy along with file.Is it possible to specify that long list of metadata in script to copy and there are nearly different content types.So each time while copying we need to modify the script along with metadata of word doc
and then run the script
Please advise.