Wednesday, 26 September 2018

Powershell - copy files from on document library to another keep the original modified by and created by

Copy files from one document library to another document library within the same site collection.

script

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

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

    #Iterate through each items
    Foreach($SourceFile in $SourceFilesColl)
    {
        #Copy File from the Source
        $NewFile = $TargetFolder.Files.Add($SourceFile.Name, $SourceFile.OpenBinary(),$True)
     
       #Copy updated required fields
        $ditem =  $NewFile.Item
        $ditem["Modified"] =$SourceFile.TimeLastModified.ToLocalTime()
        $ditem["Created"] = $SourceFile.TimeCreated.ToLocalTime()
        $ditem["Author"] = $SourceFile.Author
        $ditem["Editor"] = $SourceFile.ModifiedBy

        #Copy Meta-Data
        Foreach($Field in $SourceFile.Item.Fields)
        {

            If(!$Field.ReadOnlyField)
            {
                if($NewFile.Item.Fields.ContainsField($Field.InternalName))
                {
                    $NewFile.Item[$Field.InternalName] = $SourceFile.Item[$Field.InternalName]
                }
            }
        }
        #Update
        $NewFile.Item.UpdateOverwriteVersion()
   
        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
            $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
        }
    }
}

#Variables
$WebURL="https://portal.peelschools.org/My School/1553"
$SourceLibrary ="Shared Documents Area"
$TargetLibrary = "New"

#Get Objects
$Web = Get-SPWeb $WebURL
$SourceFolder = $Web.GetFolder($SourceLibrary)
$TargetFolder = $Web.GetFolder($TargetLibrary)

#Call the Function
Copy-Files $SourceFolder $TargetFolder


powershell-in-sharepoint.html#ixzz5S8r4cB00

No comments:

Post a Comment