Download document from SharePoint Online / Office 365 with PowerShell

I had a need to download a document from SharePoint Online with the intention of performing this download test from a variety of locations globally to test the overall performance.

After learning that the client context was the way to go re: interacting with SharePoint Online vs. On Premises, I had a number of issues ultimately getting this to work without ending up with 0 byte files saved.

Following a lot of research and copying/pasting from various blogs I compiled the example below.  It’s a bit dirty but hopefully is useful if you are stuck in a similar situation.

No warranty implied or otherwise so please use at your own risk 🙂


import-module microsoft.online.sharepoint.powershell
function downloadDocs($siteURL, $credentials)
{
 # Create a client context connection
 $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
 $ctx.Credentials = $credentials

 $list = $ctx.Web.Lists.GetByTitle('Documents')
 $destinationPath = "C:\test"

 # Connect to the list and query for all items
 $camlQuery = New-Object Microsoft.SharePoint.Client.CamlQuery
 $camlQuery.ViewXml = '<View><Query><Where></Where></Query></View>'
 $items = $list.GetItems($camlQuery)
 $ctx.Load($items)
 $ctx.ExecuteQuery()
write-host "Found " $items.Count " items"

 # Assuming we want to download all documents
 foreach ($item in $items)
 { 
 Write-Host "Saving " $item["FileRef"]
 $fileRef = $item["FileRef"]
 $fileInfo = [Microsoft.SharePoint.Client.File]::OpenBinaryDirect($ctx,$fileRef.ToString())
 $new = $destinationPath + "\" + $item["FileLeafRef"]

 [byte]$byte = ""
 $list = New-Object System.Collections.Generic.List[byte]
# Read in each file
 try {
 while(($byte = $fileInfo.Stream.ReadByte()) -ne -1)
 { 
 $list.Add($byte)
 }
 } catch [Exception] {
 #return $_.Exception.Message
 }

 [System.IO.File]::WriteAllBytes($new, $list.ToArray());
 $fileInfo.Dispose() 
 }
}
$siteUrl = “https://<mycompany>.sharepoint.com/”
$username ="<name>@<company>.onmicrosoft.com"
$password = Read-Host -Prompt "Enter password" -AsSecureString
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $password)
downloadDocs $siteURL $credentials

Leave a Reply

Your email address will not be published. Required fields are marked *