如何通过电源外壳 Invoke-RestMethod 获取返回值

mas*_*boo 1 powershell return-value

在 Powershell 中,我可以执行这种命令。但是我怎样才能得到一些返回值来验证这个调用是否成功?

我想要一些返回结果并检查做类似的任务

$url = ("http://localhost:5000", $path -join "")
Invoke-RestMethod -Method Get -Uri $url -Headers $bearerHeader
Run Code Online (Sandbox Code Playgroud)

或者,

Invoke-RestMethod -Method Post -Uri $url  -ContentType "application/json" -Body $bod
Run Code Online (Sandbox Code Playgroud)

如果我能得到一些回报,我可以做这样的事情:-

if($resp -eq $false)
{
   Write-Host "Failed to upload file:" $upload.GetPath() -ForegroundColor "Red";
    return;
}   
Run Code Online (Sandbox Code Playgroud)

Mar*_*agg 5

Invoke-RestMethod当前不会像Invoke-WebRequest这样返回响应代码。您可以Invoke-WebRequest改用,也可以使用 aTry..Catch来测试异常:

Try {
    Invoke-RestMethod -Method Post -Uri $url  -ContentType "application/json" -Body $bod -ErrorAction Stop
} Catch {
    Write-Host "Failed to upload file:" $upload.GetPath() -ForegroundColor "Red";
}
Run Code Online (Sandbox Code Playgroud)

从 PowerShell 6 (Core) 开始,即使连接成功,您也可以通过该-ResponseHeaderVariable参数Invoke-RestMethod获取数据,即使响应为空。

例如:

~\Documents> Invoke-RestMethod http://xkcd.com/info.0.json -ResponseHeadersVariable Response

~\Documents> $Response

Key            Value
---            -----
Cache-Control  {max-age=300}
Connection     {keep-alive}
Date           {Fri, 12 Jan 2018 17:24:30 GMT}
Via            {1.1 varnish}
Accept-Ranges  {bytes}
Age            {115}
ETag           {"5a5846d2-1a9"}
Server         {nginx}
Vary           {Accept-Encoding}
X-Served-By    {cache-lhr6327-LHR}
X-Cache        {HIT}
X-Cache-Hits   {1}
X-Timer        {S1515777871.992127,VS0,VE3}
Content-Length {425}
Content-Type   {application/json}
Expires        {Fri, 12 Jan 2018 05:31:14 GMT}
Last-Modified  {Fri, 12 Jan 2018 05:25:38 GMT}
Run Code Online (Sandbox Code Playgroud)