SharePoint Online: Download a File from Library using PowerShell

Requirement: Download a File from SharePoint Online using PowerShell.

How to Download a File from SharePoint Online Library?

Downloading files from SharePoint Online is pretty straightforward. If you need to download a file from SharePoint Online, just browse to the site that contains the document, right-click on it, and select ‘Download’ in the menu bar – it’s that simple. This can be useful if you need to access a document that’s been shared with you – without any connectivity from your local machine. How do I Download a document from SharePoint Online? Let’s see the step-by-step instructions on how to download a file.

To download a file from the library, follow these steps:

  1. Sign-in to the SharePoint Online site >> Navigate to the library where your desired file is located.
  2. Right-click on the file and select the “Download” option from the context menu.
    sharepoint online powershell download file
  3. This gets you the “Save” prompt, and the file gets saved in your client machine’s Downloads directory.
  4. In Modern Libraries, You can select the file(s) or folder and hit the “Download” button from the toolbar. You can also download multiple files at once.
    powershell download file from sharepoint online

Select them all and click the “Download” button in the toolbar. This will download all selected files as a .zip file, which you can then extract to your computer.

You can open any document library or folder in “File Explorer” view and just copy-paste the files to your local machine to download them! You can also use the “Sync” option to download all files/folders from the library to your computer.

Now, How to download a file from SharePoint Online using PowerShell? Well, Here is the PowerShell script to download a file from SharePoint Online!

SharePoint Online PowerShell to Download a File from Library

Let’s download documents from the SharePoint Online document library using PowerShell. This CSOM PowerShell script downloads a file from the SharePoint Online document library (or any library!). It requires the following parameters: URL of the site, server relative URL of the file, and local path. It is important to note that the script will only work if the user has sufficient permission to access the site and library.

#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

#Function to copy a given sourcefile to downloadpath
Function Download-FileFromLibrary()
{ 
    param
    (
        [Parameter(Mandatory=$true)] [string] $SiteURL,
        [Parameter(Mandatory=$true)] [string] $SourceFileURL,
        [Parameter(Mandatory=$true)] [string] $TargetFilePath
    )

    Try {
        #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
    
        #sharepoint online powershell download file from library
        $FileInfo = [Microsoft.SharePoint.Client.File]::OpenBinaryDirect($Ctx,$SourceFileURL)
        $WriteStream = [System.IO.File]::Open($TargetFilePath,[System.IO.FileMode]::Create)
        $FileInfo.Stream.CopyTo($WriteStream)
        $WriteStream.Close()

        Write-host -f Green "File '$SourceFileURL' Downloaded to '$TargetFilePath' Successfully!" $_.Exception.Message
  }
    Catch {
        write-host -f Red "Error Downloading File!" $_.Exception.Message
    }
}

#Set parameter values
$SiteURL="https://crescent.sharepoint.com/sites/sales"
$SourceFileURL="/sites/Sales/Shared Documents/Crescent Legal App Requirements.docx"  #Server Relative URL 
$TargetFilePath="C:\Temp\LegalDoc.docx"

#Call the function to download file
Download-FileFromLibrary -SiteURL $SiteURL -SourceFileURL $SourceFileURL -TargetFilePath $TargetFilePath

To download all files from a SharePoint Online document library, use this script: SharePoint Online download multiple files using PowerShell

Download a File from SharePoint Online using PnP PowerShell

We can copy files from SharePoint Online to a local disk with PowerShell. Here is the PnP PowerShell to download a file from SharePoint Online:

#Config Variables
$SiteURL = "https://crescent.sharepoint.com/sites/retail"
$FileServerRelativeURL = "/sites/Retail/Shared%20Documents/DocumentsInventory.csv"
$DestinationFolder ="C:\Temp5"

Try {
     #Check if the Destination Folder exists. If not, create the folder for targetfile
     If(!(Test-Path -Path $DestinationFolder))
     {
        New-Item -ItemType Directory -Path $DestinationFolder | Out-Null
        Write-host -f Yellow "Created a New Folder '$DestinationFolder'"
     }

    #Connect to PnP Online
    Connect-PnPOnline -Url $SiteURL -Interactive
    
    #Check if File exists
    $File = Get-PnPFile -Url $FileServerRelativeURL -ErrorAction SilentlyContinue
    If($File -ne $Null)
    {
        #Download file from sharepoint online
        Get-PnPFile -Url $FileServerRelativeURL -Path $DestinationFolder -Filename $File.Name -AsFile -Force
        Write-host "File Downloaded Successfully!" -f Green
    }
    Else
    {
        Write-host "Could not Find File at "$FileServerRelativeURL -f Red
    }
}
Catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

