
Announcements
Hi Team,
I am trying to upload file on google drive using api Powershell script.
file get added on google drive but file name is not comming its come Untitled,
also not able to view the upladed file
what is an issue
Here is my script
# Web API endpoint URL
$apiUrl = %Google%
# Input file path
$inputFilePath = "C:\Users\sanket.shinde\Downloads\Krishna.png"
# API token
$apiToken = "provided"
$fileName = "Demo"
try {
# Create a WebClient object
$webClient = New-Object System.Net.WebClient
# Set the Authorization header with the API token
$webClient.Headers.Add("Authorization", "Bearer $apiToken")
# Upload the file using multipart/form-data
$responseBytes = $webClient.UploadFile($apiUrl, "POST", $inputFilePath)
Write-Output "file saved successfully."
}
catch {
Write-Output "An error occurred: $_"
}
The code in the link below may be a useful reference for how to upload files using the Google Drive API in PowerShell.
*GDrive Upload PowerShell Script - GitHub
https://gist.github.com/ConnorGriffin/dc804357bb10ff7522d0e21ddfdf9398
Alternatively, if you are using the API Client Library for .NET, the code might look something like the one below.
Add-Type -AssemblyName "System.Web"
[void][Reflection.Assembly]::LoadFile("C:\System\Lib\Newtonsoft.Json.dll")
[void][Reflection.Assembly]::LoadFile("C:\System\Lib\Google.Apis.dll")
[void][Reflection.Assembly]::LoadFile("C:\System\Lib\Google.Apis.Core.dll")
[void][Reflection.Assembly]::LoadFile("C:\System\Lib\Google.Apis.Auth.dll")
[void][Reflection.Assembly]::LoadFile("C:\System\Lib\Google.Apis.Drive.v3.dll")
$clientId = "(Client ID)"
$clientSecret = "(Client Secret)"
$credentialPath = "C:\wk\GoogleAPI\client_secrets.json"
$uploadFilePath = "C:\Test\SamplePDF.pdf"
#[String[]]$parents = @("1*_**********_*****************") #Folder ID
[String[]]$parents = @("root")
#Get AccessToken
$clientSecrets = [Google.Apis.Auth.OAuth2.ClientSecrets]::new()
$clientSecrets.ClientId = $clientId
$clientSecrets.ClientSecret = $clientSecret
[String[]]$scopes = @("https://www.googleapis.com/auth/drive")
$credential = [Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker]::AuthorizeAsync(
$clientSecrets,
$scopes,
"user",
[System.Threading.CancellationToken]::None,
[Google.Apis.Util.Store.FileDataStore]::new($credentialPath, $true)).Result
#Upload file to Google Drive
$service = [Google.Apis.Drive.v3.DriveService]::new()
$uploadFileName = [System.IO.Path]::GetFileName($uploadFilePath)
$mimeType = [System.Web.MimeMapping]::GetMimeMapping($uploadFilePath)
$stream = [System.IO.FileStream]::new($uploadFilePath, [System.IO.FileMode]::Open)
$body = [Google.Apis.Drive.v3.Data.File]::new()
$body.Name = $uploadFileName
$body.MimeType = $mimeType
$body.Parents = $parents
$request = $service.Files.Create($body, $stream, $mimeType)
$request.AccessToken = $credential.Token.AccessToken
$request.Upload()
$stream.Close()