Skip to content

Instantly share code, notes, and snippets.

@jamiechalmerzlp
Last active October 25, 2022 16:37
Show Gist options
  • Save jamiechalmerzlp/e8925f8f408b1928ea0b0f59455d3561 to your computer and use it in GitHub Desktop.
Save jamiechalmerzlp/e8925f8f408b1928ea0b0f59455d3561 to your computer and use it in GitHub Desktop.
#Function to Download All Files from a SharePoint Online Folder - Recursively
$FolderName = "Name the folder you are downloading"
#The transcript will capture the process to ensure you have a log of the download/transfer - ALWAYS KEEP LOGS
Start-Transcript -Path "C:\temp\$FolderName.txt"
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 "$DestinationFolder\$FolderURL" | Out-Null
Write-host -f Yellow "Created a New Folder '$DestinationFolder\$FolderURL'"
}
#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
}
}
$SiteURL = "https://contoso.sharepoint.com"
$FolderSiteRelativeURL = "Shared Documents/subsite/subsitex/$FolderName" #Use the variable so you only have to change the text once.
$DownloadPath ="C:\temp\"
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive
#Get the folder to download
$Folder = Get-PnPFolder -Url $FolderSiteRelativeURL
#Call the function to download all files from a folder
Download-SPOFolder $Folder $DownloadPath
Stop-Transcript
@jamiechalmerzlp
Copy link
Author

15/08 - Modified line 33
$FolderSiteRelativeURL = "Shared Documents/subsite/subsitex/$FolderName" #Use the variable so you only have to change the text once.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment