Tuesday, February 3, 2015

Automate local file uploading to Office 365 Document Library using CSOM



After users started to use O365, there will be content migration request. Typical request is to migrate local files to O365 SharePoint online library. The following script will be handy to automate the process.

#Add references to SharePoint client assemblies and authenticate to Office 365 site - required for CSOM
Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

$siteUrl = "https://company-my.sharepoint.com/personal/userid_company_com"
$listTitle = "Documents"
$destination = "E:\\Backup"


# 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()
$ctx.Load($list)
$ctx.ExecuteQuery()
$items.Count

Foreach ($File in (dir $destination))
{
        $fileStream = New-Object IO.fileStream($File.FullName,[System.IO.FileMode]::Open)
        $fileCreationInfo = New-Object Microsoft.SharePoint.Client.fileCreationInformation
        $fileCreationInfo.Overwrite = $true
        $fileCreationInfo.ContentStream = $fileStream
        $fileCreationInfo.URL = $File
        $Upload = $list.RootFolder.Files.Add($fileCreationInfo)
        $ctx.Load($Upload)
        $ctx.ExecuteQuery()
        $fileStream.Close()
}
 

Please note this script does not handle any exception or loop through sub-folders. You could enhance it to handle them easily.

No comments:

Post a Comment