Download file from Google Drive with PowerShell

Kevin Burton picture Kevin Burton · Oct 5, 2016 · Viewed 7.2k times · Source

Right now in trying to download a file with PowerShell I have the following

$client = new-object System.Net.WebClient
$client.DownloadFile($AGRIDATAMISCURL,$TESTAGRIDATAMISCZIP)

Where $AGRIDATAMISCURL is a URL that looks like "https://drive.google.com/file/d/<...>" and $TESTAGRIDATAMISCZIP looks like "C:\test\A.zip"

This script doesn't return an error but the file it downloads is basically an HTML file with a prompt to sign in to Google. Is there another way to download a file that is "shared with me"?

Answer

CJBS picture CJBS · Dec 28, 2019

Share the file first

Files in Google Drive must be made available for sharing before they can be downloaded. There's no security context when running from PowerShell, so the file download fails. (To check this, rename the file with a `.html` extension, and view in a text editor).

Note: the following solution assumes that the links are to non-security-critical files, or that the links will only be given to those with whom access can be trusted (links are https, so are encrypted with transmission). The alternative is to programatically authenticate with Google - something not addressed in this answer.

To Share the file, in Google Drive:

  1. Right-click the file, and choose Get shareable link

    Get Shareable Link


2. Turn link sharing on

Link Sharing On


  1. Click Sharing Settings

Sharing Settings


  1. Ensure that Anyone with the link can view (Note that in corporate environments, the link must be shared with those outside the organization in order to bypass having to login)

Share with others


Then Download Programatically

  1. Then, code can be used to download the file as such (in this case with Windows PowerShell):

# Download the file
$zipFile = "https://drive.google.com/uc?export=download&id=1cwwPzYjIzzzzzzzzzzzzzzzzzzzzzzzz"
Invoke-WebRequest -Uri $zipFile -OutFile "$($env:TEMP)\myFile.doc"

  • Replace the 1cwwPzYjIzzzzzzzzzzzzzzzzzzzzzzzz with the ID code from the shareable link setting back in step #2, above.