I am writing a powershell script to post a message to slack :
Param
(
[Parameter(Mandatory = $true)]$newrelicAppName,
[Parameter(Mandatory = $true)]$releasenumber,
[Parameter(Mandatory = $true)]$RequestedBy,
[Parameter(Mandatory = $true)]$SourceVersion
)
$uriSlack = "https://hooks.slack.com/services/MYDATA"
$jsonBase = @{}
$blocksList = New-Object System.Collections.ArrayList
$fieldsList = New-Object System.Collections.ArrayList
$Null = $fieldsList.Add(@{"type"="mrkdwn";"text"="*Release Number* $releasenumber";})
$Null = $fieldsList.Add(@{"type"="mrkdwn";"text"="*Requested By* $RequestedBy";})
$Null = $fieldsList.Add(@{"type"="mrkdwn";"text"="*Source Version* $SourceVersion";})
$textData = @{"type"="plain_text";"text"="Release completed for $($newrelicAppName)";}
$dividerData = @{"type"="divider";}
$Null = $blocksList.Add(@{"type"="header"; "text"=$textData})
$Null = $blocksList.Add(@{"type"="divider"})
$Null = $blocksList.Add(@{"type"="section"; "fields"=$fieldsList;})
$blocksList | ConvertTo-Json -Depth 4
$Null = $jsonBase.Add("blocks",$blocksList)
write-output $jsonBase.GetType()
try {
Invoke-RestMethod -uri $uriSlack -Method Post -body $jsonBase -ContentType 'application/json' | Out-Null
} catch {
Write-Output $_
Write-Error "Update to Slack went wrong..."
}
This currently returns a 400 message :
Invoke-RestMethod : The remote server returned an error: (400) Bad Request
And if I looks at the GetType() output, I can see that the $jsonBase is actually still a HashTable:
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Hashtable System.Object
I thought that adding the -Depth 4 to the conversion would fix this, but apparently not! If I copy the output of $jsonBase into postman and post the plain text, it works. So I know it is something to do with the generated JSON, and not the format of the message. Any ideas?
CodePudding user response:
You can explicitly convert the body payload to JSON by doing:
Invoke-RestMethod ... -Body ($jsonBase |ConvertTo-Json -Depth 4)