在Powershell中,我可以做这种命令。但是,如何获得一些返回值以验证此调用是否成功失败?
我想要一些返回结果并检查执行类似的任务
$url = ("http://localhost:5000", $path -join "")
Invoke-RestMethod -Method Get -Uri $url -Headers $bearerHeader
或者,
Invoke-RestMethod -Method Post -Uri $url -ContentType "application/json" -Body $bod
如果我能得到一些回报,我可以这样做: -
if($resp -eq $false)
{
Write-Host "Failed to upload file:" $upload.GetPath() -ForegroundColor "Red";
return;
}
答案 0 :(得分:2)
Invoke-RestMethod
目前不会返回Invoke-WebRequest
之类的响应代码。您可以改为使用Invoke-WebRequest
,也可以使用Try..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";
}
从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}