Copy Files from SharePoint Library Folder to Another SharePoint Library Folder

$varSourceWebUrl="http://team/sites/teamsite1"
$varTargetWebUrl="http://team/sites/teamsite2"
$varSourceLibraryName = "Shared Documents"
$varTargetLibraryName = "Shared Documents"
$varSourceFolderUrl = "http://team/sites/teamsite1/Shared Documents/Subfolder/"
$varTargetParentFolderUrl = "http://team/sites/teamsite2/Shared Documents"

 $varSourceWeb = Get-SPWeb $varSourceWebUrl
 $varTargetWeb = Get-SPWeb $varTargetWebUrl 
 $varSourceLibrary = $varSourceWeb.Lists[$varSourceLibraryName]
 $varTargetLibrary = $varTargetWeb.Lists[$varTargetLibraryName]
 $varSourceFolder = $varSourceWeb.GetFolder($varSourceFolderUrl) 
 $varTargetFolder = $varTargetWeb.GetFolder($varTargetFolderUrl)
 $varTargetFolderParent = $varTargetWeb.GetFolder($varTargetParentFolderUrl)
 $varTargetFolderName =$varTargetFolder.Name
 if(!$varTargetFolder.Exists)
 {
 $varTargetFolder = $varTargetLibrary.AddItem($varTargetFolderParent,[Microsoft.SharePoint.SPFileSystemObjectType]::Folder,$varTargetFolderName)
 $varTargetFolder.Update()
 }
 $varSourceFolder = $varSourceWeb.GetFolder($varSourceFolderUrl)
 $varTargetFolder = $varTargetWeb.GetFolder($varTargetFolderUrl)
 $colSourceFiles = $varSourceFolder.Files
 foreach ($varSourceFile in $colSourceFiles) 
 {
 $varTargetFileUrl = $varTargetFolder.ServerRelativeUrl + "/" + $varSourceFile.Name
 $varTargetFile=$varTargetWeb.GetFile($varTargetFileUrl)
 if(!$varTargetFile.Exists)
 {
 $varBuffer = $varSourceFile.OpenBinary();
 $varNewTargetFile = $varTargetFolder.Files.Add($varTargetFile,$varBuffer,$true)
 }
 }
 
$varSourceWeb.Dispose();
$varTargetWeb.Dispose();
Advertisements
This entry was posted in PowerShell, SharePoint 2010, SharePoint Library. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s