In this article, you will learn how to copy list items from one list to another list using CSOM Powershell on SharePoint. This is mainly focused on using PowerShell scripts for any SharePoint 2013 / SharePoint 2016 / SharePoint online sites.
The following prerequisites need to be executed before going for any operations using CSOM PowerShell on SharePoint sites.
- Add the references using the Add-Type command with the necessary reference paths. The necessary references are Microsoft.SharePoint.Client.dll, Microsoft.SharePoint.Client.Runtime.dll.
- Initialize client context object with the site URL.
- If you are trying to access SharePoint Online site then you need to setup the site credentials with credentials parameter and load it to the client context.
- If you are trying to access the SharePoint on premise site then the credentials parameter is not required to be set to the context but you need to run the code on the respective SharePoint Server or you need to pass the network credentials and set the context.
We will see how we can copy the list items from one list to another list. Here, the list should have identical SharePoint list fields. The values will be copied only if the corresponding fields are present on both source and destination lists.
- Using the context, access the web.
- From the web, get the source list and destination list using the list names.
- From the source list, get the items using the query object. The query object should be initiated to access the necessary source list items. In this case, I have used All Items query to get all the items.
- Load and execute the query.
- For destination list, create list item creation information object and add the object to the destination list.
- Access all the fields using for each loop from the source list.
- For every field, check whether field is not read only field. If it is read only field, then we will not be able to write it to the destination list.
- Also the fields should not be hidden, attachment or content type, since the write operations will not be possible on these fields.
- For other custom fields, execute the copy operations and update the item.