代码之家  ›  专栏  ›  技术社区  ›  Scott Shorkey

将Slack CURL调用更改为PowerShell

  •  0
  • Scott Shorkey  · 技术社区  · 6 年前

    我正在编写一个从Bash到Powershell的工作松弛脚本的翻译,我无意中发现了问题的实质;如何使用Invoke WebRequest替换curl。

    这是在Bash on*nix系统中成功运行的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
    

    请注意,$COLOR和$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或类似的东西。 开箱即用的方法或模具。

    1 回复  |  直到 6 年前
        1
  •  1
  •   mklement0    6 年前

    因为你正在使用 ConvertTo-Json 不管怎样 构造更简单 全部的 作为(嵌套的)自定义对象/哈希表输入,并让 转换为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 条目被视为数组。

    此外,自 转换为Json 仅完全序列化到默认深度 2 水平 , -Depth 3 必须用于确保输入的值 mrkdwn\U输入 被序列化为数组。


    至于 你尝试了什么 :

    你的 立即的 问题 (除了失踪的 } Jeff Zeitlin在对该问题的评论中指出): 你忘了 逃跑 这个 嵌入的 " 查尔斯。 在多行字符串中。 因此,作为文档主题 Get-Help about_Quoting_Rules 讨论,您可以使用 `" 在内部嵌入双引号 "..." 或使用此处字符串( @"<nl>....<n>"@ ).

    即使修复了语法问题,代码也无法按预期工作 然而,因为 转换为Json 不会保留 预格式化 JSON 附件 输入,而将字符串值视为字符串 字面意义的 需要逃离;下面是一个简单的例子:

    @{ 
        foo = "[
          1, 
          2 
        ]"
     } | ConvertTo-Json
    

    上述收益率:

    {
      "foo": "[\n    1, \n    2 \n   ]"
    }