Wednesday, August 13, 2014

Copy Documents Between Two Libraries With Metadata Using PowerShell

The PowerShell script below shows you how to copy files and their metadata from one library to another.

Keywords: SharePoint, SharePoint 2010, SharePoint 2013, PowerShell

Add-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue

#get source list and destination list
$web = get-spWeb  "http://targetURL/"
$srcList = $web.Lists["srcLib" ]
$dstList = $web.Lists["dstLib"]

#get the content type
$ct = $srcList.ContentTypes["TargetCT"]

#get the root folder and items/files
$srcRootFolder = $srcList.RootFolder
$srcItems = $srcRootFolder.files


#iterate over files and copy them over with properties.
foreach($srcItem in $srcItems)
{
      Try
      {
             #copy over the files
             $sBytes = $srcItem.OpenBinary()
             $dstItem = $dstList.RootFolder.Files.Add($srcItem.Name, $sBytes, $true).Item
           
            #copy over files properties
            foreach($spField in $ct.Fields)
        {
          if ($spField.ReadOnlyField -ne $True )
          {
              $dstItem[$spField.InternalName] = $srcItem.Item[$spField.InternalName];
          }
             
        }
     
        $dstItem.Update()

      }
      Catch [system.exception]
      {
             $_.Exception.Message
      }
     
      Finally
      {
             
      }


}

No comments:

Post a Comment