How to Copy a File in SharePoint Online Document Library?
Here is the PowerShell to copy files in SharePoint Online document library.
- Navigate to your SharePoint Online document library. Right click on the file to copy >> Select "Copy To" menu item
- This opens information panel in the right. Select the target library to which your needs to be copied. You can select 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 tool bar and your fill will be copied momentarily.
Here is the PowerShell to copy files in SharePoint Online document library.
Function Copy-FileThis method copies given document either to same document library or different document library with in the same site along with its metadata fields (Except: Created by and Modified by fields - and obviously, the columns should exists in both libraries)!
{
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 Users2.xlsx"
#Call the function
Copy-File -SiteURL $SiteURL -SourceFileURL $SourceFileURL -TargetFileURL $TargetFileURL