[CSOM] Copy list items from one SPO list to another
So, here goes:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
#Load SharePoint CSOM Assemblies Add-Type -Path "C:\CSOM\Microsoft.SharePoint.Client.dll" Add-Type -Path "C:\CSOM\Microsoft.SharePoint.Client.Runtime.dll" Function Copy-ListItems() { param ( [Parameter(Mandatory=$true)] [string] $SiteURL, [Parameter(Mandatory=$true)] [string] $SourceListName, [Parameter(Mandatory=$true)] [string] $TargetListName ) Try { #Setup Credentials to connect $Cred = Get-Credential $Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password) #Setup the context $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL) $Ctx.Credentials = $Cred #Get the Source List and Target Lists $SourceList = $Ctx.Web.Lists.GetByTitle($SourceListName) $TargetList = $Ctx.Web.Lists.GetByTitle($TargetListName) #Get All Items from Source List $SourceListItems = $SourceList.GetItems([Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery()) $Ctx.Load($SourceListItems) $Ctx.ExecuteQuery() #Get All fields from Source List & Target List $SourceListFields = $SourceList.Fields $Ctx.Load($SourceListFields) $TargetListFields = $TargetList.Fields $Ctx.Load($TargetListFields) $Ctx.ExecuteQuery() #Get each column value from source list and add them to target ForEach($SourceItem in $SourceListItems) { $NewItem =New-Object Microsoft.SharePoint.Client.ListItemCreationInformation $ListItem = $TargetList.AddItem($NewItem) #Map each field from source list to target list Foreach($SourceField in $SourceListFields) { #Skip Read only, hidden fields, content type and attachments If((-Not ($SourceField.ReadOnlyField)) -and (-Not ($SourceField.Hidden)) -and ($SourceField.InternalName -ne "ContentType") -and ($SourceField.InternalName -ne "Attachments") ) { $TargetField = $TargetListFields | where { $_.Internalname -eq $SourceField.Internalname} if($TargetField -ne $null) { #Copy column value from source to target $ListItem[$TargetField.InternalName] = $SourceItem[$SourceField.InternalName] } } } $ListItem.update() $Ctx.ExecuteQuery() } write-host -f Green "Total List Items Copied from '$SourceListName' to '$TargetListName' : $($SourceListItems.count)" } Catch { write-host -f Red "Error Copying List Items!" $_.Exception.Message } } #Set Parameters $SiteURL= https://tenant.sharepoint.com/sites/DOCTEST1 $SourceListName="TESTLIST2222" $TargetListName="Test List" #Call the function to copy list items Copy-ListItems -siteURL $SiteURL -SourceListName $SourceListName -TargetListName $TargetListName |
Enjoy!
