I am trying to upload JSON file in google drive using Powershell. I have generated an OAUTH credentials to connect to google drive and using this credentials to upload JSON file in the google drive but I am receiving an 400 Bad Request error at Invoke-restmethod. I am not sure what I am doing wrong here. I have gone through lots of site but no luck.Any helps will be appreciated.

My code:-

$ClientID="xxxxxxxxx.apps.googleusercontent.com"
$ClientSecret="xxxxxx"
$RefreshToken="https://oauth2.googleapis.com/token"

$params = @{
Uri = 'https://accounts.google.com/o/oauth2/token'
Body = @(
 "refresh_token=$RefreshToken", 
 "client_id=$ClientID",         
 "client_secret=$ClientSecret", 
 "grant_type=refresh_token"
    
 ) -join '&'
 Method = 'Post'
 ContentType = 'application/x-www-form-urlencoded'
 }
 $accessToken = (Invoke-RestMethod @params).access_token

# Change this to the file you want to upload
$SourceFile = 'C:\check.json'

# 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)

# If uploading to a Team Drive, set this to 'true'
$supportsTeamDrives = 'false'

# Set the file metadata
$uploadMetadata = @{
originalFilename = $sourceItem.Name
name = $sourceItem.Name
description = $sourceItem.VersionInfo.FileDescription
#parents = @('my-drive') 
#teamDriveId = ‘teamDriveId’            
}

# 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" = '"application/json"; boundary=boundary'
"Content-Length" = $uploadBody.Length
}

# Perform the upload
$response = Invoke-RestMethod -Uri "https://www.googleapis.com/upload/drive/v3/files?    uploadType=multipart&supportsTeamDrives=$supportsTeamDrives" -Method Post -Headers $uploadHeaders -Body $uploadBody

Error I am getting

0

There are 0 best solutions below