restpowershellscripting

Powershell: Out-File - Access to the path is denied


I've got a REST call (POST) for downloading a PDF file. The API call responds in a binary version of the PDF file. I want to save the file on my machine as a .pdf. However, I am getting an error:

Out-File : Access to the path 'C:\Users\my-name\Documents\Tests' is denied.
At C:\Users\my-name\Documents\Tests\TEST-WITH-LOOP.ps1:132 char:149
+ ... questBody | Out-File -FilePath ("C:\Users\my-name\Documents\Tests
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (:) [Out-File], UnauthorizedAccessException
    + FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.OutFileCommand

Response body header from POSTMAN:

Content-Disposition →attachment; filename="Report-01_29_14-28.pdf"
Content-Type →application/octet-stream
DataServiceVersion →2.0
Date →Mon, 29 Jan 2018 21:51:31 GMT
Date →Mon, 29 Jan 2018 21:51:31 GMT
Server →Jetty(9.3.7.v20160115NeotysEdition.30)
Transfer-Encoding →chunked

Command:

$DownloadReportResponse = Invoke-RestMethod -Method Post -Uri $DownloadReportUrl -ContentType "application/json" -Body $DownloadReportRequestBody |
    Out-File -FilePath ("C:\Users\my-name\Documents\Tests") -Force

Question: How do I save this to my machine as a .pdf or possibly include as an attachment to the email?


Solution

  • Well, the error is a bit misleading. You're trying to create the output file as C:\Users\my-name\Documents\Tests, but that already exists as a directory, hence the access violation. Create the file with the full path:

    Invoke-RestMethod ... |
        Out-File "C:\Users\my-name\Documents\Tests\Report-01_29_14-28.pdf"