Tuesday, February 3, 2015

Automate Office 365 Document Library file downloading to local using CSOM

After users started to use O365, you might need to download files from O365 library to local file system 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()
$items = $list.GetItems($query)
$ctx.Load($list)
$ctx.Load($items)
$ctx.ExecuteQuery()
$items.Count

foreach ($File in $items) {
         Write-host "Url: $($File["FileRef"]), title: $($File["FileLeafRef"]) "
        if($File.FileSystemObjectType -eq [Microsoft.SharePoint.Client.FileSystemObjectType ]::File) {

            $fileRef = $($File["FileRef"]).ToString()
            $fileRef
            $fileInfo = [Microsoft.SharePoint.Client.File]::OpenBinaryDirect($ctx, $fileRef);
            $fileName = $destination + "\\" + $File["FileLeafRef"]
            $fileStream = [System.IO.File]::Create($fileName)
            $fileInfo.Stream.CopyTo($fileStream);
            $fileStream.Close()

        }
}

Please note this script does not handle any exception or loop through sub-folders. You could enhance it to handle them easily. You could also use different WebClient object to download file. 

In case you need a way to download ALL files from a site, you might need to get all sub-site and folders.

No comments:

Post a Comment