Keywords: SharePoint, SharePoint 2010, SharePoint 2013, PowerShell
Add-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue
function CopyFilesInFolder($srcFolder , $dstFolder)
{
#get files
inside srcFolder
$srcItems = $srcFolder.files
$nCount = $srcItems.Count
$i= $nCount - 1
#start copying
files from srcFodler to dstFolder
foreach($srcItem in $srcItems )
{
Try
{
$srcItem.CopyTo($dstFolder.ServerRelativeUrl
+ "/" + $srcItem.Name ,$true)
$newFileLoc = $dstFolder.ServerRelativeUrl
+ "/" + $srcItem.Name
Write-host $newFileLoc
}
Catch [system.exception]
{
$_.Exception.Message
}
Finally
{
}
}#end while
#iterate over
each subfolder inside $srcFolder
#create equivalent
subfolder under $dstFolde
#call the CopyFilesInFolder
foreach($srcSubFolder in $srcFolder.SubFolders)
{
if($srcSubFolder.Name -ne "Forms")
{
$dstSubFolder = $dstFolder.SubFolders.Add($srcSubFolder.Name)
CopyFilesInFolder -srcFolder $srcSubFolder -dstFolder $dstSubFolder
}
}
}#end function
#get source list and destination list
$web = get-spWeb "http://URl/"
$srcList = $web.Lists["srcLib" ]
$dstList = $web.Lists["dstLib"]
#get the root folder and
items/files
$srcRootFolder = $srcList.RootFolder;
$dstRootFolder = $dstList.RootFolder;
CopyFilesInFolder -srcFolder $srcRootFolder -dstFolder $dstRootFolder
Enjoy
Been messing with a script to copy files and folders from one document library to another with powershell, and this was the missing piece to get it working as needed! Thank you
ReplyDelete