Changing Slack CURL call into PowerShell - json

I've in the middle of writing a translation of a working Slack script from Bash to Powershell, and I'm stumbled on what is literally the meat of the problem; how to use Invoke-WebRequest to replace curl.
This is the curl command that works successfully in Bash on *nix systems:
curl \
-X POST \
-H "Content-type: application/json" \
--data "{
\"attachments\":
[
{
\"mrkdwn_in\": [\"text\"],
\"color\": \"$COLOUR\",
\"text\": \"$MESSAGE\",
}
]
}" \
https://hooks.slack.com/services/tokenpart1/tokenpart2
Note the $COLOUR and $MESSAGE variables are derived from elsewhere in the script (not the section I'm having trouble with).
I can't get it to work in PowerShell. My translation so far is:
$Body = #{
"attachments" = "[
{
"mrkdwn_in": ["text"],
"color": "$Colour",
"text": "$Message",
]"
}
$BodyJSON = $Body |convertto-JSON
Invoke-WebRequest -Headers -Method Post -Body "$BodyJSON" -Uri "https://hooks.slack.com/services/tokenpart1/tokenpart2" -ContentType application/json
This results in the following error:
At C:\path-to-file-etc.ps1:53 char:11
+ "mrkdwn_in": ["text"],
+ ~~~~~~~~~~~~~~~~~~~~~
Unexpected token 'mrkdwn_in": ["text"],
"color": "$COLOUR",
"text": "$MESSAGE",
}
]"' in expression or statement.
At C:\path-to-file-etc.ps1:53 char:11
+ "mrkdwn_in": ["text"],
+ ~
The hash literal was incomplete.At
C:\path-to-file-etc.ps1:53 char:11
+ "mrkdwn_in": ["text"],
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordEx
ception
+ FullyQualifiedErrorId : UnexpectedToken
Process exited with code 1
Process exited with code 1
Step Notify (PowerShell) failed
I have pretty much zero experience in Powershell. Also because this script has to be able to dropped onto a whole variety of boxes,I won't use any libraries or custom cmdlets or anything like that. Out of box methods or die.

Since you're using ConvertTo-Json anyway, it's simpler to construct the entire input as a (nested) custom object / hashtable, and let ConvertTo-Json handle all JSON formatting:
$Body = [pscustomobject] #{
attachments = , [pscustomobject] #{
mrkdwn_in = , 'text'
color = $Colour
text = $Message
}
}
$BodyJson = $Body | ConvertTo-Json -Depth 3
Note: You could substitute [ordered] for [pscustomobject] to use a hashtable with ordered keys instead; even omitting either would work, though seeing the entries in the resulting JSON in different order may be confusing.
Note the use of ,, the array-construction operator, to ensure that the attachments and mrkdwn_in entries are treated as arrays.
Additionally, since ConvertTo-Json only fully serializes to a default depth of 2 levels, -Depth 3 must be used to ensure that the value of entry mrkdwn_in is serialized as an array.
As for what you tried:
Your immediate problem (in addition to the missing } that Jeff Zeitlin points out in a comment on the question): You've neglected to escape the embedded " chars. in your multi-line string.
Therefore, as documentation topic Get-Help about_Quoting_Rules discusses, you can either use `" to embed double quotes inside "..." or use a here-string (#"<nl>....<n>"#).
Even with the syntax problems fixed, your code wouldn't work as intended, however, because ConvertTo-Json wouldn't preserve the pre-formatted JSON in the attachments entry and instead treat the string value as a string literal that needs escaping; here's a simple example:
#{
foo = "[
1,
2
]"
} | ConvertTo-Json
The above yields:
{
"foo": "[\n 1, \n 2 \n ]"
}

Related

Powershell Nested Json doesn't look like a Json

I am currently trying to prepare a JSON body for an API call, which should look something like this
curl -XPOST -H 'Authorization: Bearer ***API*KEY***' -H 'Content-Type: application/json' http://127.0.0.1:9000/api/alert -d '{
"title": "Other alert",
"description": "alert description",
"type": "external",
"source": "instance1",
"sourceRef": "alert-ref",
"severity": 3,
"tlp": 3,
"artifacts": [
{ "dataType": "ip", "data": "127.0.0.1", "message": "localhost" },
{ "dataType": "domain", "data": "thehive-project.org", "tags": ["home", "TheHive"] },
],
"caseTemplate": "external-alert"
}'
The problem however is that my json body which I create with powershell has weird characters and don't see where the problem is. This is my JSON Body
{
"tlp": 1,
"source": "Test",
"title": "Test Alert1",
"artifacts": "{\r\n \"dataType\": \"ip\",\r\n \"data\": \"127.0.0.1\"\r\n}",
"type": "external",
"sourceRef": "1",
"description": "Test",
"severity": 1
}
I create this JSON body as follows. I have already tried CustomObjects and Hashtables, but always get the same output
$body = #{
title = "$title"
description = "$Alert_Description"
type ="external"
source ="$Source"
sourceRef ="$SourceRef"
severity = $Severity
tlp = $tlp
$artifacts = [PSCustomObject]#{
dataType=ip
data=127.0.0.1}
}| ConvertTo-Json
$JsonBody = $body | ConvertTo-Json
Can somebody give me a hint? I have no clue anymore
First, fix your hashtable so that it creates the intended JSON representation, and only apply ConvertTo-Json once:
$body = [ordered] #{
title = $title
description = $Alert_Description
type = 'external'
source = $Source
sourceRef = $SourceRef
severity = $Severity
tlp = $tlp
artifacts = , [pscustomobject] #{
dataType = 'ip'
data = '127.0.0.1'
}
} | ConvertTo-Json
Variables don't need enclosing in "..." unless you explicitly want to convert their values to strings.
Literal textual information such as ip does require quoting ('...', i.e. a verbatim string literal, is best).
The artifacts property is an array in your sample JSON, so the unary form of ,, the array constructor operator is used to wrap the [pscustomobject] instance in a single-element array.
If you have multiple objects, place , between them; if the array was constructed previously and stored in a variable named, say, $arr, use artifacts = $arr.
Use of [ordered], i.e. the creation of an ordered hashtable isn't strictly necessary, but makes it easier to compare the resulting JSON representation to the input hashtable.
Generally keep in mind that explicit use of a -Depth argument with ConvertTo-Json is situationally required in order to ensure that properties aren't truncated - see this post for more information. However, with the hashtable in your question this happens not to be a problem.
Second, since you're sending the json to an external program, curl (note that in Windows PowerShell you'd have to use curl.exe in order to bypass the built-in curl alias for Invoke-WebRequest, an additional escaping step is - unfortunately - required up to at least v7.1 - though that may change in v7.2: The " instances embedded in the value of $body must manually be escaped as \", due to a long-standing bug in PowerShell:
curl -XPOST -H 'Authorization: Bearer ***API*KEY***' -H 'Content-Type: application/json' `
http://127.0.0.1:9000/api/alert -d ($body -replace '([\\]*)"', '$1$1\"')
Note: With your particular sample JSON, -replace '"', '\"' would do.
See this answer for more information.
Slap a "-Depth 50" on your ConvertTo-Json, that should solve your issue.
Like here: ConvertTo-Json flattens arrays over 3 levels deep

