downloading a file from SharePoint Online with PowerShell

前端 未结 5 2064
终归单人心
终归单人心 2020-12-10 09:43

I have a requirement to download files from a sharepoint online document library using powershell

I\'ve managed to get to the point where the download should happen

5条回答
  •  时光取名叫无心
    2020-12-10 10:29

    You could also utilize WebClient.DownloadFile Method by providing SharePoint Online credentials to download the resource from SharePoint Online as demonstrated below.

    Prerequisites

    SharePoint Online Client Components SDK have to be installed on the machine running the script.

    How to download a file in SharePoint Online/O365 in PowerShell

    Download-File.ps1 function:

    [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
    [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")
    
    
     Function Download-File([string]$UserName, [string]$Password,[string]$FileUrl,[string]$DownloadPath)
     {
        if([string]::IsNullOrEmpty($Password)) {
          $SecurePassword = Read-Host -Prompt "Enter the password" -AsSecureString 
        }
        else {
          $SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force
        }
        $fileName = [System.IO.Path]::GetFileName($FileUrl)
        $downloadFilePath = [System.IO.Path]::Combine($DownloadPath,$fileName)
    
    
        $client = New-Object System.Net.WebClient 
        $client.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $SecurePassword)
        $client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f")
        $client.DownloadFile($FileUrl, $downloadFilePath)
        $client.Dispose()
    }
    

    Usage

    Download-File -UserName "username@contoso.onmicrosoft.com" -Password "passowrd" -FileUrl https://consoto.sharepoint.com/Shared Documents/SharePoint User Guide.docx -DownloadPath "c:\downloads"
    

提交回复
热议问题