Skip to content

Instantly share code, notes, and snippets.

@ConnorGriffin
Last active January 18, 2018 21:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ConnorGriffin/8e846a8dc92572264102baea2dfa3f70 to your computer and use it in GitHub Desktop.
Save ConnorGriffin/8e846a8dc92572264102baea2dfa3f70 to your computer and use it in GitHub Desktop.
Google Drive Upload Excerpt
<#
This is a fairly simple one-time upload with no options, etc. Consider using this as a base to create a New-GDriveItem type function
Modified code, in response to: https://monteledwards.com/2017/03/05/powershell-oauth-downloadinguploading-to-google-drive-via-drive-api/
You should follow the above link to set $accessToken to your access token and understand what is happening here
#>
# Change this to the file you want to upload
$SourceFile = 'C:\Path\To\File'
# Get the source file contents and details, encode in base64
$sourceItem = Get-Item $sourceFile
$sourceBase64 = [Convert]::ToBase64String([IO.File]::ReadAllBytes($sourceItem.FullName))
$sourceMime = [System.Web.MimeMapping]::GetMimeMapping($sourceItem.FullName)
# Set the file metadata
$uploadMetadata = @{
originalFilename = $sourceItem.Name
name = $sourceItem.Name
description = $sourceItem.VersionInfo.FileDescription
}
# Set the upload body
$uploadBody = @"
--boundary
Content-Type: application/json; charset=UTF-8
$($uploadMetadata | ConvertTo-Json)
--boundary
Content-Transfer-Encoding: base64
Content-Type: $sourceMime
$sourceBase64
--boundary--
"@
# Set the upload headers
$uploadHeaders = @{
"Authorization" = "Bearer $accessToken"
"Content-Type" = 'multipart/related; boundary=boundary'
"Content-Length" = $uploadBody.Length
}
# Perform the upload
$uploadUri = 'https://www.googleapis.com/upload/drive/v3'
$response = Invoke-RestMethod -Uri "$uploadUri/files?uploadType=multipart" -Method Post -Headers $uploadHeaders -Body $uploadBody
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment