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) {

2 Answers 2


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.
    – samolpp2
    Commented Aug 9, 2017 at 12:16
  • It can. It works for 2013/2016/2019 and SPO. Commented Oct 4, 2018 at 11:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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