Capture the folder name for each downloaded item

Pam 46 Reputation points
2021-08-23T21:51:03.147+00:00

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

                $Ctx.Load($Item.File)
                $Ctx.ExecuteQuery()  

                $SourceFile=$Item.File.ServerRelativeUrl;
                $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
    2021-08-24T02:40:48.15+00:00

    Hi @Pam ,

    You could write a recursive function to achieve this.

    Function Download-AllFilesFromLibrary()  
    {  
        param  
        (  
            [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  
            $Ctx.Load($FilesColl)  
            $Ctx.ExecuteQuery()  
       
            #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)  
                $FileInfo.Stream.CopyTo($WriteStream)  
                $WriteStream.Close()  
                write-host -f Green "Downloaded File:"$TargetFile  
            }  
               
            #Process Sub Folders  
            $SubFolders = $SourceFolder.Folders  
            $Ctx.Load($SubFolders)  
            $Ctx.ExecuteQuery()  
            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  
    $SiteURL="https://crescent.sharepoint.com/sites/sales/"  
    $LibraryName="Documents"  
    $TargetFolder="C:\Docs"  
       
    #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)  
    $Ctx.Load($List)  
    $Ctx.Load($List.RootFolder)  
    $Ctx.ExecuteQuery()  
       
    #Call the function: sharepoint online download multiple files powershell  
    Download-AllFilesFromLibrary -SiteURL $SiteURL -SourceFolder $List.RootFolder -TargetFolder $TargetFolder  
    

    Reference: https://www.sharepointdiary.com/2017/03/sharepoint-online-download-all-files-from-document-library-using-powershell.html


    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
    2021-08-25T09:44:11.333+00:00

    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:
    https://support.microsoft.com/en-us/office/download-files-and-folders-from-onedrive-or-sharepoint-5c7397b7-19c7-4893-84fe-d02e8fa5df05

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

    Thanks,

    Bharti B

    0 comments No comments