SharePoint Online Automation – O365 – Download files from a document library using PowerShell CSOM

No comments

 37,675 total views,  42 views today

Here in this post – I will show how we can download files or documents from SharePoint online document library using PowerShell CSOM programmatically from the given date by passing the “From Date” and “To Date” to the query. Let’s say we want to download certain files from the SharePoint document library that were created between these two dates – using this script we can download those files.

Here in the below screenshot, we can see the file creation date is from September 6 to till date (November 6). Using the code I will download the files that were created from October 28 to November 6 where I will ensure that the file which was created on September 6 will not be downloaded.


PowerShell CSOM Script to Download the files:

#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"

$fileName = "File_Downloading_Report"
#'yyyyMMddhhmm   yyyyMMdd
$enddate = (Get-Date).tostring("yyyyMMddhhmmss")
#$filename =  $enddate + '_VMReport.doc'  
$logFileName = $fileName +"_"+ $enddate+"_Log.txt"   
$invocation = (Get-Variable MyInvocation).Value  
$directoryPath = Split-Path $invocation.MyCommand.Path  

if(!(Test-Path -path $directoryPathForLog))  
            New-Item -ItemType directory -Path $directoryPathForLog
            #Write-Host "Please Provide Proper Log Path" -ForegroundColor Red   

#$logPath = $directoryPath + "\" + $logFileName 

$logPath = $directoryPathForLog + "\" + $logFileName 
$isLogFileCreated = $False 

#DLL location

$directoryPathForDLL=$directoryPath+"\"+"Dependency Files"
if(!(Test-Path -path $directoryPathForDLL))  
            New-Item -ItemType directory -Path $directoryPathForDLL
            #Write-Host "Please Provide Proper Log Path" -ForegroundColor Red   

#DLL location

Add-Type -Path $clientDLL
Add-Type -Path $clientDLLRuntime
#File Download location

$directoryPathForFileDownloadLocation=$directoryPath+"\"+"Downloaded Files"
if(!(Test-Path -path $directoryPathForFileDownloadLocation))  
            New-Item -ItemType directory -Path $directoryPathForFileDownloadLocation
            #Write-Host "Please Provide Proper Log Path" -ForegroundColor Red   

#File Download location


function Write-Log([string]$logMsg)  
        Write-Host "Creating Log File..."   
        if(!(Test-Path -path $directoryPath))  
            Write-Host "Please Provide Proper Log Path" -ForegroundColor Red   
            $script:isLogFileCreated = $True   
            Write-Host "Log File ($logFileName) Created..."   
            [string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)   
            Add-Content -Path $logPath -Value $logMessage   
        [string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)   
        Add-Content -Path $logPath -Value $logMessage   

#The below function will download the file from SharePoint Online library.
Function FileDownLoadFromSPOnlineLibrary()
        [Parameter(Mandatory=$true)] [string] $SPOSiteURL,
        [Parameter(Mandatory=$true)] [string] $SourceFilePath,
        [Parameter(Mandatory=$true)] [string] $TargetFilePath,
        [Parameter(Mandatory=$true)] [string] $UserName,
        [Parameter(Mandatory=$true)] [string] $Password

        $securePassword= $Password | ConvertTo-SecureString -AsPlainText -Force  
        #Setup the Context
        $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SPOSiteURL)
        $ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $securePassword)

        #Downloading the file from SharePoint online document libray.
        $fileInfo = [Microsoft.SharePoint.Client.File]::OpenBinaryDirect($ctx,$SourceFilePath)
        $writeStream = [System.IO.File]::Open($TargetFilePath,[System.IO.FileMode]::Create)
        Write-host -f Green "File '$SourceFilePath' has been downloaded to '$TargetFilePath' successfully!"
            $ErrorMessage = $_.Exception.Message +"in Downloading File!: " +$SourceFilePath
            Write-Host $ErrorMessage -BackgroundColor Red
            Write-Log $ErrorMessage 


#Parameters value
$listName="Documents" #Document library name
$userName = ""
$password = "YourPassWord"
$securePassword= $password | ConvertTo-SecureString -AsPlainText -Force
#$batchSize =1000
#Parameters ends here.

#Setup the Context
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL)
$ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userName, $securePassword)
#Get the List
$list = $ctx.Web.Lists.GetByTitle($listName)
$emptyString = ""
#Define CAML Query to get Files from the list in batches
$Query = New-Object Microsoft.SharePoint.Client.CamlQuery

#Here in the below two line "T13:35:58Z" and "T13:36:34Z" are hard coded static value - because while we construct this camel query thru the camel query builder these values gets appended to the date value, so we need this.
#Here in the below two line "T13:35:58Z" and "T13:36:34Z" are hard coded static value - ends here.

$Query.ViewXml = "@
    <View Scope='RecursiveAll'>
            <FieldRef Name='Created' />
            <Value IncludeTimeValue='TRUE' Type='DateTime'>$startDateVar</Value>
            <FieldRef Name='Created' />
            <Value IncludeTimeValue='TRUE' Type='DateTime'>$endDateVar</Value>

$count =0
#Get List Items in Batches

    $ListItems = $List.GetItems($Query)

    #Update Postion of the ListItemCollectionPosition
    $Query.ListItemCollectionPosition = $ListItems.ListItemCollectionPosition
    If ($ListItems.Count -eq 0) 

    #Extract the each list item from the List Items collection.
    ForEach($Item in $ListItems)
          #Example to Item metadata - this can be used if we want to download based on some item metadata condition.
                #$TargetFile="C:\PowerShell\DownLoadFilesFromSPOnline\Downloaded Files\LegalDoc.docx" 

                #If we want to download the specific file type we can check the file type using the below code 

                #Calling the function "FileDownLoadFromSPOnlineLibrary"to download file
                FileDownLoadFromSPOnlineLibrary -SPOSiteURL $SiteURL -SourceFilePath $SourceFile -TargetFilePath $TargetFile -UserName $UserName -Password $Password

                $fileDownloadingMessage=$downloadItemCount.ToString()+": "+$Item.File.Name; 
                Write-Host $fileDownloadingMessage -BackgroundColor DarkGreen
                Write-Log $fileDownloadingMessage


            $ErrorMessage = $_.Exception.Message +"in: " +$Item.File.Name
            Write-Host $ErrorMessage -BackgroundColor Red
            Write-Log $ErrorMessage 


    Write-Host "============================================================="
    Write-Host $count
    Write-Host "============================================================="
}While ($Query.ListItemCollectionPosition -ne $null)


The file will be downloaded here – just ensuring before executing the script this folder is empty.


Execute the above script successfully:


Verify the  “Downloaded Files” folder – now we can see four files just have arrived.



In the above location, the file which was created before October 28 is not downloaded because we have given filter criteria from October 28 to November 6.

Prerequisites to execute this script:

Need to place the below two DLLs in your script directory “Dependency Files” folder as like below:


Change the value of the variable in the variables section like below:

#Variables region 
$siteURL="Site URL"
$listName="Document Library Name" #Document library name
$fromDate="From Date(YYYY-MM-DD)"
$toDate="To Date(YYYY-MM-DD)"
$userName = ""
$password = "YourPassWord"
#Variables region ends here



Thus, in this article we have learned the below:

  • Ho to download a file/document from SharePoint online document library using PowerShell CSOM.
  • How to download a file/document from the SharePoint folder using PowerShell.

See Also:


Download SharePoint Online & Office 365 Administration eBook

Get the PDF eBook from here:


Send download link to:

Subscribe to get exclusive content and recommendations every month. You can unsubscribe anytime.