2013-11-22

I know there are a ton of tools out there for moving content within SharePoint.  Heck, SharePoint itself even kind of gives you some tools of it’s own.  Presented here is MY quick and dirty way of moving documents from one location to another while retaining the Modified, Modified By, Created By, and Created fields.   Additional fields could be added to the script using the same method that allows for those four authorship fields to be transferred.   This script WILL recurse through all folders and will create any existing folder structure that exists within your library, even if Best Practice Billy says you should be using metadata to sort your data instead…

function create-fileitems()
{
[CmdletBinding()]
param(
[Parameter(position=1, mandatory=$true, parametersetname="Default")] [Microsoft.SharePoint.SPSite]$SourceList, 
[Parameter(position=2, mandatory=$true, parametersetname="Default")] [Microsoft.SharePoint.SPSite]$DestinationList, 
)
$src = $SourceList
$tgt = $DestinationList
$AllFolders = $src.Folders
$srcRootFolder = $src.RootFolder
$allfiles = $src.items
$RootItems = $srcRootFolder.files
$destRootFolder = $tgt.RootFolder
foreach($RootItem in $RootItems)
{
$sBytes = $RootItem.OpenBinary()
$dFile = $tgt.RootFolder.Files.Add($RootItem.Name, $sBytes, $true)
$AllFields = $RootItem.Item.Fields | ? {!($_.sealed)}
$ditem = $dfile.Item
$ditem["Modified"] = $RootItem.TimeLastModified.ToLocalTime()
$ditem["Created"] = $RootItem.TimeCreated.ToLocalTime()
$ditem["Author"] = $RootItem.Author
$ditem["Editor"] = $RootItem.ModifiedBy
$dFile.Update()
$ditem.Update()
write-host "File Copy:"$dfile.Name" - Complete"
}
foreach($Folder in $AllFolders)
{
$srcFolderURL = $folder.url
$destFolderURL = $srcFolderURL
$destFolderURL = $destFolderURL -replace $srcRootFolder, $destRootFolder
$srcItems = $Folder.folder.files
if(!($tgt.Folders | ? {$_.URL -eq $destFolderURL}))
{ 
$parentFolderURL = $folder.folder.parentfolder.serverrelativeurl
$parentFolderDestination = "KB/" + $destRootFolder
$parentFolderURL = $parentFolderURL -replace $srcRootFolder, $parentFolderDestination
$newFolder = $tgt.Additem($parentFolderURL,[Microsoft.SharePoint.SPFileSystemObjectType]::Folder,$folder.name)
$newFolder.Update()
write-host "Folder Creation:"$destFolderURL" - Complete"
}
$destFolder = $tgt.Folders | ? {$_.url -eq $destFolderURL}
if($Folder.Folder.Files.count -gt 0)
{
$srcItems = $Folder.folder.Files
foreach ($item in $srcItems)
{
$Relative = $Item.URL
$TargetItem = $AllFiles | ? {$_.URL -eq $Relative}
$sBytes = $TargetItem.File.OpenBinary()
$dFile = $destFolder.Folder.Files.Add($TargetItem.Name, $sBytes, $true)
$ditem = $dfile.Item
$ditem["Modified"] = $Item.TimeLastModified.ToLocalTime()
$ditem["Created"] = $Item.TimeCreated.ToLocalTime()
$ditem["Author"] = $Item.Author
$ditem["Editor"] = $Item.ModifiedBy
$dFile.Update()
$ditem.Update()
write-host "File Creation:" $dfile.name" - Complete"
}
}
}
}
}

 

About the author 

Lucas Struck