简体   繁体   中英

Post to Office365 Group Connector(Webhook) using Powershell

I am trying to post a simple message to a O365 'Incoming Webhook' using powershell. Here is the code:

$url = 'https://outlook.office365.com/webhook/.......'

$body = @"
{
    "text": "Hello World!"
    "title": "Today"
}
"@

Invoke-RestMethod -Uri $url -Method Post -Body $body -ContentType "application/json"

But get this error:

PSMessageDetails      : 
Exception             : System.Net.WebException: The remote server returned an error: (404) Not Found.
                           at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.GetResponse(WebRequest request)
                           at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.ProcessRecord()
TargetObject          : System.Net.HttpWebRequest
CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
ErrorDetails          : Invalid webhook request
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : at <ScriptBlock>, <No file>: line 10
PipelineIterationInfo : {}

if i leave out the -Contentype parameter i get this error:

Microsoft.IdentityModel.Clients.ActiveDirectory.AdalServiceException: AADSTS90002: Requested tenant identifier '00000000-0000-0000-0000-000000000000' is not valid. Tenant identifiers may not be an empty GUID.
Trace ID: c4b77459-3915-475e-8125-fa2db9fd11e8
Correlation ID: 0ba64202-db52-4a96-8f44-a87b7f009170
Timestamp: 2016-03-27 07:48:02Z

anyone know how to get this to work?

Thank you for the direction. I was trying to test out an Azure WebHook. It would work on the Test method of the web page; even copied the JSON body from the page to powershell and it wouldn't work. The key was apparently specifying the

-ContentType "application/json"

However, something I found interesting, is that WebHooks in Teams do work with the default content type (which is "application/x-www-form-urlencoded") as the example post Stefan Stranger posted:

Use WebHooks Connect to Send Data from PowerShell to Microsoft Teams

Nice shortcut for them, but looks best to always specify the content type for WebHooks to be safe.

Your message body is not a valid json snippet due to a missing comma after "text" field.

Changed to

$body = @"
{
    "text": "Hello World!",
    "title": "Today"
}
"@

and it works for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM