Created
December 3, 2018 07:24
-
-
Save kewalaka/7a7daca65862f86e8e5079895ebb246c to your computer and use it in GitHub Desktop.
Copy list items between sites, list must already exist. Target list is added to, not cleared first. Uses PowerShell PnP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$sourceSite = 'https://mydomain.sharepoint.com/sites/mysourcesite' | |
$targetSite = 'https://mydomain.sharepoint.com/sites/mytargetsite' | |
$listsToCopy = @('List1', 'List2') | |
# install Powershell patterns and practices (PnP) module, if not already installed | |
if ($null -eq (Get-InstalledModule SharePointPnPPowerShellOnline -ErrorAction SilentlyContinue)) { | |
install-module SharePointPnPPowerShellOnline -AllowClobber -SkipPublisherCheck -Scope CurrentUser | |
} | |
# connect to source site | |
$source = Connect-PnPOnline -Url $sourceSite -UseWebLogin -ReturnConnection | |
if (-not (Get-PnPContext)) { | |
Write-Output "Can't connect to source $($sourceSite)" | |
return | |
} | |
# connect to target site | |
$target = Connect-PnPOnline -Url $targetSite -UseWebLogin -ReturnConnection | |
if (-not (Get-PnPContext)) { | |
Write-Output "Can't connect to destination $($targetSite)" | |
return | |
} | |
Write-Output "Copying from $($source.Url) to $($target.Url)" | |
# copy lists | |
foreach ($list in $listsToCopy) { | |
Write-Output "Fetching list: $list" | |
# get all the fields except hidden, readonly fields, or the contenttype or attachments | |
$fields = Get-PnPField -List $list | | |
Where-Object {-not ($_.Hidden -or $_.ReadOnlyField)} | | |
Where-Object {-not ($_.InternalName -eq 'ContentType' -or $_.InternalName -eq 'Attachments') | |
} | |
# keep track of items done for progress | |
$i = 1 | |
# connect to source - page 5000 items at a time | |
$items = Get-PnPListItem -List $list -Connection $source -PageSize 5000 -ScriptBlock { | |
Param($items) $items.Context.ExecuteQuery() | |
$totalCount = $items.Count | |
foreach ($item in $items) { | |
# create a hash table of the form: @{"Title" = $item["Title"]} | |
$fieldsToCopy = @{} | |
foreach ($field in $fields) { | |
$fieldname = $field[0].InternalName | |
$fieldsToCopy += @{$($fieldname) = $($item[$fieldname])} | |
} | |
Write-Progress -Activity "Copying list $list" -PercentComplete (($i / $totalCount) * 100) -CurrentOperation "Item # $($i)" | |
# add the item to the target site | |
Add-PnPListItem -List $list -Values $fieldsToCopy -Connection $target | |
$i++ | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment