Functions/Submit-SlackMessage.ps1
<#
.SYNOPSIS This function posts a message to a channel in Slack. .DESCRIPTION This function posts a message to a channel in Slack. #> function Submit-SlackMessage { [CmdletBinding(PositionalBinding=$false)] [OutputType([Bool])] param( # The authentication token for Slack [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$token, # The name of the channel [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$channelName, # The message to post [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$message, # Select the stream where the messages will be directed. [Parameter(Mandatory=$false)] [ValidateSet("Information", "Warning", "Error", "None")] [String]$outputStream = "Error" ) # Convert channel name to ID and verifies the channel exists $channelID = (Get-SlackChannel -Token $token -ChannelName $channelName).id if (!$channelID) { Write-OutputMessage "The channel '$($channelName)' cannot be found in Slack." -OutputStream $outputStream -ReturnMessage:$false return $false } # Prepare the API call parameters $invokeRestMethodParams = @{ Uri = "https://slack.com/api/chat.postMessage" Method = "POST" Headers = @{ "Content-Type" = "application/json" Authorization = "Bearer $($token)" } Body = @{ "channel" = "$($channelID)" "text" = "$($message)" } | ConvertTo-Json } # Try to post the message try { $response = Invoke-RestMethod @invokeRestMethodParams } catch { Write-OutputMessage "Exception occurred while posting message '$($message)' to '$($channelName)'.`r`n$($_.Exception.Message)" -OutputStream $outputStream -ReturnMessage:$false return $false } # Verify that the message is post if ($response.ok) { Write-Information "Message '$($message)' was post to '$($channelName)'." return $true } else { Write-OutputMessage "Failed to post message '$($message)' to channel '$($channelName)' with the error message:`r`n$($response.error)." -OutputStream $outputStream -ReturnMessage:$false return $false } } |