Tuesday, July 12, 2022

Copy Items from One List to Another List

 #Load SharePoint CSOM Assemblies

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"

 

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 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 - INTERNAL NAMES

            $ListItem["Title"] = $SourceItem["Title"]

            $ListItem["Title1"] = $SourceItem["Title"]

            $ListItem["Title2"] = $SourceItem["Title"]

            

            $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= "Sharepoint Site URL"

$SourceListName="List Name"

$TargetListName="List Name"

 

#Call the function to copy list items

Copy-ListItems -siteURL $SiteURL -SourceListName $SourceListName -TargetListName $TargetListName

No comments:

Post a Comment