Wednesday, June 3, 2020

PowerShell: Migrate SharePoint list content from one farm to other farm using CSOM

Leave a Comment
Scenario:
I met a scenario, where I need to migrate some list items (around 500+) from one farm (development) to another farm (Staging) and then to Production farm.

Ideal scenario probably would be to create list schema with content. However, in my current scenario I used CSOM for copying list items. Also in my scenario I just can't replace current content of destinate list item. I must have to just copy/move list items which are required for newly developed components.

Solution:

First I save list as list template along with content from source farm and create new list in destination farm using saved & imported list template definition. Then I delete list items which is not supposed to be copied. Although this can be skipped or cater through power shell script. However, due to quick delivery I wrote following power shell script which serve my purpose.

#Since I am doing for On-Premises, so I must have to import Client runtime for On-Premises
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"

#Here I am getting user credentials
$siteURL="http://SomeSiteUrl/"
$ctx=New-Object Microsoft.SharePoint.Client.ClientContext($siteURL)
$pwd=Read-Host -Prompt "Enter password" -AsSecureString
$creds=New-Object System.Net.NetworkCredential("domain\UserName",$pwd)
$ctx.Credentials=$creds

$sourceList=$ctx.Web.Lists.GetByTitle("[{ImportedListFromDestinationFarm}]")
$destList=$ctx.Web.Lists.GetByTitle("[{SourceListWhereDataNeedToCopied}]")
$sourceListItems=$sourceList.GetItems([Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery())
$fields=$sourceList.Fields
$ctx.Load($sourceListItems)
$ctx.Load($sourceList)
$ctx.Load($destList)
$ctx.Load($fields)
$ctx.ExecuteQuery() 

#Here I am making sure, fields of list item isn't hiddent, or not readonly & don't have attachment
#and then updating in destination list
foreach($item in $sourceListItems)
 {
 #Write-Host $item.ID
$listItemInfo=New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
$destItem=$destList.AddItem($listItemInfo)
foreach($field in $fields)
{
#Write-Host $field.InternalName "-" $field.ReadOnlyField
if((-Not($field.ReadOnlyField)) -and (-Not($field.Hidden)) -and ($field.InternalName -ne "Attachments") -and ($field.InternalName -ne "ContentType"))
{
#Write-Host $field.InternalName "-" $item[$field.InternalName]
$destItem[$field.InternalName]=$item[$field.InternalName]
$destItem.update()
} }}
$ctx.ExecuteQuery()
If You Enjoyed This, Take 5 Seconds To Share It

0 comments: