Send Message to Slack and Mattermost via PowerShell
akhilsharmascripting

Send Message to Slack and Mattermost via PowerShell


This is one of the most searched and implemented logic when we talk about alerts or notifications. In our fast moving and busy schedule, we need alerts and notifications to directly come to us and update us for all kind of important updates. Gone are the days when we use to manually check and then notify the teams that there’s some kind of alert or notification for them.

Most of IT industry use Slack and Mattermost as their team collaboration software. In or out, you are always connected and updated by the means of these communication channels. People talk, people share, people discuss everything on these collaboration software.

In this post, lets discuss how to send message to these collaboration software via PowerShell.

In order to send the message to Slack/Mattermost, we write a small PowerShell script that will do the work for us. We’ll be leveraging Invoke-RestMethod of powershell for this.

Prerequisites
Uri – Your webhook url
– Channel – Your Slack/Mattermost channel name

$payload = @{
	"channel" = "#channel"
	"icon_emoji" = ":fire:"
	"text" = "Hello there! I guess there's something wrong. Would you please mind checking the API system."
	"username" = "Mr. API System"
}
 
Invoke-RestMethod `
	-Body (ConvertTo-Json -Compress -InputObject $payload) `
    -Method Post `
    -ContentType 'application/json' `
	-Uri "https://hooks.collabservice.com/services/HOOK_API_SLUG" | Out-Null

The above script is picked from GitHub.

Here, payload is JSON code that defines the message body.
Payload may be simple or it may represent some complex information in tabular form as:

 
payload={
  "channel": "general",
  "username": "New Joinees",
  "icon_url": "https://www.collabservice.org/wp-content/uploads/2019/joinee.png",
  "text": "#### List of Joinees for August 3th, 2019\n<!channel> Please congratulate and welcome.\n
  | Name  | Department   | Experience                                   |
  |:-----------|:-----------:|:-----------------------------------------------|
  | Akhil     | DevOps         | 5                           |
  | Hitesh | HR         |  2                            |
  | Radhika | PM          |  6                            |
  "
  }

In order to create URI or Webhook, please follow the procedure below:
– Slack: https://get.slack.help/hc/en-us/articles/115005265063-Incoming-WebHooks-for-Slack
– Mattermost: https://docs.mattermost.com/developer/webhooks-incoming.html

The above mentioned method is one of the simplest ways to send message on Slack or Mattermost. However, there are many other methods too to achieve this task. Please refer the below links for the same.

http://ramblingcookiemonster.github.io/PSSlack/
https://www.powershellgallery.com/packages/Mattermost/1.0.1/Content/Mattermost.ps1