Monday, November 30, 2015

Update the Document Library Items from one library to another library

Below script is an example for updating the Items from one document library to another document library.

Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue 
try
{
   $srcListSiteUrl = "http://mydomain.com/en-us/"
   $SourceListName = "Pages"     
   
   $dstListSiteUrl = "http://mydomain.us.com/en-us/"
   $DestinationListName = "Pages"
   
   $keyColumnInternalName = "FileLeafRef"     
   $sourceListWeb = Get-SPWeb -identity $srcListSiteUrl    
   $sourceListUrl = $sourceListWeb.ServerRelativeUrl + "/" +$SourceListName;     
   $dstListWeb = Get-SPWeb -identity $dstListSiteUrl    
   $destinationListUrl = $dstListWeb.ServerRelativeUrl + "/" + $DestinationListName;
   $SourceList = $sourceListWeb.GetList($sourceListUrl);   
   $DestinationList = $dstListWeb.GetList($destinationListUrl); 

     
   $filterQuery = '<Query>
<OrderBy>
<FieldRef Name = "Title" />
</OrderBy>
</Query>'     
    

$CategoryQuery = new-object Microsoft.SharePoint.SPQuery
$CategoryQuery.Query = $filterQuery

    $sourceSPListItemCollection = $SourceList.GetItems($CategoryQuery);

    foreach($srcListItem in $sourceSPListItemCollection) 
    {           
        $keyValue = $srcListItem[$keyColumnInternalName]

        $camlQuery ='<Where><Eq><FieldRef Name="FileLeafRef" /><Value Type="Text">'+$keyValue+'</Value> </Eq> </Where>'
        $spQuery = new-object Microsoft.SharePoint.SPQuery
        $spQuery.Folder = $DestinationList.RootFolder.SubFolders["Foldername"]
        $spQuery.Query = $camlQuery
        $spQuery.RowLimit = 1
        $destItemCollection = $DestinationList.GetItems($spQuery)
   if($destItemCollection.Count -gt 0)
   {
   foreach($dstListItem in $destItemCollection) 
   {  
                           $url = [String]::Format("{0}{1}",$dstListWeb.Url + "/", $dstListItem.File.Url)
                           $file = $dstListWeb.GetFile($url)
                           $file.CheckOut()
           $fileItem = $file.Item
                           Write-Host $fileItem.Name is updating Please wait ...........

   $fileItem["CustomText"] = $srcListItem["Introduction"]
                            $fileItem["Author"] = $srcListItem["Author"]                
   $fileItem.Update() 
                            $file.CheckIn("Updated Value")
            $file.Publish("Publish through Powershell")
                    } 
   }        
    }
}
catch 
    write-host $_.exception 
finally 
{        
    if($sourceListWeb -ne $null){$sourceListWeb.Dispose()}
    if($dstListWeb -ne $null){$dstListWeb.Dispose()}
}

No comments:

Post a Comment