前回に続き、PowerShellを使ってGoogleカレンダーを操作する方法を書いていきます。
今回は、新しい予定を追加する書き方です。
PowerShellでGoogleカレンダーを操作するシリーズ
PowerShellでGoogleカレンダーを操作する - 適材適所
事前準備
今回もGoogle APIの公式リファレンスを参考にします。
.NETの予定追加の例を見ると、C#の例がでてきます。
基本的には、これをPowerShell風に書き直してあげます。
よく見ると、コードの上になにやら注意書きが書いてありますね。
// Refer to the .NET quickstart on how to setup the environment: //https://developers.google.com/calendar/quickstart/dotnet // Change the scope to CalendarService.Scope.Calendar and delete any stored // credentials.
.QuickStartを参考に環境を構築しておいてね、あとスコープを変更して、他の認証情報は全部消しておいてね
とGoogle様が仰せのようなので、前回のコードで作成された「token.json」フォルダを削除しておきます。
credentials.jsonはそのままにしておきます。
これで準備完了です。
流れ
流れは前回と全く同じです。
簡単に書くと、
- Nugetから下記をダウンロード ・Newtonsoft.Json ・Google.Apis.Core ・Google.Apis ・Google.Apis.Auth ・Google.Apis.Calendar.v3
- インストール
- 認証
- カレンダーへの追加処理
という順です。
前回との違いは、認証の際のスコープを変更することです。
コード
.NETの予定追加の例を参考に、 コード全体をPowerShell風に書き直したものがこちら。
#packageの読み込み準備 $dir="$PSScriptRoot\" $package=@( ("Newtonsoft.Json","12.0.3"), ("Google.Apis.Core","1.46.0"), ("Google.Apis","1.46.0"), ("Google.Apis.Auth","1.46.0"), ("Google.Apis.Calendar.v3","1.46.0.1986") ) #dllのインストール for($i=0;$i -lt $package.Count;$i++){ $name=$package[$i][0] $version=$package[$i][1] if(!(Test-Path "$dir$name.$version")){ Install-Package $name -Source nuget -Scope CurrentUser -SkipDependencies -Destination $dir -RequiredVersion $version|out-null } } ##アセンブリの読み込み $target="net45" for($i=0;$i -lt $package.Count;$i++){ $name=$package[$i][0] $version=$package[$i][1] Add-Type -path (Join-Path "$dir$name.$version" "lib\$target\$name.dll") -ReferencedAssemblies (Join-Path $dir "$name.$version\lib\$target\$name.xml")|Out-Null } #ここのスコープが前回と異なります。 [string[]]$scope=[Google.Apis.Calendar.v3.CalendarService+Scope]::Calendar $ApplicationName = "Google Calendar API .NET Quickstart"; $open=[System.IO.FileMode]::Open $read=[System.IO.FileAccess]::Read $stream= New-Object System.IO.FileStream -ArgumentList (Join-Path $dir "sclient_secret.json"),$open,$read $secrets=([Google.Apis.Auth.OAuth2.GoogleClientSecrets]::Load($stream)).Secrets $credPath=(Join-Path $dir "token.json") $dataStore=[Google.Apis.Util.Store.FileDataStore]::new($credPath,$true) $credential= ([Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker]::AuthorizeAsync( $secrets,$scope,"user",[System.Threading.CancellationToken]::None,$dataStore)).Result; Write-Host ("Credential file saved to: " + $credPath) ##Create Google Calendar API service. $baseClient=New-Object Google.Apis.Services.BaseClientService+Initializer $baseClient.HttpClientInitializer =$credential $baseClient.ApplicationName=$ApplicationName $service=New-Object Google.Apis.Calendar.v3.CalendarService($baseClient) #新しいイベントを作成します $newEvent=New-Object Google.Apis.Calendar.v3.Data.Event $newEvent.Summary="Google Api Test" $newEvent.Location="東京都中央区" $newEvent.Description="meeting" #開始日 $start=New-Object Google.Apis.Calendar.v3.Data.EventDateTime $start.DateTime=[System.DateTime]::Parse("2020/7/1 10:00:00") $start.TimeZone="Asia/Tokyo" #終了日 $end=New-Object Google.Apis.Calendar.v3.Data.EventDateTime $end.DateTime=[System.DateTime]::Parse("2020/7/1 12:00:00") $end.TimeZone="Asia/Tokyo" $newEvent.Start=$start $newEvent.End=$end #2日連続 [string[]]$recurrence="RRULE:FREQ=DAILY;COUNT=2" $newEvent.Recurrence=$recurrence #他の参加者(ここで設定したメールアドレスにメールが飛びます) $attendees1=New-Object Google.Apis.Calendar.v3.Data.EventAttendee $attendees1.Email="large@example.com" $attendees2=New-Object Google.Apis.Calendar.v3.Data.EventAttendee $attendees2.Email="sbrin@example.com" $attendeesList=New-Object System.Collections.Generic.List[Google.Apis.Calendar.v3.Data.EventAttendee] $attendeesList.Add($attendees1) $attendeesList.Add($attendees2) $newEvent.Attendees=$attendeesList #通知の設定 $remainders=New-Object Google.Apis.Calendar.v3.Data.Event+RemindersData $remainders.UseDefault=$false $newRemainder1=New-Object Google.Apis.Calendar.v3.Data.EventReminder $newRemainder1.Method="email" $newRemainder1.Minutes=24*60 $newRemainder2=New-Object Google.Apis.Calendar.v3.Data.EventReminder $newRemainder2.Method="sms" $newRemainder2.Minutes=10 $remainderList=New-Object System.Collections.Generic.List[Google.Apis.Calendar.v3.Data.EventReminder] $remainderList.Add($newRemainder1) $remainderList.Add($newRemainder2) $remainders.Overrides=$remainderList $calendarId="primary" $request=$service.Events.Insert($newEvent,$calendarId) $createdEvent=$request.Execute() Write-Host ("Created:{0}" -f $createdEvent.HtmlLink)
注意
参加者に架空のアドレスを指定しているので、これを実行すると、Delivery Status Notification (Failure)メールが飛んできます。
私はテストで何回も実行したので、受信トレイが埋め尽くされました。
テストされるときはご留意ください。
おわりに
あっさりGoogle カレンダーに予定を追加できました。
Googleカレンダーへの予定の追加は他にもあるので、次回、紹介したいと思います。
ここまでお読みいただき、ありがとうございました。