Powershell script Missingtypename

I am trying to make some API calls through powershell using this documentation
https://octopus.com/blog/manually-push-build-information-to-octopus
$Headers = #{"X-Octopus-ApiKey"=$MYKEY"}
$jsonBody = #{
PackageId = "Test"
Version = "1.1.1"
OctopusBuildInformation =
#{
BuildEnvironment = "Jenkins"
BuildNumber = "1"
BuildURL = "myURL"
VcsCommitNumber = "250"
VcsType = "Git"
Commits = [{Id = "250" LinkUrl = "gitUrl" Comment = "someComment"}]
VcsRoot = "gitUrl"
}
} | ConvertTo-Json -Depth 5
Invoke-RestMethod -Method Post -Uri "http://alfadeployment/api/build-information" -Headers $Headers -Body $jsonBody
However, since I added the commits array, I am getting the following error:
Missing type name after '['.
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : MissingTypename
PowerShell arrays aren't enclosed in [...] - the latter is used for type literals, i.e. to refer to .NET types - hence the error message.
You may - but don't have to - enclose PowerShell arrays in #(...), the array-subexpression operator; using ,, the array constructor operator is enough, though #(...) can be helpful for visual clarity, and to create an empty (#()) or single-element arrays (#('foo')), which is perhaps clearer than the unary use of , (, 'foo')).
Additionally, the array element in your case must be a hashtable too (#{ ... }, not { ... }, the latter is a script block), and, given that the property definitions are on the same line, they must be ;-separated.
To put it all together:
Commits = #(
#{ Id = "250"; LinkUrl = "gitUrl"; Comment = "someComment" }
)

Parse value from JSON when key contains dot (period) in Powershell

In the above example, I would like to get the value "Bug" from "System.WorkItemType"
using
$response = Invoke-RestMethod -Url $someUri -Method Get -ContentType "application/json" -Headers $headers
$wit = response.fields.System.WorkItemType
doesn't work since the dot / period messes it up.
In javascript there is this question and answer but did not work in Powershell.
Using regex to replace the dot with underscore seems too farfetched (and I didn't get it to work, but used -match -convertFrom-Json -replace -convertTo-Json so maybe did it wrong?
So my question is simply: How do I get the 'Bug' value from the 'System.WorkItemType' key? (bug may be other strings...)
If you put the property names in "" or '', you should be able to get what you are looking for:
$json= #'
{ "id" : 9983,
"rev" : 17,
"fields" :{
"System.AreaPath":"Cloud\\Dev Blue Team",
"System.TeamProject":"Cloud"
}
}
'#
$j = $Json | convertfrom-json
$j.fields."System.AreaPath"
$J.fields.'System.TeamProject'
if you need to escape double quotes, use the ` grave accent, known as the backtick in PowerShell.
"area path = $($j.fields.`"System.AreaPath`")"

