0

I can easily send a message through to teams with this code in Powershell:

Invoke-RestMethod -Method post -ContentType 'Application/Json' -Body '{"text":"Hello World!"}' -Uri <YOUR WEBHOOK URL>

Now I'd like to instead send a variable through, but no matter what I try, it either sends what I have in it as plain text or I get the error: Invoke-RestMethod : Bad payload received by generic incoming webhook.

Here are some of the ways I've tried this:

Invoke-RestMethod -Method post -ContentType 'Application/Json' -Body '{"text":"Write-Output $cmdOutput"}' -Uri <YOUR WEBHOOK URL>

Invoke-RestMethod -Method post -ContentType 'Application/Json' -Body $cmdOutput -Uri <YOUR WEBHOOK URL>

Invoke-RestMethod -Method post -ContentType 'Application/Json' -Body Write-Output $cmdOutput -Uri <YOUR WEBHOOK URL>

The first example sends: Write-Output $cmdOutput, the other two get the error I've put above.

What am I missing? Is there a way to turn the variable to text before passing it through to teams?

I am using this for documentation: Send messages using cURL and PowerShell

Cody Brown
  • 1,409
  • 2
  • 15
  • 19
  • 2
    You need to use double quotes for interpolation to occur. `'{"text":"Write-Output $cmdOutput"}'` switch the quotes, or escape the double quotes if they're necessary. – Abraham Zinala Aug 19 '22 at 14:21
  • 2
    In short: In PowerShell, only `"..."` strings (double-quoted aka _expandable strings_) perform string interpolation (expansion of variable values), not `'...'` strings (single-quoted aka _verbatim strings_). If the string value itself contains `"` chars., escape them as `\`"` or `""`, or use a double-quoted _here-string_. See the conceptual [about_Quoting_Rules](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Quoting_Rules) help topics. – mklement0 Aug 19 '22 at 14:34
  • 2
    @mklement0 IMO what OP should actually do is avoid string interpolation and work with objects instead. Serialize to JSON as the last step before calling `Invoke-RestMethod`. Otherwise OP would have to deal with escaping string data for JSON. That's what I was about to post as an answer. – zett42 Aug 19 '22 at 14:37
  • 2
    `$json = @{ text = $cmdOutput } | ConvertTo-Json; Invoke-RestMethod -Method post -ContentType 'Application/Json' -Body $json -Uri ` – zett42 Aug 19 '22 at 14:41
  • 2
    Good point, @zett42. To elaborate on your recommendation, I've added [another duplicate](https://stackoverflow.com/a/42103607/45375) to the answer. While the latter is about escaping ``\``, it applies analogously to this use case. – mklement0 Aug 19 '22 at 14:49

0 Answers0