使用CURL脚本进行Powershell

时间:2019-02-12 21:40:52

标签: json powershell curl

我正在尝试使用Invoke-RestMethod将curl转换为powershell进行单信号推送

用于onesignal的脚本:

curl --include \
     --request POST \
     --header "Content-Type: application/json; charset=utf-8" \
     --header "Authorization: Basic YOUR_REST_API_KEY" \
     --data-binary "{\"app_id\": \"YOUR_APP_ID\",
\"contents\": {\"en\": \"English Message\"},
\"included_segments\": [\"Subscribed Users\"]}" \
     https://onesignal.com/api/v1/notifications

我尝试了下面的示例,但我没有成功。

   $uri = "https://onesignal.com/api/v1/notifications"
      $parameters = @{
        app_id = 'YOUR_APP_ID'
        contents = "en: English Message"
        included_segments = 'Subscribed Users'
        data = 'foo:bar'
      }
      $parameters | Invoke-RestMethod -Uri $uri -Method Post

我已经使用了该powershell脚本进行了推送,效果很好,但是现在我想转到onesignal,并且在已经使用app_id将消息推送给用户的情况下,我在哪里/如何将其余api密钥放入内部存在问题。

该代码从以下位置抢夺:https://documentation.onesignal.com/v5.0/reference#section-example-code-create-notification

我希望有人可以帮助我解决这个问题。

致谢

2 个答案:

答案 0 :(得分:1)

我不知道该端点如何工作,但它应该像这样工作:

$key = "Basic RESTAPIKEY"
$headers = @{}
$headers.Add("Authorization",$Key)
$headers.Add("Content-Type","application/json; charset=utf-8")

$uri = "https://onesignal.com/api/v1/notifications"
$parameters = @{
    app_id = 'YOUR_APP_ID'
    contents = "en: English Message"
    included_segments = 'Subscribed Users'
    data = 'foo:bar'
} | ConvertTo-Json

Invoke-RestMethod -Uri $uri -Method Post -Headers $headers -Body ([System.Text.Encoding]::UTF8.GetBytes($parameters)) -ContentType "application/json"

如果数据二进制文件是通过PowerShell发送的,则还可以使用Invoke-RestMethod中的-InFile参数。

如果只是稍微阅读一下您发布的链接,并认为正文部分应如下所示:

$parameters = @{
    app_id = "5eb5a37e-b458-11e3-ac11-000c2940e62c"
    included_segments = "Array of active users"
    data = @{
        foo = "bar"
    }
    contents = @{
        en = "English Message"
    }
} | ConvertTo-JSON

答案 1 :(得分:1)

尝试以下

$basicAuth = "Basic REST_API_KEY";
$headers = @{ Authorization = $basicAuth };
$uri = "https://onesignal.com/api/v1/notifications";
$body = @{ app_id = 'YOUR_APP_ID'; contents = @{ en = 'English Message' }; included_segments = @('Subscribed Users'); data = @{ foo = 'bar' }} | ConvertTo-Json;

Invoke-RestMethod -Method Post -Uri $uri -Headers $headers -ContentType "application/json; charset=utf-8" -Body ([System.Text.Encoding]::UTF8.GetBytes($body));