1

我已使用 Python 成功发布了警报帖子,但无法让我的 powershell 警报创建工作。我在回复中只收到了一堵 HTML 墙,没有创建警报。消息是唯一的必填字段。这是我正在使用的,但它不起作用

$api = "XXX"
$URI = "https://api.opsgenie.com/v2/alerts"
$head = @{"Authorization" = "GenieKey $api"}
$body = @{
            message = "testing";
            responders = 
                ]@{
                    name = "TEAMNAMEHERE";
                    type = "team"
                }]

        } | ConvertTo-Json

$request = Invoke-RestMethod -Uri $URI -Method Post -Headers $head -ContentType "application/json" -Body $body
$request

这是我制作的python代码,它工作得很好。

import requests
import json


def CreateOpsGenieAlert(api_token):
    header = {
        "Authorization": "GenieKey " + api_token,
        "Content-Type": "application/json"
    }

    body = json.dumps({"message": "testing",
                       "responders": [
                           {
                               "name": "TEAMNAMEHERE",
                               "type": "team"
                           }
                       ]
                       }
                      )
    try:
        response = requests.post("https://api.opsgenie.com/v2/alerts",
                                headers=header,
                                data=body)
        jsontemp = json.loads(response.text)
        print(jsontemp)

        if response.status_code == 202:
            return response
    except:
        print('error')

    print(response)


CreateOpsGenieAlert(api_token="XXX")

编辑:所以我发现它与我的“响应者”部分有关。它与 [ ]...有关,但我无法弄清楚到底是什么。如果我删除它们,它将无法正常工作。如果我把第一个转过来,它就行不通了。我可以获得成功创建的警报,但是我不断收到以下错误:

] : The term ']' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At \\file\Tech\user\powershell scripts\.not working\OpsGenieAlert.ps1:7 char:17
+                 ]@{
+                 ~
    + CategoryInfo          : ObjectNotFound: (]:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
4

1 回答 1

2

您需要将 $body 转换为 JSON

$api = "XXX"
$URI = "https://api.opsgenie.com/v2/alerts"
# Declare an empty array 
$responders = @()

# Add a new item to the array
$responders += @{
    name = "TEAMNAMEHERE1"
    type = "team1"
}
$responders += @{
    name = "TEAMNAMEHERE2"
    type = "team2"
}

$body = @{
    message    = "testing"
    responders = $responders
} | ConvertTo-Json

$invokeRestMethodParams = @{
    'Headers'     = @{
        "Authorization" = "GenieKey $api"
    }
    'Uri'         = $URI
    'ContentType' = 'application/json'
    'Body'        = $body
    'Method'      = 'Post'
}

$request = Invoke-RestMethod @invokeRestMethodParams
于 2020-02-14T08:14:27.850 回答