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:
- Sign in to the SharePoint Online site >> Navigate to the library where your desired file is located.
- Right-click on the file and select the “Download” option from the context menu.
- This gets you the “Save” prompt, and the file gets saved in your client machine’s Downloads directory.
- 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.
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.
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:\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
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?
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?
Use the “File Explorer” view or OneDrive sync client to download files from SharePoint Online sites.
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
}
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?
Use the PnP PowerShell method: Connect-PnPOnline -Url $SiteURL -Interactive
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
This should help you to start with: SharePoint Online: Download All Versions of a Document 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:
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.
Sure! You can search using PowerShell as in: How to Search SharePoint Online using PnP PowerShell?
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.
Here you go: How to Download All Files from a SharePoint Online Document Library using PowerShell?