Capture the folder name for each downloaded item

Pam 46 Reputation points

Hi, I have a script that downloads files from SP library (code below), and I would need to extract folder name of the item.
The source SP library has many folders and I'd need to capture the folder name for each downloaded item and add it to the target path or target file name. how could this be approached?

   #Extract the each list item from the List Items collection.
    ForEach($Item in $ListItems)


                $TargetFile=$TargetFolder + "\" + $Item.File.Name; 

                If ($Action -ne "UpdateOnly")
                FileDownLoadFromSPOnlineLibrary -SPOSiteURL $SiteURL -SourceFilePath $SourceFile -TargetFilePath $TargetFile 

                $fileDownloadingMessage="Downloaded: "+$Item.File.Name; 

                Write-Log $fileDownloadingMessage
SharePoint Development
SharePoint Development
SharePoint: A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.Development: The process of researching, productizing, and refining new or existing technologies.
2,714 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,407 questions
0 comments No comments
{count} votes

Accepted answer
  1. MichaelHan-MSFT 18,016 Reputation points

    Hi @Pam ,

    You could write a recursive function to achieve this.

    Function Download-AllFilesFromLibrary()  
            [Parameter(Mandatory=$true)] [string] $SiteURL,  
            [Parameter(Mandatory=$true)] [Microsoft.SharePoint.Client.Folder] $SourceFolder,  
            [Parameter(Mandatory=$true)] [string] $TargetFolder  
        Try {  
            #Create Local Folder, if it doesn't exist  
            $FolderName = ($SourceFolder.ServerRelativeURL) -replace "/","\"  
            $LocalFolder = $TargetFolder + $FolderName  
            If (!(Test-Path -Path $LocalFolder)) {  
                    New-Item -ItemType Directory -Path $LocalFolder | Out-Null  
            #Get all Files from the folder  
            $FilesColl = $SourceFolder.Files  
            #Iterate through each file and download  
            Foreach($File in $FilesColl)  
                $TargetFile = $LocalFolder+"\"+$File.Name  
                #Download the file  
                $FileInfo = [Microsoft.SharePoint.Client.File]::OpenBinaryDirect($Ctx,$File.ServerRelativeURL)  
                $WriteStream = [System.IO.File]::Open($TargetFile,[System.IO.FileMode]::Create)  
                write-host -f Green "Downloaded File:"$TargetFile  
            #Process Sub Folders  
            $SubFolders = $SourceFolder.Folders  
            Foreach($Folder in $SubFolders)  
                If($Folder.Name -ne "Forms")  
                    #Call the function recursively  
                    Download-AllFilesFromLibrary -SiteURL $SiteURL -SourceFolder $Folder -TargetFolder $TargetFolder  
        Catch {  
            write-host -f Red "Error Downloading Files from Library!" $_.Exception.Message  
    #Set parameter values  
    #Setup Credentials to connect  
    $Cred= Get-Credential  
    $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)  
    #Setup the context  
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)  
    $Ctx.Credentials = $Credentials  
    #Get the Library  
    $List = $Ctx.Web.Lists.GetByTitle($LibraryName)  
    #Call the function: sharepoint online download multiple files powershell  
    Download-AllFilesFromLibrary -SiteURL $SiteURL -SourceFolder $List.RootFolder -TargetFolder $TargetFolder  


    If an Answer is helpful, please click "Accept Answer" and upvote it.
    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.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Limitless Technology 39,436 Reputation points

    Hello @Pam ,

    Thank you for your question.

    You can download files and folders from Microsoft OneDrive, or from SharePoint in Microsoft 365 or SharePoint Server 2019, to your computer with just a few clicks.

    On your OneDrive, SharePoint Server 2019, or SharePoint in Microsoft 365 website, select the files or folders you want to download.

    To download individual or multiple files, select each item by clicking the circle check box that appears. (The left image below shows items in List view, the right image shows items in Tiles or Photos view.) (You can also select several files at once by selecting one file, scrolling down the list, then hold down the Shift key while left-clicking the last item you want to select.)

    To select all files in a folder, click the circle to the left of the header row, or press CTRL + A on your keyboard.

    To select a folder, rather than just its contents, you may need to go up or back a level to select the whole folder.

    In the top navigation, select Download. (You can also right-click the file, photo, or folder, and select Download.)

    If your browser prompts you, choose Save or Save As and browse to the location where you want to save the download. (Some browsers just start saving right away to a Downloads folder on your computer.)

    If you select multiple files or folders and then select Download, your browser will start downloading a .zip file containing all the files and folders you selected. If you're in a folder and you select Download without selecting any files or folders, your browser will begin downloading all contents of the folder.

    For more information please go through this link:

    If the reply was helpful, please don't forget to upvote or accept as answer.


    Bharti B

    0 comments No comments