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?
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
    sharepoint online copy document
  • This opens information panel in the right. Select the target library to which your file 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.
    sharepoint online copy file
  • 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 file will be copied momentarily.
    sharepoint online powershell copy documents

SharePoint Online: PowerShell to Copy Documents
Here is the PowerShell to copy files in 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 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)!

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://crescenttech.sharepoint.com/sites/Marketing"
$SourceFileURL="https://crescenttech.sharepoint.com/sites/Marketing/Shared Documents/Discloser Asia.doc"
$TargetFileURL="https://crescenttech.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, lets copy all files along with its 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:
#Config Variables
$SiteURL = "https://crescenttech.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
The Copy-PnPFile cmdlet can be used to copy a file to same library, between different libraries in different site collections!
#Config Variables
$SiteURL = "https://crescenttech.sharepoint.com/sites/marketing"
$SourceURL= "Shared Documents/Discloser Asia.doc"
$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) #-UseWebLogin

#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
#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"
SharePoint Online: Copy File Between Document Libraries using PowerShell SharePoint Online: Copy File Between Document Libraries using PowerShell Reviewed by Salaudeen Rajack on February 04, 2017 Rating: 5

No comments:

Please Login and comment to get your questions answered!

Powered by Blogger.