通过 PowerShell 使用 REST API 创建 JIRA 问题

Create JIRA Issue with REST API via PowerShell

我正在尝试通过 Powershell 创建 JIRA 问题。

这是我的代码。

function ConvertTo-Base64($string) {
$bytes  = [System.Text.Encoding]::UTF8.GetBytes($string);
$encoded = [System.Convert]::ToBase64String($bytes);
return $encoded;
}

function Get-HttpBasicHeader([string]$username, [string]$password, $Headers = @{}) {
    $b64 = ConvertTo-Base64 "$($username):$($Password)"
    $Headers["Authorization"] = "Basic $b64"
    $Headers["X-Atlassian-Token"] = "nocheck"
    return $Headers
}

$restapiuri = "https://baseurl/rest/api/2/issue/"
$headers = Get-HttpBasicHeader "user" "password"

$body = ('
{
    "fields":
    {
        "project":
        {
            "id": "10402"
        },

        "summary": "Test",

        "description": "Test",

        "duedate": "2019-05-11",

        "issuetype":
        {
            "id": "3"
        },

        "reporter":
        {
            "name": "user"
        },

        "priority":
        {
            "id": "10101"
        },

        "customfield_11403": "Test",

        "security":
        {
            "id": "11213"
        },

        "components":
        [
            {           
                "id": "10805"
            }
        ]
    }
}')

Invoke-RestMethod -uri $restapiuri -Headers $headers -Method POST -ContentType "application/json" -Body $body

它的 JSON 部分运行良好,因为我使用 Postman 尝试过它并且问题已创建。

但是,在 Powershell 中,我总是返回 400 错误请求。有人知道为什么会这样吗?

谢谢!

编辑:根据答案的代码示例

$body = @{

    "fields" = @{

        "project" = @{

            "id" = "10402";
        }

        "summary" = "Test";

        "description" = "Test";

        "duedate" = "2019-05-11";

        "issuetype" = @{

            "id" = "3";
        }

        "reporter" = @{

            "name" = "user";
        }

        "priority" = @{

            "id" = "10101";
        }

        "customfield_11403" = "Test";

        "security" = @{

            "id" = "11213";
        }
    }
}

使用 Invoke-RestMethod 来使用 REST-API。将 JSON 保存为字符串并将其用作正文, 例如:

$body = @'
{
    "fields":
    {
        "project":
        {
            "id": "10402"
        },

        "summary": "Test",

        "description": "Test",

        "duedate": "2019-05-11",

        "issuetype":
        {
            "id": "3"
        },

        "reporter":
        {
            "name": "user"
        },

        "priority":
        {
            "id": "10101"
        },

        "customfield_11403": "Test",

        "security":
        {
            "id": "11213"
        },

        "components":
        [
            {           
                "id": "10805"
            }
        ]
    }
}
'@

Invoke-RestMethod -uri $restapiuri -Headers $headers -Method POST -ContentType "application/json" -Body $body

问题来了。

$restapiuri = "https://baseurl/rest/api/2/issue/"

应该是

$restapiuri = "https://baseurl/rest/api/2/issue"

经过这一改,终于成功了!额外的 / 是 PowerShell 似乎不喜欢的东西:)