I need to copy document library to other site via powershell.

My structure of this document library is like this:

In a root si many folder, these folders can contains subfolder and these subfolder can contains next subfolder.

In each folder/subfolder can be a file (usually PDF) or a document set.

I found a script which recursively passes every folder and copy every item to the new site.

I have a problem that this script copy a Document set like a folder.

How Can I modify these script to store the structure - folder will be folder, Document Set will be Document Set?

I didn't find anything helpful :( I would like to store the all metadata :)

Thank you

    Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

   #Variables for Processing

    $SourceWeb = "SourceSite"

   $TargetWeb = "TargetSite"

   $web1 = Get-SPWeb $SourceWeb

   $web2 = Get-SPWeb $TargetWeb

    $SourceLibrary = "SourceDocumentLibrary"

    $TargetLibrary = "TargetDocumentLibrary"

   $SourceFolder = $web1.GetFolder($SourceLibrary)

   $TargetFolder = $web2.GetFolder($TargetLibrary)

    #Call the Function to Copy All Files
    Copy-Files $SourceFolder $TargetFolder

    #Custom Function to Copy Files from Source Folder to Target
    Function Copy-Files($SourceFolder, $TargetFolder)
    write-host "Copying Files from:$($SourceFolder.URL) to $($TargetFolder.URL)"
    #Get Each File from the Source
    $SourceFilesColl = $SourceFolder.Files

    #Iterate through each item from the source
    Foreach($SourceFile in $SourceFilesColl)
        #Copy File from the Source
        $NewFile = $TargetFolder.Files.Add($SourceFile.Name,  $SourceFile.OpenBinary(),$True)

        #Copy Meta-Data from Source
        Foreach($Field in $SourceFile.Item.Fields)
                    $NewFile.Item[$Field.InternalName] =      $SourceFile.Item[$Field.InternalName]

        Write-host "Copied File:"$SourceFile.Name

    #Process SubFolders
    Foreach($SubFolder in $SourceFolder.SubFolders)
        if($SubFolder.Name -ne "Forms")
            #Check if Sub-Folder exists in the Target Library!
            $NewTargetFolder = $TargetFolder.ParentWeb.GetFolder($SubFolder.Name)

            if ($NewTargetFolder.Exists -eq $false)
                #Create a Folder

                $NewTargetFolder = $TargetFolder.SubFolders.Add($SubFolder.Name)

            #Call the function recursively
            Copy-Files $SubFolder $NewTargetFolder

1 Answer 1


To work with document set you need to use the Microsoft.Office.DocumentManagement.DocumentSets dll. This TechNet has very good example how to copy move the document sets.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.