SharePoint Online: Download a File 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 the 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()
        [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)

        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
$SourceFileURL="/sites/Sales/Shared Documents/Crescent Legal App Requirements.docx"  #Server Relative URL 

#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 = ""
$FileServerRelativeURL = "/sites/Retail/Shared%20Documents/DocumentsInventory.csv"
$DestinationFolder ="C:\Temp"

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
        Write-host "Could not Find File at "$FileServerRelativeURL -f Red
Catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red

This PowerShell copies the file locally from SharePoint Online without prompt. The Get-PnPFile cmdlet also has other parameters like FileName, etc. Here is an example of how to download and read a CSV file from the SharePoint Online document library using PowerShell:

$SiteURL = ""
$FileServerRelativeURL = "/sites/retail/Invoices/MonthlyRpt.csv"

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive

$DownloadPath = $env:TEMP
$FileName = Split-Path $FileServerRelativeURL -leaf

#Download file from sharepoint online to Temp Folder
Get-PnPFile -Url $FileServerRelativeURL -Path $DownloadPath -Filename $FileName -AsFile -Force

#Import the CSV file
$CSVFile = Import-Csv -Path $env:TEMP\$FileName

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 the files from a SharePoint site?

To download all files from all libraries on a SharePoint site, use the “File Explorer” view. First, navigate to the document library or folder you want to download from. Then, click on the “Library” tab and select “Open with Explorer.” This will open a Windows Explorer window where you can select all the files and drag them to a local folder on your computer.
Alternatively, you can use the 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. You can also use PowerShell to download multiple files.

How do I turn off download permissions in SharePoint?

To disable download permissions in SharePoint, you can grant “Restricted View” (or “View Only”) Permission to Users, which will prevent users from downloading files. You can also use Information Rights Management (IRM) to restrict access to certain files and prevent them from being downloaded or printed. More info: How to prevent download in SharePoint document library?

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!

22 thoughts on “SharePoint Online: Download a File using PowerShell

  • It worked fine one day then I started getting the strange error
    Error: The ‘Connect-PnPOnline’ command was found in the module ‘PnP.PowerShell’, but the module could not be loaded. For more information, run ‘Import-Module PnP.PowerShell
    I found not much information on the internet.
    I also added the command Install-Module PnP.PowerShell -Force at the beginning of the script since I am not sure that this module is installed on the targeted machine

      • Hey Salaudeen,
        It didn’t help. Also, when I run Import-Module PnP.PowerShell I get the error: Import-Module : Could not load file or assembly ‘System.Management.Automation, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35’ or one of its
        dependencies. The system cannot find the file specified.
        At line:1 char:1
        + Import-Module PnP.PowerShell -Force
        + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo : NotSpecified: (:) [Import-Module], FileNotFoundException
        + FullyQualifiedErrorId : System.IO.FileNotFoundException,Microsoft.PowerShell.Commands.ImportModuleCommand

        #Read more:

        • Could be a bug in the latest version of PnP PowerShell! Try Uninstalling the latest version and install the previous version.
          Install-Module PnP.PowerShell -RequiredVersion 1.12.0 -Force

          • It worked with version 1.12. Thanks a lot for your help. Where can I report a bug in the latest version?

          • Great call! I had this same error and must be a bug in latest version. installing 1.12.0 worked


  • Thanks a lot Rajack. Just modified the code for download all files in a subfolder and then delete them. This uses API key of the site.
    #This code uses sites clientId and clientSecret of SharePoint site
    #Install-Module -Name PnP.PowerShell -RequiredVersion 1.10.0
    #Note: Remove-PnPFile had problem with 1.11.0 hence used 1.10.0
    #Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
    $siteUrl = “your site url”
    $LibraryName = “”
    $SharePointFolderPath = “//”
    $localDirectoryPath = “C:\Test”
    $clientId = “xxxxxxxxxxxxxxx”
    $clientSecret = “xxxxxxxxxxxxxxx”

    Try {
    $siteConn = Connect-PnPOnline -Url $siteUrl -ClientId $clientId -ClientSecret $clientSecret -WarningAction Ignore
    $web = Get-PnPWeb -Connection $siteConn

    $Files = Get-PnPFolderItem -FolderSiteRelativeUrl $SharePointFolderPath -ItemType File

    #Download files
    foreach($File in $Files) {
    Write-Host (“Downloading File: ‘{0}’ at ‘{1}'” -f $File.Name, $File.ServerRelativeURL)
    Get-PnPFile -Url $File.ServerRelativeUrl -Path $localDirectoryPath -FileName $File.Name -AsFile

    #Delete files
    foreach($File in $Files) {
    Write-Host (“Deleting File: ‘{0}’ at ‘{1}'” -f $File.Name, $File.ServerRelativeURL)
    Remove-PnPFile -ServerRelativeUrl $File.ServerRelativeURL -Force
    Write-host “Did not find any files in specified folder!” -f Yellow; Break
    Catch {
    write-host “Error: $($_.Exception.Message)” -foregroundcolor Red

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

  • Hi does this utilize Modern Authentication?

  • 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?

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

  • 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

  • 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.

  • 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.

    • 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
  • 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.

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

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


Leave a Reply

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