PowershellでOutlookのある期間内のメールや予定の抽出をしようとした時に混乱したのでメモする。ちょっとしたことなので、どこかで他の記事にマージするかも…
Itemsの絞り込み
Outlookのメールや予定を表すItems
というオブジェクトを扱う(Itemsの説明)。Items
では対象を絞り込むメソッドが2種類あり、
-
Find(condition)
+FindNext()
- 1つ1つ走査する(イテレータのイメージ)
- https://docs.microsoft.com/en-us/office/vba/api/outlook.items.find
-
Restrict(condition)
+foreach
という操作ができるようになっている。
時刻で抽出する
condition
は文字列で[Subject]='Test'
のように、条件を指定する。時刻の場合、PowershellとOutlookの時刻の表現はどちらもローカル時間だが、フォーマットが違うので注意が必要。
-
Get-Date
: ローカル時間。 -
Items.Find
: ローカル時間。フォーマットは'MM/dd/yyyy hh:mm'
で、引用符が必要。 -
Items.Restrict
:Items.Find
と同じ。
なので、例えば現在時刻以降の開始日を条件とするなら、
$now = Get-Date
$condition= "[Start]>'{0}'" -f $now.ToString("MM/dd/yyyy hh:mm")
繰り返しの会議を抽出する
定例会は「繰り返し」設定されている場合、何も指定しないと最初の1つしか抽出されない。「Search the Calendar for Appointments that Occur Partially or Entirely in a Given Time Period」によると、以下の手順が必要とのことだった。
- [Start]でソートする
- フィルタをかける
(原文抜粋) To include recurrent appointments in the query, it sets Items.IncludeRecurrences to True and then sorts the items by the AppointmentItem.Start property. It then builds the query for all appointments that begin on or before myEnd, and end on or after myStart. It then applies the query to items in the default calendar folder, using the ** Items.Restrict** method, and then prints the start time of all the returned appointments.
これはPowershellでは以下のようになる。
$mapi = $outlook.GetNameSpace("MAPI")
# 予定表(フォルダ)を表す数値
# olFolderCalendar = 9
# https://docs.microsoft.com/ja-jp/office/vba/api/outlook.oldefaultfolders
$calendarFolder = $mapi.GetDefaultFolder( $olFolderCalendar )
$items = $calendarFolder.Items;
# 検索条件
$now = Get-Date
$condition= "[Starts]>'{0}'" -f $now.ToString("MM/dd/yyyy hh:mm")
# ここから、繰り返しの予定を検索するための準備
$items.IncludeRecurrences = $true;
$items.Sort( '[Start]' );
$filtered = $items.Restrict( $search )
# 結果を見てみる
# olAppontmentはItemがAppointment Itemであるかを確認するための数値
# https://docs.microsoft.com/ja-jp/office/vba/api/outlook.olobjectclass
foreach( $item in $$filtered ) {
if( $item.Class -eq $olAppointment ) {
"{0} {1}" -f $item.Subject, $item.Start.DateTime | Write-Host
}
}
# Javascript
new Date( 数値 )とすることで、1970/1/1 0:00:00(GMT) からのミリ秒で時間を表せる。`valueOf()`メソッドで数値に戻せるので、グラフで表示したいときに役立つ。