PowerShell – OAuth & Downloading,Uploading to Google Drive via Drive API

Google offers a REST API that can be accessed via PowerShell to Upload, Download, and change files relatively easily.

Where does this come handy? This could be used to dynamically process Active Directory, Office 365, employee onboarding workflows, or any other system changes off a Google Sheet. This also allows the sysadmin to routinely upload logs, backup files, or any other data to Google Drive as apart of their job process.

This guide shows from start to finish how to generate an OAuth token, Download a file, and upload a file to Google Drive via the Drive REST HTTP API.

Create Project and OAuth Tokens

  1. Go to https://console.developers.google.com/iam-admin/projects?
  2. Create a new project
  3. Enable the Drive API by selecting the Drive API and selecting enable API , after creating your project.
  4. Click Credentials
  5. Create OAuth Client ID Credentials
  6. Select Web Application as product type
  7. Configure the Authorized Redirect URI to https://developers.google.com/oauthplayground must not have a ending “/” in the URI
  8. Save your client ID and Secret
  9. Browse to https://developers.google.com/oauthplayground
    This saves us time from generating an OAuth request in PowerShell. This is where we will authorize our Project to our Google Account using our provided Client ID and Client Secret. 
  10. Click the gear in the right-hand corner and select “Use your own OAuth credentials
  11. Authorize the https://www.googleapis.com/auth/drive API
  12. Click “Exchange Refresh Token for Access Token”
    explanation – Access Tokens have a limited lifetime (approximately 60 minutes) whereas Refresh Tokens last indefinitely (some exclusions here). The Access Token is what you will hardcode into your script, configuring the script to hit the Google Identity Platform to request a Refresh Token on execution. 
  13. Save your Refresh Token

Get Auth Token & Download

Now that we have our Refresh Token, Client ID, Client Secret we can request an Access Token with PowerShell.  Random but lookalike values gave for variables.

note that Invoke-RestMethod was used instead of Invoke-WebRequest. Invoke-RestMethod returns the output to a JSON object that we can easily work with going forward.

Our access token is now  $accessToken = $GAuthResponse.access_token .

Now that we have the Access Token, downloading from Drive is pretty straight forward.

Notice here that I am requesting to download a Google Sheet as CSV. This is done by calling /{DocumentID}/export?mimeType=txt/csv against the API endpoint. Other formats are supported depending on your file type, or /export can removed if the file is not a G Suite file type. More info on this here.

Uploading to Drive

Traditionally, uploads to Drive are sent via 2 requests. One to send file metadata to get the DocumentID, the second to PUT the contents of the file to the DocumentID. However, the  https://www.googleapis.com/upload/drive/v2/files endpoint supports Multi part uploads, allowing us to send metadata and file contents in one request.

 

 

 

14 thoughts on “PowerShell – OAuth & Downloading,Uploading to Google Drive via Drive API

  1. I am attempting to upload an .xls file to google drive. I do not see in this example where to specify the location of the file I am uploading. Example: My file is at C:\Temp\Testfile.xls
    Where does that get specified in this example?

    1. $title = “My Document Title” is where the title of the document is configured.
      You’ll have to change the mime type to spreadsheet and also use Get-Content to load the file.

      1. Referring to Matthew’s post, $title is where we need to specify the path to the file we are uploading?

        For example:
        $title = Get-Content C:\Users\user\Desktop\Testfile.xls

        I’m getting an “Invoke-WebRequest : Input string was not in a correct format.” error.

        1. Justin,
          Get-content is used to just load the bytes of the file to be sent. $title should be set as the name of the file. You’ll concatenate the file name for $title, and then use Get-Content for $togoogle.

  2. Thank you for your well explained post. It has been very helpful.

    I’m looking to upload .zip files. Is this possible with Powershell and the Drive API?

    Thank you!

  3. I get malformed multipart body error when trying to execute your code. Could you check if it’s the case on your side as well?

      1. @Connor I don’t see a place to enter the google drive folder id in your script. Where are you specifying a destination?

        1. Leo,

          If you need more assistance, feel free to email me. connor[at]connorcg[dot]com. I don’t get notified to responses here, so I apologize for the delayed response.

          My script was created more as a base than as a fully functional script. It works for uploading a single file to the root of your Google Drive. If you need additional functionality, I have provided a solid enough base for you to add on, similar to what montel has provided. You can review the Google Drive v3 API to find out how to perform additional actions.

          That said, to upload to a folder, add the ID of the folder to the uploadMetadata in an array:
          $uploadMetadata = @{
          originalFilename = $sourceItem.Name
          name = $sourceItem.Name
          description = $sourceItem.VersionInfo.FileDescription
          parents = @(‘folderId’)
          }

          For a team drive upload, modify $uploadMetadata and the Invoke-RestMethod URI. Use the teamDriveId in the Parents array for an upload to the root of the team drive. Provide a folder ID instead to upload to a folder within the team drive.
          $uploadMetadata = @{
          originalFilename = $sourceItem.Name
          name = $sourceItem.Name
          description = $sourceItem.VersionInfo.FileDescription
          parents = @(‘teamDriveId or folderId’)
          teamDriveId = ‘teamDriveId’
          }
          […rest of the script…]
          $response = Invoke-RestMethod -Uri “$uploadUri/files?uploadType=multipart&supportsTeamDrives=true” -Method Post -Headers $uploadHeaders -Body $uploadBody

      2. Connor, you are correct. Thank you for sharing this. Your method looks much more clean. Can’t wait to see your modules!

  4. Hi,
    thanks for the great article. I’m trying to upload to my google drive an archive .cbr
    but i get
    “Invoke-WebRequest : You must write ContentLength bytes to the request stream before calling [Begin]GetResponse.”

    i changed $imputmime = application/vnd.google-apps.file
    then as suggested $togoogle = get-content

    what am i missing? any help is appreciated.
    Matthew

Leave a Reply

Your email address will not be published. Required fields are marked *