1

Downloading folders from Sharepoint Online using Powershell

Needed to do this in work recently, found this excellent link over here: https://www.sharepointdiary.com/2017/07/download-folder-from-sharepoint-online-using-powershell.html

Needs to open a Powershell window first and run “Install-Module -Name "PnP.PowerShell"

 

#Function to Download All Files from a SharePoint Online Folder - Recursively 
Function Download-SPOFolder([Microsoft.SharePoint.Client.Folder]$Folder, $DestinationFolder)
    #Get the Folder's Site Relative URL
    $FolderURL = $Folder.ServerRelativeUrl.Substring($Folder.Context.Web.ServerRelativeUrl.Length)
    $LocalFolder = $DestinationFolder + ($FolderURL -replace "/","\")
    #Create Local Folder, if it doesn't exist
    If (!(Test-Path -Path $LocalFolder)) {
            New-Item -ItemType Directory -Path $LocalFolder | Out-Null
            Write-host -f Yellow "Created a New Folder '$LocalFolder'"
    }
           
    #Get all Files from the folder
    $FilesColl = Get-PnPFolderItem -FolderSiteRelativeUrl $FolderURL -ItemType File
    #Iterate through each file and download
    Foreach($File in $FilesColl)
    {
        Get-PnPFile -ServerRelativeUrl $File.ServerRelativeUrl -Path $LocalFolder -FileName $File.Name -AsFile -force
        Write-host -f Green "`tDownloaded File from '$($File.ServerRelativeUrl)'"
    }
    #Get Subfolders of the Folder and call the function recursively
    $SubFolders = Get-PnPFolderItem -FolderSiteRelativeUrl $FolderURL -ItemType Folder
    Foreach ($Folder in $SubFolders | Where {$_.Name -ne "Forms"})
    {
        Download-SPOFolder $Folder $DestinationFolder
    }
 
#Set Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$FolderSiteRelativeURL = "/Team Documents/2018"
$DownloadPath ="C:\Docs"
 
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -UseWebLogin
 
#Get the folder to download
$Folder = Get-PnPFolder -Url $FolderSiteRelativeURL
 
#Call the function to download the folder
Download-SPOFolder $Folder $DownloadPath

 

 

One Comment

  1. Thank you so much! The first script, that actually WORK on powershell 7!
    Spent few days looking for!!

Leave a Reply

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