Migrate data from Source to Destination Library without changing the audit trail column values– PowerShell

Add-PSSnapin "Microsoft.SharePoint.Powershell" -ErrorAction SilentlyContinue

$sourceWebURL = "http://srcurl"
$sourceListName = "Source"

$destinationWebURL = "http://desurl"
$destinationListName = "Destination"

$spSourceWeb = Get-SPWeb $sourceWebURL
$spDestinationWeb = Get-SPWeb $destinationWebURL

$spSourceList = $spSourceWeb.Lists[$sourceListName]
$spDestinationList = $spDestinationWeb.Lists[$destinationListName]

$RootFolder = $spDestinationList.RootFolder

$spSourceItems = $spSourceList.Items

ForEach ($item in $spSourceItems)
{

Try
{

$binary = $item.File.OpenBinary();

if ($binary -ne $null)
{
$sBytes = $item.File.OpenBinary()

[Microsoft.SharePoint.SPFile]$spFile = $RootFolder.Files.Add($item.Name, $sBytes, $true)
$theItem = $spFile.Item
write-host -f Green "...Success!"
$pos = $item["Author"].IndexOf("#")
$userAuthorLogin = "amat\"+$item["Author"].Substring($pos+1)

$pos1 = $item["Editor"].IndexOf("#")
$userEditorLogin = "amat\"+$item["Editor"].Substring($pos+1)

$dateCreatedToStore = Get-Date $item["Created"]
$dateModifiedToStore = Get-Date $item["Modified"]

$userAuthor = Get-SPUser -Web $spDestinationWeb | ? {$_.userlogin -eq $userAuthorLogin}
$userAuthorString = "{0};#{1}" -f $userAuthor.ID, $userAuthor.UserLogin.Tostring()

$userEditor = Get-SPUser -Web $spDestinationWeb | ? {$_.userlogin -eq $userEditorLogin}
$userEditorString = "{0};#{1}" -f $userEditor.ID, $userEditor.UserLogin.Tostring()

#Sets the created by field
$theItem["Author"] = $userAuthorString
$theItem["Created"] = $dateCreatedToStore

#Set the modified by values
$theItem["Editor"] = $userEditorString
$theItem["Modified"] = $dateModifiedToStore

#Store changes without overwriting the existing Modified details.
$theItem.UpdateOverwriteVersion()

write-host -f Green "...Success!"

}

}
Catch [system.exception]
{
write-host "Caught a system exception for " $item.ID $item.Title
}
Finally
{
$spSourceWeb.Dispose();
$spDestinationWeb.Dispose();
}

}

Advertisements

About Joseph Velliah
As a SharePoint Developer my professional interests tend to be technical and SharePoint focused. I run a blog at "SP RIDER" where you can expect to read HOW TOs and scenarios that I run into during my day to day job. I hope my posts will give back a little to the community that is helped me.

Comments are closed.

%d bloggers like this: