Another script from a couple of months ago
With Microsoft pushing "Service Update XX" almost every week it became hard to track down when particular update is going to be released.
Powershell script uses application registered in AAD with privileges to read messages from Office 365 Communication API and access D365 to create appointments. Appointments are set category and subcategory to identify unique messages without customizations. Recipients of the appointment are defined as a list of activity parties.
# | |
# With Microsoft pushing "Service Update XX" almost every week it became hard | |
# to track down when particular update is going to be released. | |
# This script uses application registered in AAD with privileges to read | |
# messages from Office 365 Communication API and access D365 to create | |
# appointments. Appointments are set category and subcategory to identify | |
# unique messages without customizations. Recipients of the appointment are | |
# defined as a list of activity parties. | |
# | |
# https://www.nuget.org/packages/Microsoft.IdentityModel.Clients.ActiveDirectory/ | |
Add-Type -Path "Microsoft.IdentityModel.Clients.ActiveDirectory.dll" | |
function Get-AccessToken { | |
[CmdletBinding()] | |
param ( | |
[Parameter(Mandatory=$true)][string]$Tenant, | |
[Parameter(Mandatory=$true)][guid]$ClientID, | |
[Parameter(Mandatory=$true)][string]$ClientSecret, | |
[Parameter(Mandatory=$true)][string]$Resource | |
) | |
process { | |
$authority = "https://login.microsoftonline.com/$Tenant" | |
$clientCredential = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential($ClientID, $ClientSecret) | |
$authContext = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext($authority) | |
$authContext.AcquireTokenAsync($Resource, $clientcredential).Result.AccessToken | |
Write-Verbose "AccessToken Acquired" | |
} | |
} | |
function Get-CommsHeaders { | |
[CmdletBinding()] | |
param ( | |
[Parameter(Mandatory=$true)][string]$AccessToken | |
) | |
process { | |
@{ | |
"Content-Type" = "application/json" | |
"Authorization" = "Bearer $($AccessToken)" | |
} | |
} | |
} | |
function Get-DynHeaders { | |
[CmdletBinding()] | |
param ( | |
[Parameter(Mandatory=$true)][string]$AccessToken | |
) | |
process { | |
@{ | |
"Content-Type" = "application/json; charset=utf-8" | |
"OData-MaxVersion" = "4.0" | |
"OData-Version" = "4.0" | |
"Accept" = "application/json" | |
"Authorization" = "Bearer $($AccessToken)" | |
} | |
} | |
} | |
function Get-AppoitnmentPayload { | |
[CmdletBinding()] | |
param ( | |
[Parameter(Mandatory=$true, ValueFromPipeline = $true)][psobject]$Item | |
) | |
process { | |
$id = $Item.Id | |
if(-not $Item.AffectedWorkloadNames.Contains("DynamicsCRM")) { return } | |
$Item | ConvertTo-Json | Out-File -FilePath ".\messages\$id.json" | |
$msg = $Item.Messages[-1].MessageText -replace '<[^>]+>','' | |
if($msg -match "Maintenance window start:\s*([^\n]+)\n") { | |
$maintenanceStart = [DateTime]::ParseExact($matches[1], "dd MMMM yyyy, HH:mm UTC", [CultureInfo]::InvariantCulture, [System.Globalization.DateTimeStyles]::AssumeUniversal) | |
} | |
if($msg -match "Maintenance window end:\s*([^\n]+)\n") { | |
$maintenanceEnd = [DateTime]::ParseExact($matches[1], "dd MMMM yyyy, HH:mm UTC", [CultureInfo]::InvariantCulture, [System.Globalization.DateTimeStyles]::AssumeUniversal) | |
} | |
@{ | |
scheduledstart = $maintenanceStart.ToUniversalTime().ToString("s")+"Z" | |
scheduledend = $maintenanceEnd.ToUniversalTime().ToString("s")+"Z" | |
subject = $Item.Title | |
description = "$msg`n`n$($Item.ExternalLink)" | |
category = "ServiceComms" | |
subcategory = $id | |
appointment_activity_parties = $activityParties | |
} | |
} | |
} | |
# Stop if error occurs | |
$ErrorActionPreference = "Stop" | |
#################### CONFIGURATION | |
# Tenant | |
$tenant = "yourtenant.onmicrosoft.com" | |
# Azure Portal > Azure Active Directory > App Registrations > App (DynReleaseCalendar) | |
# Required API Permissions (Admin consent should be granted for tenant) | |
# Dynamics CRM (1) | |
# user_impersonation Delegated Access Common Data Service as organization users | |
# Office 365 Management APIs (1) | |
# ServiceHealth.Read Application Read service health information for your organization | |
# | |
# Add S2S Application user to Dynamics and assign appropriate role | |
# Detailed tutorial: https://community.dynamics.com/crm/b/debajitcrm/archive/2018/08/16/step-by-step-guide-query-dynamics-crm-web-api-using-server-to-server-authentication-with-application-user | |
$clientId = "00000000-0000-0000-0000-000000000000" | |
# Azure Portal > Azure Active Directory > App Registrations > App (DynReleaseCalendar) > Client secrets | |
$clientSecret = "asdf.123trjd-asdfgh-as+df*hj*kl" | |
# Organization url | |
$orgUrl = "https://yourorg.crm4.dynamics.com" | |
# List of activity parties | |
# partyid_systemuser paired with /systemusers(guid); partyid_contact with /contacts(guid); partyid_account with /accounts(guid); etc | |
# ParticipationTypeMask: https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/activityparty-entity#activity-party | |
# 7 - Organizer | |
# 5 - RequiredAttendee | |
# 6 - OptionalAttendee | |
$activityParties = @( | |
@{ | |
# Organizer must be set, "Appointments, Contacts and Tasks" sync must be enabled | |
"participationtypemask" = 7 | |
"partyid_systemuser@odata.bind" = "/systemusers(0ae18442-7037-4849-9e9f-4ef153fb118e)" | |
}, | |
@{ | |
# OptionalAttendee, contact with email address | |
"participationtypemask" = 6 | |
"partyid_contact@odata.bind" = "/contacts(b63bf83c-9088-e911-a97a-000d3ab10a26)" | |
} | |
) | |
#################### END OF CONFIGURATION | |
$commsToken = Get-AccessToken -Tenant $tenant -ClientID $clientId -ClientSecret $clientSecret -Resource "https://manage.office.com" | |
$dynToken = Get-AccessToken -Tenant $tenant -ClientID $clientId -ClientSecret $clientSecret -Resource $orgUrl | |
# create folder to store individual messages (not really required) | |
if(-not (Test-Path "messages")) { New-Item -Path "messages" -ItemType Directory | Out-Null } | |
$commsJson = Invoke-RestMethod -Uri "https://manage.office.com/api/v1.0/$tenant/ServiceComms/Messages" -Headers (Get-CommsHeaders -AccessToken $commsToken) | |
if(-not $commsJson -or -not $commsJson.value) { | |
Write-Error "Unexpected response" $commsJson | |
} | |
foreach($val in $commsJson.value) { | |
$id = $val.Id | |
if(-not $val.AffectedWorkloadNames.Contains("DynamicsCRM")) { continue } | |
# just store individual message json | |
$val | ConvertTo-Json | Out-File -FilePath ".\messages\$id.json" | |
$body = Get-AppoitnmentPayload -Item $val | |
# Check if appointment already exists | |
$url = "$orgUrl/api/data/v9.1/appointments?`$select=activityid,subject,description,scheduledstart,scheduledend&`$filter=category eq '$($body.category)' and subcategory eq '$($body.subcategory)'" | |
$appt = Invoke-RestMethod -Uri $url -Headers (Get-AuthenticationHeaders -AccessToken $dynToken) | |
if($appt -and $appt.value -and $appt.value.Count -gt 0) { | |
# Update only first matching | |
$activityid = $appt.value[0].activityid | |
$id = $body.subcategory | |
$body.Remove("appointment_activity_parties") | |
$body.Remove("category") | |
$body.Remove("subcategory") | |
if($body.scheduledstart -eq $appt.value[0].scheduledstart) { $body.Remove("scheduledstart") } | |
if($body.scheduledend -eq $appt.value[0].scheduledend) { $body.Remove("scheduledend") } | |
# Strip all non-word characters for comparison (had some issues with dash vs hyphen) | |
if(($body.subject -replace "[\W]+", "") -eq ($appt.value[0].subject -replace "[\W]+", "")) { $body.Remove("subject") } | |
if(($body.description -replace "[\W]+", "") -eq ($appt.value[0].description -replace "[\W]+", "")) { $body.Remove("description") } | |
# Update existing appointment if something has changed | |
if($body.Count -gt 0) { | |
Write-Verbose "Updating appointment for $id." | |
Invoke-RestMethod -Method Patch -Uri "$dynUrl/api/data/v9.1/appointments($activityid)" -Headers (Get-DynHeaders -AccessToken $dynToken) -Body ($body | ConvertTo-Json) | |
} | |
}else{ | |
# Insert a new appoitnment | |
Invoke-RestMethod -Method Post -Uri "$dynUrl/api/data/v9.1/appointments" -Headers (Get-DynHeaders -AccessToken $dynToken) -Body ($body | ConvertTo-Json) | |
Write-Verbose "Created appointment for $($body.subcategory)." | |
} | |
} | |
# | |
# The MIT License (MIT) | |
# | |
# | |
# Copyright (c) 2019 milolav. | |
# | |
# | |
# Permission is hereby granted, free of charge, to any person obtaining a copy | |
# of this software and associated documentation files (the "Software"), to deal | |
# in the Software without restriction, including without limitation the rights | |
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
# copies of the Software, and to permit persons to whom the Software is | |
# furnished to do so, subject to the following conditions: | |
# | |
# | |
# The above copyright notice and this permission notice shall be included in all | |
# copies or substantial portions of the Software. | |
# | |
# | |
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
# SOFTWARE. | |
# | |
# |
Top comments (0)