Skip to content

Instantly share code, notes, and snippets.

@rajeshg
Last active March 3, 2021 03:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajeshg/e14a08eb22f596dadcc610929f3478d9 to your computer and use it in GitHub Desktop.
Save rajeshg/e14a08eb22f596dadcc610929f3478d9 to your computer and use it in GitHub Desktop.
powershell script to sync to a local calendar
#
# Usage: .\sync-meetings.ps1
#
$DebugPreference = "Continue"
$VerbosePreference = "SilentlyContinue"
Add-Type -assembly "Microsoft.Office.Interop.Outlook"
$Outlook = New-Object -comobject Outlook.Application
$namespace = $Outlook.GetNameSpace("MAPI")
$calendar = $namespace.GetDefaultFolder([Microsoft.Office.Interop.Outlook.OlDefaultFolders]::olFolderCalendar)
$items = $calendar.items
# write-debug ("#of Items : {0}" -f $items.count)
$start = Get-Date
$end = $start.AddDays(5)
# query string see <https://msdn.microsoft.com/en-us/library/office/ff869597.aspx>
$condition = "[Start] >= '{0:MM/dd/yyyy} 00:00 am' AND [End] < '{1:MM/dd/yyyy} 00:00 am'" -f $start, $end
write-debug $condition
$items.IncludeRecurrences = $true
$items.Sort("[Start]")
$filteredItems = $items.Restrict($condition)
$filteredItems = $filteredItems | Where-Object {$_.subject -inotmatch 'Canceled:'}
write-debug ("#of Items in 5 days : {0}" -f $filteredItems.count) # Sync for 5 days
# Uncomment the below 3 lines to export to CSV file at C:\temp\ocal.csv
# $filteredItemsToWrite = $filteredItems | Select-Object -Property subject,location,Organizer,StartInStartTimeZone,EndInEndTimeZone
# Write-Verbose "export items..."
# $filteredItemsToWrite | export-csv -Encoding utf8 -path c:\temp\ocal.csv -NoTypeInformation
$MyTargetCal = $calendar.Folders.Item("SyncCal")
# cleanup current events and write again
for ($i=1; $i -le 5; $i++)
{
$ToDeleteItems = $MyTargetCal.Items
# write-debug ("Deleting {0} events from SyncCal calendar before syncing again" -f $ToDeleteItems.count)
$ToDeleteItems | ForEach-Object{ $_.Delete() }
}
write-debug ("Items left after cleanup in SyncCal: {0}" -f $MyTargetCal.Items.count)
# Write events one by one
Foreach ($item in $filteredItems)
{
write-debug ("creating event {0}" -f $item.subject)
$meeting = $MyTargetCal.Items.Add(1)
$meeting.Subject = $item.subject
$meeting.Body = $item.Body
$meeting.Location = $item.location
$meeting.Start = $item.StartInStartTimeZone
$meeting.End = $item.EndInEndTimeZone
$meeting.Save()
}
Write-Verbose "done."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment