【发布时间】:2018-08-09 23:00:03
【问题描述】:
我正在编写一个从 Bash 到 Powershell 的工作 Slack 脚本的翻译,我偶然发现了问题的实质;如何使用 Invoke-WebRequest 替换 curl。
这是在 *nix 系统上的 Bash 中成功运行的 curl 命令:
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 或类似的东西。开箱即用的方法或死。
【问题讨论】:
-
这是一个语法错误;您在附件中的
]之前缺少}。 -
我知道不需要库,但自定义 cmdlet 与脚本代码没有什么不同...您可以添加一个函数或类似的东西。
标签: json powershell curl slack-api