This PowerShell copies file locally from SharePoint Online without prompt. The Get-PnPFile cmdlet also has other parameters like FileName, etc.

How do I Download a folder from SharePoint using PowerShell? To download a folder from SharePoint Online using PowerShell, use: PowerShell to Download a Folder from SharePoint Online

How do I download all files from a SharePoint site?

If you want to download all files from all libraries on a SharePoint site, you can use the “File Explorer” view or PowerShell script: How to Download All Files from a SharePoint Site?

How do I download all files from the SharePoint Online library?

To download all files from a SharePoint Online document library, browse to your SharePoint document library >> Select all Files and folders. Click on the “Download” button from the toolbar. You can use the “File Explorer view” or PowerShell as alternative options to download the document library.
More info: How to Download a Document Library in SharePoint Online?

How do I download multiple files from SharePoint Classic?

Use the “File Explorer” view or OneDrive sync client to download files from SharePoint Online sites.

Salaudeen Rajack

Salaudeen Rajack - SharePoint Expert with Two decades of SharePoint Experience. Love to Share my knowledge and experience with the SharePoint community, through real-time articles!

15 thoughts on “SharePoint Online: Download a File from Library using PowerShell

  • If the library is too big you should add ‘$FileInfo.Stream.Close()’ after the line ‘$WriteStream.Close()’ to avoid time out errors.

    Reply
  • Hi does this utilize Modern Authentication?

    Reply
  • Hi and thanks for all the info provided here!
    I have one quick question for the situation when the file you want to download it is read-only. When I try to open it in powershell it automatically opens me the workbook and the pop-up where I should hit the Read-Only button.
    After this, the script continue to run.
    Do you have any solution of doing this manual step automatically in a script?

    Reply
  • How to download all Folders & Files from Document library with version history using powershell

    Reply
  • Doesn’t work.

    Get-PnPFile : Cannot convert ‘System.Object[]’ to the type ‘System.String’ required by parameter ‘Url’. Specified method is not supported.
    At line:15 char:18
    Get-PnPFile -Url $CSVData.FileRelativeURL -path $DownloadPath -AsFile
    ~~~~~~~~~~~~~~~~~~~~~~~~
    CategoryInfo : InvalidArgument: (:) [Get-PnPFile], ParameterBindingException
    FullyQualifiedErrorId : CannotConvertArgument,PnP.PowerShell.Commands.Files.GetFile

    Reply
  • Hi,
    is there a way to pass the credentials of the currently logged in user to the script?
    E.g. every user who gets the script via intune (so even outside of the Domain-Network and out of reach for the gpo’s) automatically downloads a file from the SharePoint to a specific location on the device.

    Many thanks in advance.

    Reply
  • Hello,

    I have a need to download a list of specific files from SharePoint Online that are from different libraries to a network location. Do you have anything that accomplishes that task. Currently i have the list of file paths in sharepoint in a .csv file. I would like to read in that .csv and download the files.

    Reply
    • Say, you have a CSV file with “FileRelativeURL” column. Here is the PowerShell script you can utilize:

      #Get Data from CSV File
      $CSVData = Import-CSV -path "C:\SitesData.csv"
      
      #Iterate through each Row in the CSV
      foreach ($Row in $CSVData)
      {
      #Download the File
      Get-PnPFile -Url $CSVData.FileRelativeURL -Path "C:\Downloads" -AsFile
      }
      
      Reply
  • This is a great site for information. Thank you

    Do you have also sharepoint online powershell scripts that searches inside documents (docx, xlsx, pdf) for keywords? I could not find any.

    Reply
  • How to download a file from SharePoint on premise site based on current date? any help will be much appreciated

    Reply
  • How to download multiple files from sharepoint online using powershell. Above one is to download single file.

    Reply

Leave a Reply

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