Powershell & Curl - Using variables inside single-quoted JSON body

I am currently trying to automate new user creation in our Zendesk ticketing system using Powershell and Curl. The problem I am running into is that the curl json body is enclosed by single quotes and I need to reference a variable inside that body. Here is what I have:
$Firstname = "Test"
$Lastname = "User"
$email= 'user#test.org'
curl.exe https://mydomain.zendesk.com/api/v2/users.json -H "Content-Type: application/json" -X POST -d '{\"user\": {\"name\": \"$Firstname $Lastname\", \"email\": \"$email\"}}' -v -u myuser:mypass
This works fine if I type in regular text values inside the json, but how can I get it to recognize the variables $Firstname, $Lastname and $email?
Try the following:
$Firstname = "Test"
$Lastname = "User"
$email= 'user#test.org'
$json=#"
{\"user\": {\"name\": \"$Firstname $Lastname\", \"email\": \"$email\"}}
"#
curl.exe https://mydomain.zendesk.com/api/v2/users.json -d $json -H 'Content-Type: application/json' -X POST -v -u myuser:mypass
Using a double-quoted here-string #"<newline>...<newline>"# makes specifying embedded " instances easy (no escaping for the sake of PowerShell's own syntax required), while still expanding variable references - see the docs online or Get-Help about_Quoting_Rules.
You're clearly aware of the - unfortunate - additional need to \-escape the " instances, but just to explain why that is needed:
When passing arguments to an external program, PowerShell, after its own parsing and interpolation, conditionally wraps the resulting arguments in double quotes when concatenating them to form the argument list (a single string) to pass to the external utility. Unfortunately, this can result in embedded " instances getting discarded, and the only way to preserve them reliably is to \-escape them - see this answer for more information.
If you wanted to do it inline with a regular double-quoted string, you'd have to escape the " instances for PowerShell too (as `"), resulting in the awkward combination \`":
"{\`"user\`": {\`"name\`": \`"$Firstname $Lastname\`", \`"email\`": \`"$email\`"}}"
Afterthought:
Ryan himself points out in a comment that using a hashtable to construct the data and then converting it to JSON with ConvertTo-Json and feeding it to curl via stdin is an alternative that avoids the quoting headaches:
# Create data as PS hashtable literal.
$data = #{ user = #{ name = "$Firstname $Lastname"; email = "$adUsername#mydomain.org" } }
# Convert to JSON with ConvertTo-Json and pipe to `curl` via *stdin* (-d '#-')
$data | ConvertTo-Json -Compress | curl.exe mydomain.zendesk.com/api/v2/users.json -d '#-' -H "Content-Type: application/json" -X POST -v -u myuser:mypass
I think we can use here-string as json body for Invoke-RestMethod as below
$bufferTime = 5
$requestBody = #"
{
"size": 0,
"aggs": {
"last_x_min": {
"filter": {
"range": {
"#timestamp": {
"gte": "now-$($bufferTime)m",
"lte": "now"
}
}
},
"aggs": {
"value_agg": {
"avg": {
"field": "time-taken"
}
}
}
}
}
}
"#
$esResponse = Invoke-RestMethod -URI http://locahost:9200 -TimeoutSec 15 -Method Post -ContentType 'application/json' -Body $requestBody
This is the script I use to query Elasticsearch. No need to escape double quotes.

"Invalid array passed" when parsing JSON

I have this file which I want to read with PowerShell:
var myMap =
[
{
"name": "JSON Example",
"attr": "Another attribute"
}
]
My PowerShell v3 Code:
$str = Get-Content $file | Select -Skip 1;
$str | ConvertFrom-Json;
But I'm always getting this error:
ConvertFrom-Json : Invalid array passed in, ']' expected. (1): [
At S:\ome\Path\script.ps1:60 char:8
+ $str | ConvertFrom-Json;
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [ConvertFrom-Json], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.ConvertFromJsonCommand
If I copy and paste the JSON code manually into the code, everything is working fine:
'[
{
"name": "JSON Example",
"attr": "Another attribute"
}
]' | ConvertFrom-Json;
Try to pipe to Out-String before piping to ConvertFrom-Json:
Get-Content $file | Select -Skip 1 | Out-String | ConvertFrom-Json
In your working example the JSON code is a string while the non-working example returns a collection of lines. Piping to Out-String converts the collection to a single string, which is what the InputObject parameter accept.
Alternatively you can use Get-Content -Raw which will retrieve the JSON as a single string.
See this post for more info: http://blogs.technet.com/b/heyscriptingguy/archive/2014/04/23/json-is-the-new-xml.aspx
The var myMap = isn't json, it's javascript. Delete the first line and it will be fine.
EDIT:
Oh, you are skipping the first line. It may be that there's a carriage return missing in the last line of the file, and Powershell 3 is more sensitive to it. It works fine in Powershell 5.1 even without a carriage return at the end.
another answer that also works: use GC -raw <FILE> which will pass in as string