SharePoint Online: Move All Files from One Folder to Another using PowerShell

Requirement: Move All Files Between Folders in SharePoint Online using PowerShell

Move All Files from One Folder to Another in SharePoint Online using PowerShell

PowerShell to Move All Files from One Folder to Another in SharePoint Online:

If you’ve been using SharePoint Online for any length of time, you’re probably familiar with the basic file upload and download process. However, there may be times when you need to move files between folders on your site. When you are frequently moving files and folders around in SharePoint Online, It can be a little cumbersome to open the SharePoint Online site, navigate to the folder where you want to move the file or folder, and then move it into place.

Wouldn’t it be nice if there was an easy way to do this from PowerShell? This article will show you how to use PowerShell to quickly and easily move files between folders in SharePoint Online. Let’s get started!

How to move files between folders in SharePoint Online? Well, here is the PowerShell to move all files from one folder to another folder:

#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"

#Set Variables
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$ListName = "Documents"
#Relative URLs of Source and Destination Folders
$SourceFolderURL = "/sites/marketing/Shared Documents"
$TargetFolderURL = "/sites/marketing/Shared Documents/Archive"

#Get Credentials to connect
$Cred = Get-Credential

Try {
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

    #Get all items from source folder
    $List = $Ctx.Web.Lists.GetByTitle($ListName)
    $Query = [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery()
    $Query.FolderServerRelativeUrl = $SourceFolderURL
    $ListItems = $List.GetItems($Query)
    $Ctx.Load($ListItems)
    $Ctx.ExecuteQuery()
    
    #Move All Files from Source to Destination
    ForEach ($Item in $ListItems)
    {
        #Filter Files
        If($Item.FileSystemObjectType -eq [Microsoft.SharePoint.Client.FileSystemObjectType]::File)
        {
            $TargetFileUrl = $Item["FileRef"].ToString().Replace($SourceFolderURL,$TargetFolderURL)
            $Item.File.MoveTo($TargetFileUrl, [Microsoft.SharePoint.Client.MoveOperations]::Overwrite)
            $Ctx.ExecuteQuery()

            Write-host -f Green "File Moved to:"$TargetFileUrl
        }
    }
}
catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

This script moves all files from the source folder to the target folder. What if the source folder has sub-folders?

SharePoint Online: Move Files and Folders using PowerShell

This PowerShell script moves all files and sub-folders between given folders in a SharePoint Online document library. We can also move a folder between document libraries or sites with PnP PowerShell, as in How to move a Folder 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 Move-SPOFilesBetweenFolders
{
  param
    (
        [Parameter(Mandatory=$true)] [string] $SiteURL,
        [Parameter(Mandatory=$true)] [Microsoft.SharePoint.Client.Folder] $SourceFolder,
        [Parameter(Mandatory=$true)] [Microsoft.SharePoint.Client.Folder] $TargetFolder
    )
    Try {
        #Write-host "Copying Files from '$($SourceFolder.ServerRelativeUrl)' to '$($TargetFolder.ServerRelativeUrl)'"
        #Get all Files from the source folder
        $SourceFilesColl = $SourceFolder.Files
        $Ctx.Load($SourceFilesColl)
        $Ctx.ExecuteQuery()
 
        #Iterate through each file and move
        Foreach($SourceFile in $SourceFilesColl)
        {
            #Get all files from source Folder
            $SourceFile =$Ctx.Web.GetFileByServerRelativeUrl($SourceFile.ServerRelativeUrl)
            $Ctx.Load($SourceFile)
            $Ctx.ExecuteQuery()
             
            #Move File to destination
            $TargetFileUrl = $SourceFile.ServerRelativeUrl -Replace $SourceFolderURL,$TargetFolderURL
            $SourceFile.MoveTo($TargetFileUrl, [Microsoft.SharePoint.Client.MoveOperations]::Overwrite)
            $Ctx.ExecuteQuery()
 
            Write-host -f Green "File Moved 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
                $EnsureFolderURL = $SubFolder.ServerRelativeUrl -Replace $SourceFolderUrl, $TargetFolderUrl
                Try {
                        $Folder=$Ctx.web.GetFolderByServerRelativeUrl($EnsureFolderURL)
                        $Ctx.load($Folder)
                        $Ctx.ExecuteQuery()
                    }
                catch {
                        #Create Folder
                        if(!$Folder.Exists)
                        {
                            $Folder=$Ctx.Web.Folders.Add($EnsureFolderURL)
                            $Ctx.Load($Folder)
                            $Ctx.ExecuteQuery()
                            Write-host "New Folder Created:"$SubFolder.Name -f Yellow
                        }
                    }
                #Call the function recursively to move all files from source folder to target
                Move-SPOFilesBetweenFolders -SiteURL $SiteURL -SourceFolder $SubFolder -TargetFolder $Folder

                #Remove the Source Folder
                $SubFolder.Recycle() | Out-Null
                $Ctx.ExecuteQuery()
            }
        } 
    }
    Catch {
        write-host -f Red "Error Moving File:" $_.Exception.Message
    }
}
 
