49
votes

I have a URL to a CSV file which, in a browser, I can download and open without issue.

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.

2
I stranded here when looking for a way to download from docs.google.com/file/d/0B78A_rsP6RDSVjBTa1ZUSXBGYzA/edit - the accepted answer helped me to find drive.google.com/… - I know that this is not for this excact question but hope it could be an equally huge help to somebody else landing here. - Cadoiz

2 Answers

93
votes

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.

5
votes

TLDR answers*:

Method 1, by default synchronous**

Invoke-WebRequest $url -OutFile $path_to_file

Method 2, by default synchronous**

(New-Object System.Net.WebClient).DownloadFile($url, $path_to_file)

Method 3, asynchronous and may not be immediate, uses BITS service

Import-Module BitsTransfer
Start-BitsTransfer -Source $url -Destination $path_to_file

Notes:

*: This answer is for those that google for "how to download a file with PowerShell".

**: Read the help pages if you want asynchronous downloading