Download subfolders folders in SharePoint 2019 on-premise?

Tevon2.0 1,106 Reputation points
2023-06-05T14:06:15.41+00:00

I am using Sharepoint Server 2019, I would like to download a sub folder within a document library. I only want to grab the sub folder not all folders/files in the document library. How should I correctly fill in the SharePoint Management Script below so that I do not end up downloading a bunch of unnecessary documents that will need to be deleted and only the sub folder that I want.?

Also how would I figure out the path or URL of the subfolder that I am seeking to download?

Add-PSSnapin Microsoft.Sharepoint.Powershell  
$SiteURL = "http://sp/sites/echo"  
$LibraryName ="Documents"  
$DownloadPath ="C:\temp"  
Function Download-SPFolder($SPFolderURL, $DownloadPath)  
{  
     Try {  
         $SPFolder = $web.GetFolder($SPFolderURL)  
         Write-host $SPFolder  
         $DownloadPath = Join-Path $DownloadPath $SPFolder.Name   
         If (!(Test-Path -path $DownloadPath))  
         {     
             $LocalFolder = New-Item $DownloadPath -type directory  
         }  
         #Loop through each file in the folder and download it to Destination  
         ForEach ($File in $SPFolder.Files)  
         {  
             #Download the file  
             $Data = $File.OpenBinary()  
             $FilePath= Join-Path $DownloadPath $File.Name  
             [System.IO.File]::WriteAllBytes($FilePath, $data)  
             Write-host -f Green "`tDownloaded the File:"$File.ServerRelativeURL          
         }  
         #Process the Sub Folders & Recursively call the function  
         ForEach ($SubFolder in $SPFolder.SubFolders)  
         {  
             If($SubFolder.Name -ne "Forms")  
             {  
                 #Call the function Recursively  
                 Download-SPFolder $SubFolder $DownloadPath  
             }  
         }  
     }  
     Catch {  
         Write-host -f Red "Error Downloading Document Library:" $_.Exception.Message  
     }   
}  
#Main Function  
Function Download-SPDocumentLibrary($SiteURL, $LibraryName, $DownloadPath)  
{  
     Try {  
         #Get the  Web  
         $Web = Get-SPWeb $SiteURL  
         #Delete any existing files and folders in the download location  
         If (Test-Path $DownloadPath) {Get-ChildItem -Path $DownloadPath -Recurse| ForEach-object {Remove-item -Recurse -path $_.FullName }}  
         #Get the document Library to Download  
         $Library = $Web.Lists[$LibraryName]  
         Write-host -f magenta "Downloading Document Library:" $Library.Title  
         #Call the function to download the document library  
         Download-SPFolder -SPFolderURL $Library.RootFolder.Url -DownloadPath $DownloadPath  
         Write-host -f Green "*** Download Completed  ***"  
     }  
     Catch {  
         Write-host -f Red "Error Downloading Document Library:" $_.Exception.Message  
     }   
}  
Download-SPDocumentLibrary $SiteURL $LibraryName $DownloadPath
Microsoft 365 and Office | SharePoint Server | For business
Microsoft 365 and Office | SharePoint Server | Development
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Xyza Xue_MSFT 30,176 Reputation points Microsoft External Staff
    2023-06-06T03:18:57.6566667+00:00

    Hi @Tevon2.0 ,

    You can download specific folders using this powershell (You need to replace SharePointFolderUrl and LocalFolderPath in the last line of code).

    The url of a specific folder/subfolder can be viewed by the end of the URL of the page(%2F = Forward slash (/), %20= Forward slash (Space)), for example:

    User's image

    Add-PSSnapin Microsoft.Sharepoint.PowerShell
    
    function Download-Folder
    {
        [CmdletBinding()]
        param
        (
            [Parameter(Mandatory=$true)][string]$SharePointFolderUrl,
            [Parameter(Mandatory=$true)][string]$Path,
            [Parameter(Mandatory=$false)][switch]$Recurse
        )
    
        begin
        {
        }
        process
        {
            $site   = New-Object Microsoft.SharePoint.SPSite($SharePointFolderUrl)
            $web    = $site.OpenWeb()
            $folder = $web.GetFolder($SharePointFolderUrl)
    
            if( $folder.Exists )
            {
                Write-Verbose "$(Get-Date) - Processing Folder: $($folder.ServerRelativeUrl)"
    
                foreach( $file in $folder.Files )
                {
                    $fileUrl = $site.MakeFullUrl($file.ServerRelativeUrl)
                
                    Write-Verbose "$(Get-Date) - Downloading File: $($fileUrl)"
    
                    $response = Invoke-WebRequest -Uri $fileUrl -UseDefaultCredentials -Verbose:$false
                    
                    try
                    {
                        # combine the provided path to the server relative url
                        $savePath = Join-Path -Path $Path -ChildPath $file.ParentFolder.ServerRelativeUrl
    
                        # ensure the folder exists
                        New-Item -Path $savePath -ItemType Directory -Force | Out-Null
    
                        # add the file name to the path
                        $savePath = Join-Path -Path $savePath -ChildPath $file.Name
                        
                        # save the bits locally
                        $stream = New-Object System.IO.FileStream( $savePath, [System.IO.FileMode]::Create, [System.IO.FileAccess]::ReadWrite)
                        $response.RawContentStream.CopyTo($stream)
                    }
                    finally
                    {
                        if( $stream ) 
                        {
                            $stream.Close()
                            $stream.Dispose()
                        }
                    }
                }
    
                if( $Recurse )
                {
                    foreach( $subFolder in $folder.SubFolders )
                    {
                        if( $subFolder.Item )
                        {
                            $subFolderUrl = $site.MakeFullUrl($subFolder.ServerRelativeUrl)
                            Download-Folder -SharePointFolderUrl $subFolderUrl -Path $Path -Recurse
                        }
                    }
                }
            }
        }
        end
        {
        }
    }
    
    Download-Folder -SharePointFolderUrl "http://sp19/sites/luyi19/Shared Documents/folder1" -Path "C:\SP" -Recurse -Verbose
    

    The download effect diagram after running is shown in the figure below (it will automatically create a local folder to store the file):User's image


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.