Home > Software design >  MS Teams alert, triggered via webhook and PS script, does not want to parse the text on multiple lin
MS Teams alert, triggered via webhook and PS script, does not want to parse the text on multiple lin

Time:01-28

I'm trying to create a PS script that is supposed to post MS Teams alerts via webhooks, regarding some metrics. The current solution that I have almost made work is via a PSCustomObject, which is afterwards converted to JSON and used as the body of the alert. The below is the current code that I am using:

$JSONBody = [PSCustomObject][Ordered] @{
     "@type"     = "MessageCard"
     "title"     = "Alert Title"
     "text"      = "Alert 1: $alert1CountVariable
                    Alert 2: $alert2CountVariable
                    Alert 3: $alert3CountVariable"
}

$TeamsMessageBody = ConvertTo-Json $JSONBody -Depth 100

$parameters = @{
    "URI"          = '<Teams Webhook URI>'
    "Method"       = 'POST'
    "Body"         = $TeamsMessageBody
    "ContentType"  = 'application/json'
}

Invoke-RestMethod @parameters

Everything works as needed, but as you can see the text parameter within the PSCustomObject is supposed to parse the 3 alerts on 3 separate lines, which does not seem to happen whatever I try. I tried inserting the \n and \r operators (also tried \n and \r) and nothing works this far.

Another working method that I have is the following:

$Body = '{"text": "Alert 1: '   $alert1CountVariable  ' Alert 2: '   $alert2CountVariable  ' Alert 3: '   $alert3CountVariable  '"}'
$TeamsUrl = '<Teams Webhook URI>'
Invoke-WebRequest -Uri $TeamsUrl -Method Post -Body $Body -ContentType "application/json"

However, this also does not fully satisfy the criteria, as it still does not display the alets on separate lines and there is no title here.

Any advise on how I can make any of these two options work?

CodePudding user response:

The teams interface seems to accept HTML:

Please see your script adjusted below:

$JSONBody = [PSCustomObject][Ordered] @{
     "@type"     = "MessageCard"
     "title"     = "Alert Title"
     "text"      = "Alert 1: $alert1CountVariable <br>
                    Alert 2: $alert2CountVariable <br>
                    Alert 3: $alert3CountVariable"
}

$TeamsMessageBody = ConvertTo-Json $JSONBody -Depth 100

$parameters = @{
    "URI"          = '<Teams Webhook URI>'
    "Method"       = 'POST'
    "Body"         = $TeamsMessageBody
    "ContentType"  = 'application/json'
}

Invoke-RestMethod @parameters

I have inserted <br> at the end of each line which is a line break in HTML.

  •  Tags:  
  • Related