Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kinuasa/1c1b0677b31b058465920e53e9abeabd to your computer and use it in GitHub Desktop.
Save kinuasa/1c1b0677b31b058465920e53e9abeabd to your computer and use it in GitHub Desktop.
Google API Client Library for .NETを使用してGoogle ドライブにファイルをアップロードするPowerShellスクリプトです。エラー処理は含めていません。 関連Webサイト:https://powerusers.microsoft.com/t5/Power-Automate-Desktop/uploading-file-on-google-drive-using-api-Power-shell-script-PAD/td-p/2730269
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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment