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()
{ 
    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:\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
    }
    Else
    {
        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:

#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/retail"
$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 - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world 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

    Reply
      • 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=7.2.0.0, 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: https://www.sharepointdiary.com/2016/09/sharepoint-online-download-file-from-library-using-powershell.html#ixzz7y0d5kr1J

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

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

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

            thanks!

            Reply
  • 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
    $web.Title

    $Files = Get-PnPFolderItem -FolderSiteRelativeUrl $SharePointFolderPath -ItemType File
    If($Files)
    {

    #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
    }
    }
    else
    {
    Write-host “Did not find any files in specified folder!” -f Yellow; Break
    }
    }
    Catch {
    write-host “Error: $($_.Exception.Message)” -foregroundcolor Red
    }

    Reply
  • 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 *