
Import calendar event through impersonation – O365
Sometimes, for several reasons, you’ll have to import calendar events into users mailbox in O365.
That could be done using different methods, directly using a service account (with a mailbox !), impersonated (as if the user created the event).
Here below is a quick example of a small script (powershell of course ! )
O365 connexion :
Import-Module MSOnline $O365Cred = Get-Credential $O365Session = New-PSSession –ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $O365Cred -Authentication Basic -AllowRedirection Import-PSSession $O365Session -AllowClobber Connect-MsolService –Credential $O365Cred
In my case, I have to fulfill all roommailboxes calendar using a csv extrat from an old tool. Those meetings have to be created by the user, and autoaccepted by rooms.
#Locate Microsoft Exchange Webservices dll Import-Module -Name "C:\scripts\tools\office365_license_mgmt\Office365Mgmt\Microsoft.Exchange.WebServices.dll" $ExchangeService = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2013) $creds = New-Object System.Net.NetworkCredential($O365Cred.UserName.ToString(),$O365Cred.GetNetworkCredential().password.ToString()) $ExchangeService.Credentials = $creds #Enable impersonation to book into the user's calendar $ExchangeService.ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress,$MeetingAuthor) $ExchangeService.AutodiscoverUrl("$MeetingAuthor", {$true})
Then you’ll have to create your event, based on your import file:
#Formating Event $appointment = New-Object Microsoft.Exchange.WebServices.Data.Appointment -ArgumentList $ExchangeService $appointment.Subject = "$SubjectM" $appointment.Location="$RoomName" $appointment.Body = $Body $appointment.Id.UniqueId #$appointment.RequiredAttendees.Add("$($MeetingAuthor)") $appointment.RequiredAttendees.Add("$($RoomMail)") $Appointment.ReminderMinutesBeforeStart=60 $appointment.Start = Get-Date "$startdate" -Hour $StartTimeHour -Minute $StartTimeMinute $appointment.End = Get-Date "$EndDate" -Hour $EndTimeHour -Minute $EndTimeMinute $appointment.IsAllDayEvent = $false $appointment.LegacyFreeBusyStatus = [Microsoft.Exchange.WebServices.Data.LegacyFreeBusyStatus]::Busy $appointment.IsReminderSet = $false
And finally, just save it !
$appointment.Save([Microsoft.Exchange.WebServices.Data.SendInvitationsMode]::SendOnlyToAll) | out-null
And, of course, close that pssession at the end !
#Closing remote Session to O365 Get-Pssession | Remove-Pssession