Downloading a file with Powershell

JustAGuy picture JustAGuy · Jul 7, 2018 · Viewed 58.4k times · Source

The following Google Doc gets exported to CSV and is then downloaded automatically using a standard Web Browser: https://docs.google.com/spreadsheets/d/1wDD_Xm8IQYuYNefv9cOJ_7afTLImHgYA05pfN3qY63E/export?format=csv

I'm trying to download this file using Powershell without success. I tried using Invoke-Webrequest, Start-BitsTransfer and using a webrequest object but no luck there.

EDITED: changed url.

Answer

TGlatzer picture TGlatzer · Jul 7, 2018

Invoke-WebRequest comes with a parameter to store its result in a file: -OutFile

Invoke-WebRequest URL -OutFile c:\file.ext

If you need authorization before you can send a request like this:

Invoke-WebRequest URL /* whatever is neccesary to login */ -SessionVariable MySession
Invoke-WebRequest URL -WebSession $MySession

To determine the layout of the form where the login happens, you can use Invoke-WebRequests return object. It'll collect information about forms and fields on the HTML (might be Windows only). Mileage of logging in may vary with things like Two-Factor-Auth active or not. Probably you can create some secret link to your file which does not need Auth or possibly google allows you to create a private access token of some sort, which can be send aus Authorization-Header alongside your request.