Invoke-RESTMethod PowerShell

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Invoke-RESTMethod PowerShell相关的知识,希望对你有一定的参考价值。

我正在尝试使用Invoke-Rest方法来调用一组API,但它失败并出现以下错误,我也发布了相同的json格式,有些人可以让我知道可能出错吗?

    ### Ignore TLS/SSL errors
add-type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}}
"@

[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12


#Create URL string for Invoke-RestMethod
$urlsend = 'https://' + 'vrslcm-01a.corp.local/lcm/api/v1/' + '/login'


#Credential

$Username = "admin@localhost"
$password = "VMware1!"

$basicAuth = "Basic " + [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("$($Username):$Password"))
    $headers = @{

        "description"= "Testing Authentication"
    }

    $body = @{
                    $raw= '{
	"username": "admin@localhost",
	"password": "vmware"
}'
                    "mode"= $raw
            }

Invoke-RestMethod -Method POST -uri $urlsend -Headers $headers -Body $body -ContentType 'application/json'

enter image description here

这是我试图通过powershell调用的示例jSON,它由标题和正文组成。我需要了解如何通过PowerShell Invoke-RestMethod调用相同的jSON POSTMAN示例

"item": [
        {
            "name": "authorization",
            "description": "",
            "item": [
                {
                    "name": "Login",
                    "event": [
                        {
                            "listen": "test",
                            "script": {
                                "type": "text/javascript",
                                "exec": [
                                    "var response=JSON.parse(responseBody)",
                                    "postman.setEnvironmentVariable("token", response.token)"
                                ]
                            }
                        }
                    ],
                    "request": {
                        "url": "{{Server}}/lcm/api/v1/login",
                        "method": "POST",
                        "header": [
                            {
                                "key": "Content-Type",
                                "value": "application/json",
                                "description": ""
                            }
                        ],
                        "body": {
                            "mode": "raw",
                            "raw": "{
	"username": "admin@localhost",
	"password": "vmware"
}"
                        },
                        "description": ""
                    },
                    "response": []
                },
                {
                    "name": "Logout",
                    "request": {
                        "url": "{{Server}}/lcm/api/v1/logout",
                        "method": "POST",
                        "header": [
                            {
                                "key": "x-xenon-auth-token",
                                "value": "{{token}}",
                                "description": ""
                            }
                        ],
                        "body": {},
                        "description": ""
                    },
                    "response": []
                }
            ]
        },
答案

$raw变成哈希表

$raw = @{
    username=$Username
    password=$Password
}

将此哈希表添加到$body哈希表中

$body = @{         
    mode= $raw
}

但现在它仍然是api无法使用的哈希表。因此将其转换为json就好

$jsonBody = $body | ConvertTo-Json

使用$jsonBody然后应该像使用时一样工作

Invoke-RestMethod -Method POST -uri $urlsend -Headers $headers -Body $jsonBody -ContentType 'application/json'
另一答案

与错误状态一样,问题是您的哈希定义。

散列字面值中不允许使用null键。

PowerShell尝试将$ raw评估为hash table密钥。因为它在null之前尚未定义并且因为不允许null而失败。试试这样:

$raw= '{
	"username": "admin@localhost",
	"password": "vmware"
}'

$body = @{         
    "mode"= $raw
}

以上是关于Invoke-RESTMethod PowerShell的主要内容,如果未能解决你的问题,请参考以下文章

无法使用 Invoke-RestMethod 更新工作项历史记录

Invoke-RESTMethod PowerShell

格式化 Invoke-RestMethod 或 ConvertFrom-Json 返回的 [pscustomobject] 实例

用于排队构建的Invoke-RestMethod的Body需要包含什么? [重复]

Powershell Invoke-Restmethod不能将生成的Authtoken用作变量

powershell 使用REST-API的PowerShell V3 Multipart / formdata示例(Invoke-RestMethod)