Skip to content

Instantly share code, notes, and snippets.

@brettmillerb
Last active August 28, 2020 23:54
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 brettmillerb/acd9e2f2973b40b872921266e0019153 to your computer and use it in GitHub Desktop.
Save brettmillerb/acd9e2f2973b40b872921266e0019153 to your computer and use it in GitHub Desktop.
Teams JSON String Creation of Teams Webhook Content

I wanted a way to dynamically build output in Azure Automation for a database migration.

# Create the internal sections first with ElasticPoolName and databases joined with \n\n (new line in Teams)
$sections = $dbsPerElasticPool | ForEach-Object {
    New-TeamsSection -ActivityTitle ('ElasticPool: **{0}**' -f $_.ElasticPool) -Value ($_.databases -join '\n\n')
}

# Create the rest of the card with the sections
$card = New-TeamsMessageCard -Sections $sections | ConvertTo-Json -Depth 5

# Required as ConvertTo-Json Escapes the newline strings 🤷‍♂️
$body = $card -replace '\\\\n\\\\n', '\n\n'

Invoke-RestMethod -Uri $webhookuri -Body $body -Method Post
function New-TeamsMessageCard {
[CmdletBinding()]
param(
[string]
$Title = 'Elastic Pools Migrated Today {0}' -f (Get-Date -Format FileDate),
[string]
$Summary = 'Elastic Pool Migration Status',
[array]
$Sections
)
$outputHash = @{
"@type" = "MessageCard"
"@context" = 'https://schema.org/extensions'
title = $Title
summary = $Summary
}
if ($PSBoundParameters.ContainsKey('Sections')) {
$outputHash.Add('sections', $Sections) | Out-Null
}
[PSCustomObject]$outputHash
}
function New-TeamsSection {
[cmdletbinding()]
param (
[string]
$ActivityTitle,
[string]
$Value
)
[PSCustomObject]@{
activityTitle = $ActivityTitle
facts = @(
@{
name = 'Databases'
value = $Value
}
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment