I have a document library on Office 365 which I want to download to my local directory via powershell csom. I want to keep the file structure so its exactly the same in my local directory as it is in my Office 365 document library I found this which is what I want but its not in CSOM

$web = Get-SPWeb -Identity $webUrl
$list = $web.GetList($listUrl)

function ProcessFolder {
    $folder = $web.GetFolder($folderUrl)
    foreach ($file in $folder.Files) {
        #Ensure destination directory
        $destinationfolder = $destination + "/" + $folder.Url 
        if (!(Test-Path -path $destinationfolder))
            $dest = New-Item $destinationfolder -type directory 
        #Download file
        $binary = $file.OpenBinary()
        $stream = New-Object System.IO.FileStream($destinationfolder + "/" + $file.Name), Create
        $writer = New-Object System.IO.BinaryWriter($stream)

#Download root files
#Download files in folders
foreach ($folder in $list.Folders) {

I don't know if this workaround yet works (seems to be obsolete based on the comments here), but you should be able to map the document library as a local drive, for example, O:, and then use the Copy-Item cmdlet to copy the entire folder structure recursively (see here):

Copy-Item O:\ –destination '\\GRAPE\Documents\migrated' -recurse -container

Take a look here for the CSOM PowerShell to download files from SPO https://gallery.technet.microsoft.com/scriptcenter/How-to-automactically-1bc0ddd6 or use OfficeDevPnP PowerShell https://github.com/OfficeDev/PnP-PowerShell highly recommended!

  • how to use pnp powershell in an on-premises version of SP 2013? i dont have SPO, so, would like to know whether the pnp-powershell from the above link, can be used for on-prem version as well. Aug 9 '17 at 12:16
  • It can. It works for 2013/2016/2019 and SPO. Oct 4 '18 at 11:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.