#Set Parameter values
$SiteURL="https://crescent.sharepoint.com/sites/marketing"
$SourceFolderURL ="/sites/marketing/shared Documents/2018"
$TargetFolderURL ="/sites/marketing/Shared Documents/2019"
 
#Setup Credentials to connect
$Cred= Get-Credential
 
#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
      
#Get the source and Target Folders
$SourceFolder=$Ctx.Web.GetFolderByServerRelativeUrl($SourceFolderURL)
$Ctx.Load($SourceFolder)
$TargetFolder=$Ctx.Web.GetFolderByServerRelativeUrl($TargetFolderURL)
$Ctx.Load($TargetFolder)
$Ctx.ExecuteQuery()

#Call the function 
Move-SPOFilesBetweenFolders -SiteURL $SiteURL -SourceFolder $SourceFolder -TargetFolder $TargetFolder

If you want to move a single file, use: SharePoint Online: Move a File between Document Libraries using PowerShell

PnP PowerShell to Move All Files and Folders Between Document Libraries

PnP PowerShell makes it much simpler! You can move document library contents to another SharePoint Online site with this PowerShell script:

#Config Variables
$SiteURL = "https://crescent.sharepoint.com/sites/Purchase"
$SourceLibraryURL = "Migration" #Site Relative URL from the current site
$TargetLibraryURL = "/sites/Marketing/Migration" #Server Relative URL of the Target Folder

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive

#Get all Items from the Document Library
$Items = Get-PnPFolderItem -FolderSiteRelativeUrl $SourceLibraryURL | Where {$_.Name -ne "Forms"}

#Move All Files and Folders Between Document Libraries
Foreach($Item in $Items)
{
    Move-PnPFile -SourceUrl $Item.ServerRelativeUrl -TargetUrl $TargetLibraryURL -AllowSchemaMismatch -Force -AllowSmallerVersionLimitOnDestination
    Write-host "Moved Item:"$Item.ServerRelativeUrl
}

Make sure you have the Target library created before running this script!

Salaudeen Rajack

Salaudeen Rajack - SharePoint Expert with Two decades of SharePoint Experience. Love to Share my knowledge and experience with the SharePoint community, through real-time articles!

3 thoughts on “SharePoint Online: Move All Files from One Folder to Another using PowerShell

  • Thanks for providing this script it looks great.
    Can the same script be used for moving files to a different site in the same tenant?
    Also is there a way to validate the number of files in the source (including versions) and the number moved to the destination? I guess I’m looking for logging that can display any errors encountered in the move?

    Reply
  • Thank you for this, do you have a way to move files to a folder with existing files on it?

    Reply
    • Do you mean, You want to avoid overwriting the file if that exists already? Use the flag [Microsoft.SharePoint.Client.MoveOperations]::none

      Reply

Leave a Reply

Your email address will not be published.