Last active
May 4, 2023 06:17
-
-
Save joerodgers/97fa343cd5595d3fdb07b4cd430680a3 to your computer and use it in GitHub Desktop.
Download a File From SharePoint Online Document Library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add-Type -Path "C:\O365_CSOM\Microsoft.SharePointOnline.CSOM.16.1.6008.1200\lib\net45\Microsoft.SharePoint.Client.dll" | |
Add-Type -Path "C:\O365_CSOM\Microsoft.SharePointOnline.CSOM.16.1.6008.1200\lib\net45\Microsoft.SharePoint.Client.Runtime.dll" | |
function Download-File | |
{ | |
[cmdletbinding()] | |
param | |
( | |
[Parameter(Mandatory=$true)][Microsoft.SharePoint.Client.ClientContext]$ClientContext, | |
[Parameter(Mandatory=$true)][System.Uri]$FileUri, | |
[Parameter(Mandatory=$true)][string]$Path | |
) | |
begin | |
{ | |
} | |
process | |
{ | |
if( $FileUri.IsAbsoluteUri ) | |
{ | |
Write-Verbose -Message "Loading by AbsolutePath" | |
$fileInfo = [Microsoft.SharePoint.Client.File]::OpenBinaryDirect( $ClientContext, $FileUri.AbsolutePath ) | |
} | |
else | |
{ | |
Write-Verbose -Message "Loading by OriginalString" | |
$fileInfo = [Microsoft.SharePoint.Client.File]::OpenBinaryDirect( $ClientContext, $FileUri.OriginalString ) | |
} | |
try | |
{ | |
$fileStream = New-Object System.Io.FileStream( $Path, [System.IO.FileMode]::Create ) | |
$fileInfo.Stream.CopyTo( $fileStream ) | |
} | |
finally | |
{ | |
if( $fileStream ) | |
{ | |
$fileStream.Close() | |
$fileStream.Dispose() | |
} | |
if( $fileInfo ) | |
{ | |
$fileInfo.Dispose() | |
} | |
} | |
} | |
end | |
{ | |
} | |
} | |
$contextUrl = "https://contoso.sharepoint.com/sites/teamsite" | |
$documentUrl = "https://contoso.sharepoint.com/sites/teamsite/SubSite/Documents/Updates.docx" | |
$downloadPath = "C:\_temp\Updates.docx" | |
$credential = Get-Credential | |
$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($contextUrl) | |
$clientContext.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($credential.UserName, $credential.Password) | |
Download-File -ClientContext $clientContext -FileUri $documentUrl -Path $downloadPath | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment