我正在写一个工作正常的Slack脚本从Bash到Powershell的翻译,但是我偶然发现了问题的实质。如何使用Invoke-WebRequest替换curl。
这是curl命令,可在* nix系统上的Bash中成功运行:
curl \
-X POST \
-H "Content-type: application/json" \
--data "{
\"attachments\":
[
{
\"mrkdwn_in\": [\"text\"],
\"color\": \"$COLOUR\",
\"text\": \"$MESSAGE\",
}
]
}" \
https://hooks.slack.com/services/tokenpart1/tokenpart2
请注意,$ COLOUR和$ MESSAGE变量是从脚本的其他位置派生的(不是我遇到问题的部分)。
我无法在PowerShell中使用它。到目前为止,我的翻译是:
$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
这将导致以下错误:
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
我在Powershell中几乎没有零经验。另外,由于此脚本必须能够放入各种盒子中,因此我不会使用任何库或自定义cmdlet或类似的东西。开箱即用的方法还是会死的。
由于ConvertTo-Json
无论如何都在使用,因此将整个输入构造为(嵌套的)自定义对象/哈希表更为简单,并ConvertTo-Json
处理所有JSON格式:
$Body = [pscustomobject] @{
attachments = , [pscustomobject] @{
mrkdwn_in = , 'text'
color = $Colour
text = $Message
}
}
$BodyJson = $Body | ConvertTo-Json -Depth 3
注意:您可以代替[ordered]
为[pscustomobject]
使用带有命令键代替了哈希表; 即使忽略其中任何一个都可以,尽管以不同顺序查看结果JSON中的条目可能会造成混淆。
请注意,使用,
数组构造运算符来确保将attachments
和mrkdwn_in
条目视为数组。
此外,由于ConvertTo-Json
仅完全序列化为默认的2
level深度,因此-Depth 3
必须使用确保输入的值mrkdwn_in
序列化为数组。
至于你尝试了什么:
你的眼前问题(除了缺少}
杰夫蔡特林在关于这个问题的评论所指出的):你已经忘了逃跑的嵌入式 "
字符。在您的多行字符串中。因此,正如文档主题所Get-Help about_Quoting_Rules
讨论的,您可以使用`"
嵌入双引号,也可以"..."
使用here-string(@"<nl>....<n>"@
)。
即使解决了语法问题,您的代码也无法按预期工作,因为ConvertTo-Json
不会在attachments
条目中保留预格式化的JSON,而是将字符串值视为需要转义的字符串文字。这是一个简单的例子:
@{
foo = "[
1,
2
]"
} | ConvertTo-Json
以上收益:
{
"foo": "[\n 1, \n 2 \n ]"
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句