Downloading File from SharePoint Online Using PowerShell, OAuth and Invoke-Rest Method and Downloaded File is not correctly Formatted

With the below code, I am able to successfully authenticate to the site and download a file from SharePoint Online but the file appears to have a bunch of ancillary information from the site and not the actual text or images that it should have. I am able to successfully download the file using Postman but from Powershell, using Invoke-RestMethod, it appears to not format the file correctly after saving to local disk. Do I need to add a parameter to get it to save the file correctly?


$filename = ‘test1File.pdf’
$directory = ‘C:temp’
$path = $directory + $filename
$outfile = “C:temp$filename”

Function GetAccessToken() {

$appId = ‘d78f1248-6516-4ac5-838a-4a42c049435b’ #This is the Client ID
$appSecret = ‘(App Secret Here)’ #This is the Client Secret
$principal = ‘00000003-0000-0ff1-ce00-000000000000’ #This is the SharePoint Principal ID
$realm = ‘(Tenant ID Here)’ #This is the Tenant Id
$targetHost = ‘’ #This is the SharePoint Site
$resource = “00000003-0000-0ff1-ce00-000000000000/ ID Here)”

$body = (ordered)@{
grant_type = ‘client_credentials’
client_id = “$appId@$realm”
client_secret = $appSecret
resource = $resource

$accessTokenUrl = “$realm/tokens/OAuth/2”
$global:Access_Token = Invoke-RestMethod -uri $accessTokenUrl -Body $body -Method Post

Write-Host “Token =” $global:Access_Token.Access_token


Function DownloadFile() {

$url = “‘/sites/ecm-poc/Documents’)/Files(‘$filename’)/$value”
$headers = @{‘Authorization’ = “Bearer $access_token”;’Content-Type’=”application/json”;’Accept’=”application/json;odata=verbose”}
$DownloadFile = Invoke-RestMethod -Uri $url -Headers $headers -Method Get -OutFile $outfile -Verbose


$access_token = $global:Access_Token.Access_token


Write-Host “File Downloaded Successfully!”


Below is a Snipit of what it looks like after downloading the file: