Friday, January 30, 2015

Powershell to move files around in same web for O365 SharePoint online

Sometime we need to help users to move files around the same web for O365 SharePoint online.  We have implemented this using CSOM as below. Please note this will not work to move files across the web or site.

$listTitle = "SourceDocuments"
$sourceFolder = "/SourceDocuments"
$destFolder = "/DestinationDocuments"
$siteUrl = "https://mycompany-my.sharepoint.com/personal/userID_company_com"


# Login as the user account to window server and run the following script
# read-host -AsSecureString | ConvertFrom-SecureString | out-file C:\cred.txt
# The password will be encripted to file
$o365admin = "userID@domain.company.com"
$password = get-content C:\cred.txt | convertto-securestring
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($o365admin,$password)


$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
$ctx.Credentials = $credentials

#Load items
$list = $ctx.Web.Lists.GetByTitle($listTitle)
$query = [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery()
$items = $list.GetItems($query)
$ctx.Load($list)
$ctx.Load($items)
$ctx.ExecuteQuery()
$items.Count


foreach ($item in $items){

  if($item.FileSystemObjectType -eq [Microsoft.SharePoint.Client.FileSystemObjectType ]::File) {

     $destFileUrl = $item["FileRef"].ToString().Replace($sourceFolder,$destFolder)
     $item.File.MoveTo($destFileUrl, [Microsoft.SharePoint.Client.MoveOperations]::Overwrite)
     $ctx.ExecuteQuery()
  }
}


I'm still working to find good solution to move files across site collection. I'm also working on to move the web from one site collection to another. Currently Microsoft API does not support this. Please share your thoughts if you have done this already.

1 comment:

  1. Hi Harry,

    Can this be used to move all files and folders in a document library? Will it work between Sites in the same Collection?

    ReplyDelete